From 415e67998566af364ef337050162118edd7de87a Mon Sep 17 00:00:00 2001 From: TheAnimatrix Date: Mon, 30 Nov 2026 03:18:37 +0530 Subject: [PATCH 01/15] feat(tools): subagents hold what their parent holds; the person-only capability is gone Subagents now list and call the theme and quick-action tools, wakes, question_ask, secret_request, secret_run, the task tools, dev GUI tools, applets, computer_use_request and report_bug. thread_archive no longer needs a turn a person started, and a subagent may archive its own thread. thread_fork starts from any thread the agent may read. No Mousse tool needs a turn a person started any more, so the person capability, its provenance reads and its refusal are removed. --- src/mms/orchestrator/OrchestratorService.ts | 90 +++------------------ src/mms/run/mcp/appTools/appearance.ts | 4 +- src/mms/run/mcp/appTools/askUser.ts | 13 +-- src/mms/run/mcp/appTools/authority.ts | 86 +++----------------- src/mms/run/mcp/appTools/bugReports.ts | 4 +- src/mms/run/mcp/appTools/computer.ts | 10 +-- src/mms/run/mcp/appTools/devGui.ts | 4 +- src/mms/run/mcp/appTools/host.ts | 10 +-- src/mms/run/mcp/appTools/index.ts | 3 +- src/mms/run/mcp/appTools/quickActions.ts | 4 +- src/mms/run/mcp/appTools/registry.ts | 40 ++------- src/mms/run/mcp/appTools/schedules.ts | 10 --- src/mms/run/mcp/appTools/secrets.ts | 9 +-- src/mms/run/mcp/appTools/tasks.ts | 4 +- src/mms/run/mcp/appTools/thread.ts | 36 +++++---- src/mms/run/mcp/appTools/threadWakes.ts | 18 ++--- src/mms/run/mcp/appTools/types.ts | 15 +--- src/mms/run/mcp/instructions.ts | 2 +- src/mms/run/nativeHelpers.ts | 10 +-- tests/wakes/threadWakeTools.test.ts | 12 +-- 20 files changed, 90 insertions(+), 294 deletions(-) diff --git a/src/mms/orchestrator/OrchestratorService.ts b/src/mms/orchestrator/OrchestratorService.ts index 74edd49c61..f81c2dbbc7 100644 --- a/src/mms/orchestrator/OrchestratorService.ts +++ b/src/mms/orchestrator/OrchestratorService.ts @@ -115,7 +115,7 @@ import type { MonitorSummary, ThreadMonitors } from '../monitors/ThreadMonitors' import type { ThreadWakes } from '../wakes/ThreadWakes' import { PROVIDER_BACKGROUND_ID, type ThreadBackgroundWork } from '../../shared/backgroundWork' import { oneLineLabel, type ArchiveBlocker, type ArchiveBlockerKind } from '../../shared/archiveBlockers' -import { agentMessage, AppToolTurns, createAppToolRegistry, holdsPerson, type AgentAccessResult, type LacksReport, McpToolError, type BotAppToolDeps, type BotMemoryToolHost, type AgentApprovalResult, type AgentArchiveResult, type AgentArchiveOwnResult, type AgentCreatedThread, type AgentRemoteThreadRequest, type AgentRemoteThreadResult, type RemoteProjectCandidate, type AgentQueueCommand, type AgentQueueResult, type AgentScheduleHost, type AgentRunCommandResult, type AgentSendResult, type AgentThreadRequest, type ApprovalRequestInfo, type AppToolHost, type RemoteThreadsHost, type AppToolTurn, type McpCaller, type QueueSnapshot, type ToolRegistry, userMcpProxy } from '../run/mcp/appTools' +import { agentMessage, AppToolTurns, createAppToolRegistry, type AgentAccessResult, type LacksReport, McpToolError, type BotAppToolDeps, type BotMemoryToolHost, type AgentApprovalResult, type AgentArchiveResult, type AgentArchiveOwnResult, type AgentCreatedThread, type AgentRemoteThreadRequest, type AgentRemoteThreadResult, type RemoteProjectCandidate, type AgentQueueCommand, type AgentQueueResult, type AgentScheduleHost, type AgentRunCommandResult, type AgentSendResult, type AgentThreadRequest, type ApprovalRequestInfo, type AppToolHost, type RemoteThreadsHost, type AppToolTurn, type McpCaller, type QueueSnapshot, type ToolRegistry, userMcpProxy } from '../run/mcp/appTools' import { AGENT_THREAD_COMMAND, AGENT_THREAD_CREATED_ACTION, AGENT_THREAD_REPAIR_WINDOW_MS, agentThreadFingerprint, readAgentThreadReceipt, type AgentThreadIntent } from './agentThreadIntent' import { AGENT_QUEUE_MAX_PER_SENDER, AGENT_QUEUE_MAX_PER_THREAD, AGENT_REPEAT_WINDOW_MS, botRequestPrefix, lineageRelation } from '../run/mcp/appTools/thread' import { botMessage } from '../run/mcp/appTools/agentMessage' @@ -4888,9 +4888,8 @@ export class OrchestratorService extends EventEmitter { } /** - * What a job created or changed by an agent's run may run in: the permission mode the run is bound to. A run that is - * not a person's turn (a remote turn, a bot, a scheduled run, a workflow or a definition) gets the narrowest, and so - * does any run whose origin cannot be read, so a job made by an unattended agent is never wider than that agent was. + * What a job created or changed by an agent's run may run in: the permission mode the run is bound to, whoever + * started it, so a job is never wider than the agent that made it. */ private scheduledCreatorLimits(caller: { threadId: string; runId: string }): { permissionCeiling: PermissionMode; heldTo?: ScheduledJobHeldTo } { // The owner's bot ("schedule work in your threads") makes jobs as it starts threads: in Full access, or no wider than @@ -4908,45 +4907,7 @@ export class OrchestratorService extends EventEmitter { } return { permissionCeiling: owned ? owned.limit ?? 'full' : 'ask', ...(owned && heldTo ? { heldTo } : {}) } } - return { permissionCeiling: this.runStartedByPerson(caller) ? this.runPermissionMode(caller.runId) : 'ask' } - } - - /** - * Whether a person started the run: the run's source and its binding's origin say so (`startedByPerson`, the rule that - * decides who a standing approval rule may answer). Fails closed on a missing run, a missing binding, a bot's thread - * and anything that cannot be read. - */ - private runStartedByPerson(caller: { threadId: string; runId: string }): boolean { - try { - if (this.botThreads?.roleOf(caller.threadId)) return false - const engine = this.runEngine - // A subagent has what its parent has: a subagent of a person's turn (or of one of its subagents) counts as that turn. - const root = this.delegationRootOf(caller.runId) - const run = root ? engine?.getRun(root) : undefined - if (run && run.threadId !== caller.threadId && this.botThreads?.roleOf(run.threadId)) return false - const binding = root ? engine?.bindingForRun(root) : undefined - // Provenance the run cannot show (no run or no binding) holds no person authority. - return holdsPerson(run && binding ? { origin: policyOrigin(binding.policy), source: run.source } : undefined) - } catch { - return false - } - } - - /** - * Whether the run holds `person` (docs/plans/tool-api.md §1.3 "Provenance"): a person started this run itself, and its - * thread is neither a subagent (`person` never passes down) nor a bot's. Fails closed on anything that cannot be read. - */ - private runHoldsPerson(caller: { threadId: string; runId: string }): boolean { - try { - const engine = this.runEngine - if (!engine || this.botThreads?.roleOf(caller.threadId)) return false - if (engine.delegations.getLineage(caller.threadId)?.relationship === 'subagent') return false - const run = engine.getRun(caller.runId) - const binding = engine.bindingForRun(caller.runId) - return run?.threadId === caller.threadId && holdsPerson(binding ? { origin: policyOrigin(binding.policy), source: run.source } : undefined) - } catch { - return false - } + return { permissionCeiling: this.runPermissionMode(caller.runId) } } /** The delegation tools of an in-process turn, holding the grant its registered turn was given at its start. */ @@ -5268,8 +5229,6 @@ export class OrchestratorService extends EventEmitter { readOnlyThread: (threadId) => this.isReadOnlyChild(threadId), projectPathFor: (threadId) => this.getOrCreateSession(threadId).projectCwd ?? undefined, subagentThread: (threadId) => this.isSubagentThread(threadId), - // `person` (§1.3): a person started the run, and it is not a subagent's (which has what its parent has, but never this). - personHeld: (caller) => this.runHoldsPerson(caller), parentThread: (threadId) => this.subagentParentOf(threadId), reportLacks: (report) => this.reportSubagentLacks(report), // Only a bot's threads list the bot tools (`permission_ask`; `consult` on its activation thread). @@ -6867,7 +6826,7 @@ export class OrchestratorService extends EventEmitter { } /** - * `thread_archive` of another thread: an agent's turn the person started, or the owner's bot from its chat in a turn + * `thread_archive` of another thread: any agent's turn, or the owner's bot from its chat in a turn * that may act on threads (`botSenderOf`), archives or unarchives it through the app's own Archive (`archiveThread`). An * agent's archive never ends work: a thread an Archive would stop something in (`archiveBlockers`), there or in a * subagent below it, is refused with what that is (`thread_running` while a run works or is paused, else @@ -6876,9 +6835,8 @@ export class OrchestratorService extends EventEmitter { */ private async setThreadArchivedAsAgent(threadId: string, archived: boolean, options: { actor: AgentActor; clientRequestId: string }): Promise { const engine = this.requireRunEngine() - // The registry checked `person` (or the bot's grant) before the call; checked again here, where it acts. - if (!this.runHoldsPerson(options.actor) && !this.botSenderOf(options.actor, 'thread_archive')) - throw new McpToolError('mousse_scope_denied', 'Only a turn the user started, or a bot\'s with "use your threads", archives another thread.') + // A bot's grant was checked before the call; checked again here, where it acts (it throws for a bot that may not). + this.botSenderOf(options.actor, 'thread_archive') const thread = this.threadStore?.getThread(threadId) let botThread = false try { @@ -6978,11 +6936,11 @@ export class OrchestratorService extends EventEmitter { } /** - * `thread_archive` from a thread's own agent: the person asked it to archive its thread when done. A turn - * cannot archive the thread it runs in, so the request is kept with the run and done when that turn ends well - * (`archiveAfterTurnEnds`). Only the thread's own top-level turn that a person started: never a subagent, a bot's - * thread, or a turn another agent's message started. Refused, with what it is, while the archive would stop something - * besides the calling turn (`archiveBlockers`): the agent stops it first, or tells the person. + * `thread_archive` from a thread's own agent, subagents included: it archives its thread when done. A turn cannot + * archive the thread it runs in, so the request is kept with the run and done when that turn ends well + * (`archiveAfterTurnEnds`). Only the thread's running turn, and never a bot's thread. Refused, with what it is, while + * the archive would stop something besides the calling turn (`archiveBlockers`): the agent stops it first, or tells + * the person. */ private archiveOwnThreadAfterTurn(options: { actor: AgentActor }): AgentArchiveOwnResult { const engine = this.requireRunEngine() @@ -6995,10 +6953,8 @@ export class OrchestratorService extends EventEmitter { botThread = true } if (!thread || botThread) throw new McpToolError('mousse_scope_denied', 'thread_archive is not available in this thread.') - if (thread.lineage?.relationship === 'subagent') return { status: 'rejected', reason: 'subagent' } if (thread.archivedAt) return { status: 'accepted', changed: false } if (engine.getActiveRun(threadId)?.runId !== runId) return { status: 'rejected', reason: 'not_running' } - if (!this.runStartedByPerson(options.actor)) return { status: 'rejected', reason: 'not_started_by_person' } const blockers = this.archiveBlockers(threadId, { exceptRunId: runId }) if (blockers.length) return { status: 'rejected', reason: 'busy', blockers } this.archiveAfterTurn.set(threadId, { runId, actor: options.actor }) @@ -8911,28 +8867,6 @@ export class OrchestratorService extends EventEmitter { } } - /** - * The run at the top of a delegated run's chain: the turn a person, a job, a wake or another agent's message started, - * whose subagent (or subagent of a subagent) `runId` is. `runId` itself when it was not delegated; undefined when the - * chain can't be read or is deeper than 64. - */ - private delegationRootOf(runId: string): string | undefined { - const engine = this.runEngine - if (!engine) return undefined - let run = runId - for (let depth = 0; depth < 64; depth += 1) { - try { - if (engine.getRun(run)?.source !== 'delegation') return engine.getRun(run) ? run : undefined - const parentRunId = engine.delegations.getByChildRun(run)?.parentRunId - if (!parentRunId) return undefined - run = parentRunId - } catch { - return undefined - } - } - return undefined - } - /** * Issue #142 preflight, before any thread is created: a target whose provider cannot hold a * child to its policy gets a structured refusal instead of a child it could not keep read-only. diff --git a/src/mms/run/mcp/appTools/appearance.ts b/src/mms/run/mcp/appTools/appearance.ts index e1c2c1b475..f4a564a1c4 100644 --- a/src/mms/run/mcp/appTools/appearance.ts +++ b/src/mms/run/mcp/appTools/appearance.ts @@ -145,7 +145,7 @@ function state(appearance: AppearanceSettings): Record { /** * Refused where settings may not change: read-only turns, and a bot's subagents and consults. A Mousse - * subagent never holds the owner's `themes` (the authority compiler refuses it). A bot's own turn may, once its owner + * subagent may, as its parent may. A bot's own turn may, once its owner * allowed "change how Mousse looks" (the registry holds every call to that). */ function mayChangeSettings(turn: AppToolTurn): Availability { @@ -289,8 +289,6 @@ export function appearanceTools(host: AppToolHost): MousseTool[] { } }, access: 'changesSettings', - // The owner's own look: it never passes down to a subagent. - capabilities: ['themes'], permissionKey: PERMISSION_KEYS.mousseAppearance, class: 'mutation', approvalPrompt: (args) => { diff --git a/src/mms/run/mcp/appTools/askUser.ts b/src/mms/run/mcp/appTools/askUser.ts index e350700b8f..afab3b3689 100644 --- a/src/mms/run/mcp/appTools/askUser.ts +++ b/src/mms/run/mcp/appTools/askUser.ts @@ -7,7 +7,6 @@ import { disabledInSettings, plainSchema, truncateForDisplay, - type AppToolTurn, type MousseTool, type ToolCallContext, type ToolImage, @@ -57,14 +56,6 @@ function openQuestionText(questionId: string): string { }, null, 2) } -/** - * `question_ask` is offered in Agent mode and in a read-only mode. Subagents and Build/Skill modes go without it so - * workers implement instead of stopping to ask. - */ -function offeredInMode(turn: AppToolTurn): boolean { - return turn.modeFacts.readOnly || (!turn.subagent && turn.modeFacts.agent) -} - /** The questions a call names: each with an id, a prompt and at least two options; malformed entries are dropped. */ export function parseQuestions(raw: unknown): Question[] { if (!Array.isArray(raw)) return [] @@ -159,7 +150,7 @@ export function askUserTools(host: AppToolHost): MousseTool[] { readOnlySafe: true, asksUser: 'question', available: (turn) => (turn.settingsEnabled('question_ask') ? true : disabledInSettings('question_ask')), - offered: (turn) => offeredInMode(turn) && turn.settingsEnabled('question_ask'), + offered: (turn) => turn.settingsEnabled('question_ask'), describe: () => 'Question tool question_ask', handler: (args, ctx) => run(args, ctx) }, { @@ -172,7 +163,7 @@ export function askUserTools(host: AppToolHost): MousseTool[] { readOnlySafe: true, // Offered with `question_ask`, and only where a question can be asked without waiting. available: (turn) => (turn.settingsEnabled('question_ask') ? true : disabledInSettings('question_ask')), - offered: (turn) => offeredInMode(turn) && turn.settingsEnabled('question_ask') && host.withdrawQuestion !== undefined, + offered: (turn) => turn.settingsEnabled('question_ask') && host.withdrawQuestion !== undefined, describe: () => 'Question tool question_withdraw', handler: async (args, ctx) => withdraw(args, ctx) }] diff --git a/src/mms/run/mcp/appTools/authority.ts b/src/mms/run/mcp/appTools/authority.ts index 4a8873b6ac..7520e06fa0 100644 --- a/src/mms/run/mcp/appTools/authority.ts +++ b/src/mms/run/mcp/appTools/authority.ts @@ -5,7 +5,6 @@ import { botMayBeOffered, isBotThreadTool, isBotTurnHeldTool } from '../../../.. import { botCoreTool } from '../../../../shared/bots/personal/catalogue' import { canonicalToolName, isBotVariant } from '../../../../shared/toolAliases' import type { McpToolDescriptor } from '../../../../shared/integrations' -import { startedByPerson } from '../../approvalRights' import { familyMessageScope } from './family' import { refused } from './refusal' import { callerThreadOnly } from './thread' @@ -14,13 +13,11 @@ import { McpToolError, type AppToolTurn, type FamilyRelation, type McpCaller, ty /** * The authority compiler (docs/plans/tool-api.md §1.3, PR 2a): the one place that decides what a thread lists and what * a run holds of each Mousse tool. The thread's list (`tools/list`), Pi's per-turn list, the turn preamble's "usable - * now" line and every call's dispatch read what it compiles, from four inputs: - * 1. provenance: who started the run (`holdsPerson`, from the run's source and its binding's origin); unknown - * provenance grants no person authority, and a subagent never holds `person` (`MousseTool.needsPerson`); - * 2. lineage: whether the thread is a read-only child, whether it is a subagent (`AppToolTurn.subagent`, from the - * thread's lineage: the owner's own preferences never pass down to one), and its role when it is a personal bot's; - * 3. narrowing: the turn's mode (a mode that denies edits only reads pages); - * 4. the run's request policy (`approvals`, its permission mode) and its request channel (a bot's grant or owner). + * now" line and every call's dispatch read what it compiles, from three inputs: + * 1. lineage: whether the thread is a read-only child, and its role when it is a personal bot's (a subagent that is not + * read-only holds what its parent holds; who started the run decides nothing); + * 2. narrowing: the turn's mode (a mode that denies edits only reads pages); + * 3. the run's request policy (`approvals`, its permission mode) and its request channel (a bot's grant or owner). * * Each tool's declaration is read here and nowhere else (`toolNeeds`). What a call holds is `held`, `ask_first` (it * asks the person before it runs) or `lacks`: a listed tool the turn does not hold a capability of is refused with @@ -70,11 +67,6 @@ export interface ToolNeeds { readOnlyLacks?: string /** It sends messages (`messageIntent`): a read-only child holds it for a note to its family, whatever `readOnlyLacks` says. */ messages: boolean - /** The owner's own preference it changes: it never passes down to a subagent (§1.3 "Subagents"). */ - owner?: 'themes' | 'quick_actions' - /** The variants that need `person` (§1.3 "Provenance"); `personAlways`: every call does. */ - person?(args: Record): boolean - personAlways: boolean /** What a call waits for: the person's approval or their answer to a question. */ waitsFor?: 'approval' | 'question' /** Who answers it on a personal bot's turn: its grant, or its owner in the bot's own chat. */ @@ -102,8 +94,6 @@ const WRITE_CAPABILITY: Readonly> = { /** What a turn that lacks a capability is told would give it (`fix`). */ const READ_ONLY_FIX = 'This thread is a read-only subagent: its parent can do this, or start a subagent that is not read-only.' const READ_ONLY_MODE_FIX = 'This turn runs in a mode that denies edits; an Agent turn holds this.' -const OWNER_FIX = 'Only the thread\'s own agent changes the owner\'s preferences: tell your parent what you need.' -const PERSON_FIX = 'Only a turn the person started holds this: the person asks for it in their own turn of a thread that is not a subagent.' /** A tool's needs, read from its declaration: the only reader of its access flags. */ export function toolNeeds(tool: MousseTool): ToolNeeds { @@ -112,7 +102,6 @@ export function toolNeeds(tool: MousseTool): ToolNeeds { // `threads.start`: `thread_create` and `thread_fork` alike (§6, finding 9), whatever their `access`. const starts = tool.access === 'startsThreads' || tool.capabilities?.includes('threads.start') === true const readOnlyChild = reads || tool.readOnlySafe === true - const owner = tool.capabilities?.find((capability): capability is 'themes' | 'quick_actions' => capability === 'themes' || capability === 'quick_actions') return { access: tool.access, effect: tool.class === 'delegation' ? 'delegates' : tool.class === 'mutation' ? 'changes' : READ_ONLY_TOOL_NAMES.has(tool.name) ? 'none' : 'own', @@ -122,9 +111,6 @@ export function toolNeeds(tool: MousseTool): ToolNeeds { ...(readOnlyChild ? {} : { readOnlyLacks: starts ? 'threads.start' : tool.browserRight?.({}) ?? WRITE_CAPABILITY[tool.access] }), ...(tool.browserRight ? { browser: tool.browserRight } : {}), messages: tool.messageIntent !== undefined, - ...(owner ? { owner } : {}), - ...(tool.needsPerson ? { person: tool.needsPerson === true ? () => true : tool.needsPerson } : {}), - personAlways: tool.needsPerson === true, ...(tool.asksUser ? { waitsFor: tool.asksUser } : {}), ...(tool.botGrantAnswers ? { botAnswers: 'grant' as const } : tool.botAsksOwner ? { botAnswers: 'owner' as const } : {}), ...(edits ? { asksFirst: (args: Record) => tool.runsWithoutAsking?.(args) ?? 'edit' } : {}), @@ -171,10 +157,6 @@ export function listsTool(tool: MousseTool, listing: ToolListing): boolean { if (tool.variants) return tool.variants.some((variant) => listsTool(variant, listing)) const needs = toolNeeds(tool) if (listing.readOnly && !needs.readOnlyChild && !needs.messages) return false - // A subagent's thread never holds the owner's own preferences, nor `person`, so it never lists them (a bot's thread - // is held to its grant instead). - if (listing.subagent && needs.owner) return false - if (listing.subagent && needs.personAlways && listing.botRole === undefined) return false // A bot's main thread lists the thread tools its grant allows: "use your threads" is what lets it use them. Only // those its turn holds now are listed (none without the permission, with the switch off, or in a turn that only // reads), and every call is held to it again. A consult never has them. The profiler's tools likewise follow "use @@ -195,12 +177,10 @@ export function listsTool(tool: MousseTool, listing: ToolListing): boolean { /** The inputs of one call's or one turn's authority (see the file comment). */ export interface AuthorityInputs { turn: AppToolTurn - /** 2. Lineage: the thread is a read-only (`shared`) delegated child. */ + /** 1. Lineage: the thread is a read-only (`shared`) delegated child. */ readOnly: boolean - /** 4. The permission mode the run enforces, read only when a call would ask; unknown is Ask (it fails closed). */ + /** 3. The permission mode the run enforces, read only when a call would ask; unknown is Ask (it fails closed). */ permissionMode(): PermissionMode | undefined - /** 1. Provenance: the turn holds `person` (a person started it and it is not a subagent's); read only when a call needs it. */ - person(): boolean } /** What a call that asks first asks for: the mode that would let it run unasked, and whether nobody can answer. */ @@ -227,8 +207,6 @@ export interface CompiledTool { authorize(actor: McpCaller, args: Record, targets: ToolAccessPolicy | undefined): ToolScope | undefined /** What the turn lacks for it whatever the arguments, after the targets: an error result, or undefined. */ lacks(): ToolOutcome | undefined - /** The refusal of a variant that needs `person` in a turn that does not hold it, or undefined. A bot's grant answers instead. */ - personRefusal(args: Record): ToolOutcome | undefined /** * A personal bot's grant's refusal of this variant of the call, or undefined (and always for a turn that is not a * bot's). Nobody is asked: a list cached before a narrower revision cannot reach a removed tool. Dispatch checks it @@ -256,10 +234,6 @@ export function compileTool(tool: MousseTool, inputs: AuthorityInputs): Compiled return tool.authorize?.(actor, args, targets) ?? scope }, lacks: () => (lacks ??= { outcome: turnLacks(tool, needs, turn) }).outcome, - personRefusal: (args) => { - if (turn.bot || !needs.person?.(args) || inputs.person()) return undefined - return refused('lacks_capability', personLacks(tool.name), { lacks: 'person', fix: PERSON_FIX, data: { reason: 'mousse_scope_denied' } }) - }, grantRefusal: (args) => { if (!turn.bot) return undefined const refusal = botAppToolRefusal(turn.bot, tool.name, args) @@ -279,12 +253,9 @@ export function compileTool(tool: MousseTool, inputs: AuthorityInputs): Compiled } /** - * What the turn lacks for a tool whatever the call's arguments: the owner's preferences in a subagent, the bot's - * browser, availability, the request policy. + * What the turn lacks for a tool whatever the call's arguments: the bot's browser, availability, the request policy. */ function turnLacks(tool: MousseTool, needs: ToolNeeds, turn: AppToolTurn): ToolOutcome | undefined { - if (turn.subagent && needs.owner) - return refused('lacks_capability', `${tool.name} changes the owner's own preferences; a subagent does not hold that.`, { lacks: needs.owner, fix: OWNER_FIX }) // A bot's thread lists the browser tools whatever it holds: one its owner has not allowed says so, and how to ask, // not that no browser is bound to the turn. One the owner allowed after the turn started is answered as held: the // bot is not sent to ask again, and its turn continues with the browser once it ends. @@ -389,45 +360,28 @@ function botThreadScope(tool: MousseTool, needs: ToolNeeds, args: Record heldBeforeArguments(variant, turn, inputs)) const needs = toolNeeds(tool) if (needs.readOnlyLacks && inputs.readOnly && !needs.messages) return false if (needs.browser?.({}) === 'browser.act' && turn.modeFacts.readOnly) return false if (turnLacks(tool, needs, turn)) return false - // A tool every call of which needs `person`; one only some variants need stays usable. - if (needs.personAlways && !turn.bot && inputs.person?.() !== true) return false return botTurnOffers(turn.bot, tool.name) } -/** What a turn that lacks `person` is told for `tool`. */ -function personLacks(tool: string): string { - return `${tool} is only for a turn a person started. This run was started by a job, an agent's message, a wake, a continuation or a remote send, is a subagent's, or its origin cannot be read.` -} - /** What a thread holds now, as far as a capability its child lacks is concerned (`parentHolds`). */ export interface HolderState { /** A read-only (`shared`) subagent. */ readOnly: boolean - subagent: boolean - /** Its turn holds `person`. */ - person: boolean } /** * Whether a thread in `state` holds the capability `lacks` that its subagent was refused (§2.4): its parent is then told, - * and otherwise the root names what would give it. + * and otherwise the root names what would give it. Every capability a child lacks is one a thread that is not + * read-only holds. */ -export function parentHolds(lacks: string, state: HolderState): boolean { - switch (lacks) { - case 'person': - return state.person && !state.subagent - case 'themes': - case 'quick_actions': - return !state.subagent - default: - return !state.readOnly - } +export function parentHolds(_lacks: string, state: HolderState): boolean { + return !state.readOnly } /** @@ -455,17 +409,3 @@ export function userMcpSource(turn: AppToolTurn, botMcp: boolean): 'bot' | 'defi export function userMcpForReader(tools: readonly McpToolDescriptor[], turn: AppToolTurn, readOnly: boolean): McpToolDescriptor[] { return tools.filter((tool) => !readOnly || turn.toolAccess?.allows(tool.providerName) === true) } - -/** - * Who started the run (§1.3 "Provenance"): its origin and source, as `startedByPerson` reads them. Absent: unknown, - * which grants no person authority. - */ -export interface RunProvenance { - origin: string - source: string | null | undefined -} - -/** Whether the run holds `person`: only a run a person started (`gui`, `cli`, `resume_now`) does. */ -export function holdsPerson(provenance: RunProvenance | undefined): boolean { - return provenance !== undefined && startedByPerson(provenance) -} diff --git a/src/mms/run/mcp/appTools/bugReports.ts b/src/mms/run/mcp/appTools/bugReports.ts index 037d26c13d..85f9ab7784 100644 --- a/src/mms/run/mcp/appTools/bugReports.ts +++ b/src/mms/run/mcp/appTools/bugReports.ts @@ -52,9 +52,9 @@ export function bugReportTools(host: AppToolHost): MousseTool[] { // The person files it: an unattended run cannot ask, a bot's owner answers in the dialog. asksUser: 'approval', botAsksOwner: true, - listed: (listing) => !listing.subagent && Boolean(host.bugReports?.()), + listed: () => Boolean(host.bugReports?.()), available: () => (host.bugReports?.()?.settings().enabled ? true : 'Error reports are off in Settings → General.'), - offered: (turn) => !turn.subagent && Boolean(host.bugReports?.()?.settings().enabled), + offered: () => Boolean(host.bugReports?.()?.settings().enabled), describe: (args) => `Report a Mousse bug: ${text(args.title, 80)}`, handler: async (args, ctx): Promise => { const service = host.bugReports?.() diff --git a/src/mms/run/mcp/appTools/computer.ts b/src/mms/run/mcp/appTools/computer.ts index 91a5518c33..2a52be778e 100644 --- a/src/mms/run/mcp/appTools/computer.ts +++ b/src/mms/run/mcp/appTools/computer.ts @@ -14,8 +14,8 @@ import type { AppToolTurn, JsonSchema, MousseTool, ToolImage, ToolListing, ToolO * changes the thread's capability revision, and the runtime lists again. * * `computer_use_request` is how an agent that needs the computer asks for that setup: a card above the composer, never a - * wait (`ComputerUseSetupRequests`). It is listed for a thread's own agent (never a subagent) wherever it may use the - * computer, whatever the driver's state, so the list stays the same; a call needs a turn a person started. A bot's run + * wait (`ComputerUseSetupRequests`). It is listed for any thread's agent, subagents included, wherever it may use the + * computer, whatever the driver's state, so the list stays the same. A bot's run * its owner asked for in the chat holds it while the bot holds "use the computer". */ @@ -141,14 +141,13 @@ export function computerTools(host: AppToolHost): MousseTool[] { if (state === 'missing' || state === 'installing') return false return threadId === undefined || cu.allowedFor(threadId) } - // The setup request: a thread's own agent where it may use the computer, or a bot's run that holds it. + // The setup request: any thread's agent where it may use the computer, or a bot's run that holds it. const requestListed = (listing: ToolListing): boolean => { if (listing.botRole) return listing.botRole === 'activation' && Boolean(listing.botTurnTools?.has(COMPUTER_USE_REQUEST_TOOL)) - if (!computer() || listing.subagent) return false + if (!computer()) return false return listing.threadId === undefined || computer()!.allowedFor(listing.threadId) } const requestAvailable = (turn: AppToolTurn): true | string => { - if (turn.subagent) return "Only the thread's own agent asks for computer use, not a subagent." if (turn.bot) { // A bot asks only in work its owner asked for in its chat: never from a schedule, a reminder or another bot. if (!turn.bot.appTools.has(COMPUTER_USE_REQUEST_TOOL)) return 'Ask your owner for "use the computer" with permission_ask first.' @@ -172,7 +171,6 @@ export function computerTools(host: AppToolHost): MousseTool[] { inputSchema: REQUEST_SCHEMA, access: 'actsAsCaller', class: 'read', - needsPerson: true, listed: requestListed, available: requestAvailable, describe: () => 'Ask to set up computer use', diff --git a/src/mms/run/mcp/appTools/devGui.ts b/src/mms/run/mcp/appTools/devGui.ts index 8390bd283b..88562329c4 100644 --- a/src/mms/run/mcp/appTools/devGui.ts +++ b/src/mms/run/mcp/appTools/devGui.ts @@ -3,7 +3,7 @@ import type { AppToolHost } from './host' import { disabledInSettings, plainSchema, truncateForDisplay, type MousseTool } from './types' /** - * Dev-only self-inspection of the Mousse window (`npm run dev`), for the main agent; gated by + * Dev-only self-inspection of the Mousse window (`npm run dev`), for any agent; gated by * Settings → Skills & MCP like every other Mousse tool. Listed only in development builds. */ export function devGuiTools(host: AppToolHost): MousseTool[] { @@ -20,7 +20,7 @@ export function devGuiTools(host: AppToolHost): MousseTool[] { if (!isDevGuiToolsEnabled()) return 'Dev GUI tools are only available in development (`npm run dev`).' return turn.settingsEnabled(tool.name) ? true : disabledInSettings(tool.name) }, - offered: (turn) => !turn.subagent && isDevGuiToolsEnabled() && turn.settingsEnabled(tool.name) && Boolean(host.devGui), + offered: (turn) => isDevGuiToolsEnabled() && turn.settingsEnabled(tool.name) && Boolean(host.devGui), describe: () => `Dev GUI ${tool.name}`, handler: async (args, ctx) => { const devGui = host.devGui diff --git a/src/mms/run/mcp/appTools/host.ts b/src/mms/run/mcp/appTools/host.ts index 835b0f5b59..6ba68a19f7 100644 --- a/src/mms/run/mcp/appTools/host.ts +++ b/src/mms/run/mcp/appTools/host.ts @@ -216,14 +216,14 @@ export type AgentArchiveResult = /** * What asking to archive the caller's own thread did (`thread_archive` from a thread's agent): `scheduled` archives it - * when the running turn ends well, `changed: false` when it already is archived. Refused for a subagent, a bot's thread, - * a turn no person started, or a run that is not the thread's running turn; and (`busy`) while the archive would stop - * something besides that turn, named by `blockers`. + * when the running turn ends well, `changed: false` when it already is archived. Refused for a bot's thread or a run + * that is not the thread's running turn; and (`busy`) while the archive would stop something besides that turn, named + * by `blockers`. */ export type AgentArchiveOwnResult = | { status: 'scheduled' } | { status: 'accepted'; changed: false } - | { status: 'rejected'; reason: 'subagent' | 'not_started_by_person' | 'not_running' } + | { status: 'rejected'; reason: 'not_running' } | { status: 'rejected'; reason: 'busy'; blockers: ArchiveBlocker[] } /** @@ -432,8 +432,6 @@ export interface AppToolHost extends DelegationToolsHost { projectPathFor?(threadId: string): string | undefined /** The thread is a Mousse subagent, from its lineage. */ subagentThread?(threadId: string): boolean - /** The run holds `person`: a person started it and its thread is not a subagent (§1.3 "Provenance"). */ - personHeld?(caller: { threadId: string; runId: string }): boolean /** The parent a subagent's lineage names; undefined for a thread that is not a subagent. */ parentThread?(threadId: string): string | undefined /** Tells a subagent's parent, or the root of its tree, what the subagent was refused for lacking (§2.4). */ diff --git a/src/mms/run/mcp/appTools/index.ts b/src/mms/run/mcp/appTools/index.ts index 89c7d4e18c..312d93968d 100644 --- a/src/mms/run/mcp/appTools/index.ts +++ b/src/mms/run/mcp/appTools/index.ts @@ -48,7 +48,7 @@ const ANSWER_TOOLS: readonly string[] = Object.values(REQUEST_ANSWER_KINDS).map( export * from './types' export * from './refusal' export * from './registry' -export { compileTool, heldBeforeArguments, holdsPerson, parentHolds, toolNeeds, unattendedRefusal, type CompiledTool, type RunProvenance, type ToolEffect, type ToolNeeds } from './authority' +export { compileTool, heldBeforeArguments, parentHolds, toolNeeds, unattendedRefusal, type CompiledTool, type ToolEffect, type ToolNeeds } from './authority' export * from './turns' export type { AgentAccessResult, AgentActionDetails, AgentApprovalResult, AgentArchiveResult, AgentArchiveOwnResult, AgentCreatedThread, AgentRemoteThreadRequest, AgentRemoteThreadResult, RemoteProjectCandidate, AgentQueueCommand, AgentQueueResult, AgentScheduleHost, AgentRunCommandResult, AgentSendResult, AgentThreadRequest, ApprovalRequestInfo, AppToolHost, QueueSnapshot, RemoteThreadsHost, ThreadSearchHit } from './host' export { AGENT_MESSAGE_END, AGENT_MESSAGE_PREFIX, agentMessage, agentMessageText, cleanRemoteSenderTitle, BOT_MESSAGE_END, BOT_MESSAGE_PREFIX, botMessage, botMessageText, isPersonMessage, personTurnRequest } from './agentMessage' @@ -166,7 +166,6 @@ export function createAppToolRegistry(input: { toolLedger: host.toolLedger ? (runId) => host.toolLedger!(runId) : undefined, readOnlyThread: host.readOnlyThread ? (threadId) => host.readOnlyThread!(threadId) : undefined, subagentThread: host.subagentThread ? (threadId) => host.subagentThread!(threadId) : undefined, - personHeld: host.personHeld ? (caller) => host.personHeld!(caller) : undefined, parentThread: host.parentThread ? (threadId) => host.parentThread!(threadId) : undefined, reportLacks: host.reportLacks ? (report) => host.reportLacks!(report) : undefined, botRole: host.botRole ? (threadId) => host.botRole!(threadId) : undefined, diff --git a/src/mms/run/mcp/appTools/quickActions.ts b/src/mms/run/mcp/appTools/quickActions.ts index 55612a7c7b..41952e0a1e 100644 --- a/src/mms/run/mcp/appTools/quickActions.ts +++ b/src/mms/run/mcp/appTools/quickActions.ts @@ -33,7 +33,7 @@ export function questionApproval(questions: Pick false, () => undefined).getToolDefinitions() return definitions.map((tool): MousseTool => ({ @@ -47,8 +47,6 @@ export function quickActionTools(host: AppToolHost): MousseTool[] { // registry holds every call of a bot's turn to that grant, and nothing asks again. asksUser: 'approval', botGrantAnswers: true, - // A button in the owner's own Actions list: an owner preference, which never passes down to a subagent. - capabilities: ['quick_actions'], botDescription: 'Add a quick action for your owner: a button in their Actions list that sends a message (send-current, send-new-chat) or runs a shell command (bash) when they press it. Your owner allowed "add quick actions", so nothing asks first; add one only when they ask for it, and say what you added.', listed: () => Boolean(host.quickActions), available: (turn) => (turn.settingsEnabled(tool.name) ? true : disabledInSettings(tool.name)), diff --git a/src/mms/run/mcp/appTools/registry.ts b/src/mms/run/mcp/appTools/registry.ts index 6fc5d169f7..776bf5a2c6 100644 --- a/src/mms/run/mcp/appTools/registry.ts +++ b/src/mms/run/mcp/appTools/registry.ts @@ -114,13 +114,8 @@ export interface ToolRegistryOptions { toolLedger?(runId: string): ToolLedger | undefined /** The thread is a read-only (`shared`) delegated child; it may call only `reads` and `readOnlySafe` tools. */ readOnlyThread?(threadId: string): boolean - /** The thread is a Mousse subagent, from its lineage: it lists and holds nothing that never passes down. */ + /** The thread is a Mousse subagent, from its lineage (its refusals are reported up its tree). */ subagentThread?(threadId: string): boolean - /** - * The run holds `person` (§1.3 "Provenance"): a person started it and its thread is not a subagent. Absent, or a run - * whose origin cannot be read: it does not. - */ - personHeld?(caller: { threadId: string; runId: string }): boolean /** The thread a subagent's lineage names as its parent; undefined for a thread that is not a subagent. */ parentThread?(threadId: string): string | undefined /** @@ -626,7 +621,7 @@ export class ToolRegistry { * would refuse before any argument (`heldBeforeArguments`). */ usableNow(turn: AppToolTurn): string[] { - const inputs = { readOnly: this.options.readOnlyThread?.(turn.threadId) === true, person: () => this.personHeld(turn) } + const inputs = { readOnly: this.options.readOnlyThread?.(turn.threadId) === true } return this.listForThread(turn.threadId, turn.runId).filter((tool) => heldBeforeArguments(tool, turn, inputs)).map((tool) => tool.name) } @@ -925,9 +920,6 @@ export class ToolRegistry { } const lacks = compiled.lacks() if (lacks) return { refusal: lacks } - // A variant only a turn a person started may make (§1.3 "Provenance"). - const person = compiled.personRefusal(args) - if (person) return { refusal: person } // A bot turn: every other app tool is held to the bot's grant, on every call. A thread tool was checked above. if (!compiled.botThreads) { const refusal = compiled.grantRefusal(args) @@ -959,22 +951,10 @@ export class ToolRegistry { return compileTool(tool, { turn, readOnly: this.options.readOnlyThread?.(caller.threadId) === true, - permissionMode: () => this.options.permissionModeFor?.(caller.runId), - // A native helper's view of its run is a subagent's (`delegableTurn`): it never holds person either. - person: () => turn.subagent !== true && this.personHeld(caller) + permissionMode: () => this.options.permissionModeFor?.(caller.runId) }) } - /** Whether the caller's run holds `person`: the owner says so, and a subagent never does. */ - private personHeld(caller: { threadId: string; runId: string }): boolean { - if (this.options.subagentThread?.(caller.threadId) === true) return false - try { - return this.options.personHeld?.(caller) === true - } catch { - return false - } - } - /** * A subagent's `lacks_capability` refusal is reported up its tree (§2.4): to its parent when the parent holds what it * lacks, else to the root of its tree, which names what would give it. The owner tells each the first time per @@ -1006,19 +986,9 @@ export class ToolRegistry { return { ...outcome, text: refusalText(code, `${message} ${told}`, { ...rest, data: { ...(data ?? {}), told: to } }) } } - /** What `threadId` holds now (`parentHolds`): its lineage and its run's provenance. */ + /** What `threadId` holds now (`parentHolds`): its lineage. */ private holderState(threadId: string): Parameters[1] { - let active: string | null = null - try { - active = this.options.activeRunId(threadId) - } catch { - active = null - } - return { - readOnly: this.options.readOnlyThread?.(threadId) === true, - subagent: this.options.subagentThread?.(threadId) === true, - person: active !== null && this.personHeld({ threadId, runId: active }) - } + return { readOnly: this.options.readOnlyThread?.(threadId) === true } } /** diff --git a/src/mms/run/mcp/appTools/schedules.ts b/src/mms/run/mcp/appTools/schedules.ts index 8c40482515..6b9f9e1a91 100644 --- a/src/mms/run/mcp/appTools/schedules.ts +++ b/src/mms/run/mcp/appTools/schedules.ts @@ -343,7 +343,6 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ } }, class: 'mutation', - needsPerson: true, handler: (args, ctx) => { // A personal bot has no project of its own: a job that starts a new thread per run names the project. Any other // caller's job takes its thread's project, so naming one is refused as before. @@ -432,14 +431,6 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ } }, class: 'mutation', - // Changing what a job does; renaming it is for any turn. - needsPerson: (args) => { - try { - return Object.keys(asScheduledJobPatch(without(args, 'jobId'))).some((key) => key !== 'name') - } catch { - return false - } - }, handler: (args, ctx) => { refuseForbidden(args) if (args.enabled !== undefined) throw new Error('schedule_update does not change whether a job is enabled: pause it with schedule_pause; a person resumes it.') @@ -524,7 +515,6 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ 'Start a scheduled job your thread created now, as Run now does (needs a turn a person started: a job cannot start another). It starts within seconds, runs under the limits recorded on the job, and is refused while the job is running, waits in a queue, is paused, or has ended (a person resumes or extends it). The result is in the job\'s run history: read it with schedule_list.', inputSchema: { type: 'object', properties: { jobId: { type: 'string' } }, required: ['jobId'] }, class: 'mutation', - needsPerson: true, handler: (args, ctx) => { const job = findVisible(requiredId(args, 'jobId'), ctx) if (isWorkflowPrompt(job.prompt)) return { text: 'This job runs a workflow; an agent does not start those.', isError: true } diff --git a/src/mms/run/mcp/appTools/secrets.ts b/src/mms/run/mcp/appTools/secrets.ts index 2360e024ea..8f1133bd83 100644 --- a/src/mms/run/mcp/appTools/secrets.ts +++ b/src/mms/run/mcp/appTools/secrets.ts @@ -75,11 +75,6 @@ const RUN_DEFINITION: Tool = { }) } -/** Offered where `question_ask` is: the thread's own agent in Agent mode or a read-only mode, never a subagent. */ -function requestOffered(turn: AppToolTurn): boolean { - return turn.modeFacts.readOnly || (!turn.subagent && turn.modeFacts.agent) -} - function runAvailable(turn: AppToolTurn): true | string { if (turn.modeFacts.readOnly) return 'secret_run runs a command, which this mode does not allow. Ask for the secret now, and use it in a turn that may run commands.' // A personal bot runs it from its files folder, as its commands run. @@ -210,7 +205,7 @@ export function secretTools(host: AppToolHost): MousseTool[] { botDescription: 'Ask your owner for a secret (an API key, a token, a password) when the work your owner asked for needs one. A private card shows in your chat, where your owner types it or picks a saved one; never ask for a secret in a message, and never repeat one. You get only its name (like HF_TOKEN), never the value. Optionally bind it with for: {service} or {origin}, read only: Mousse adds its value only in secret_fetch; secret_run refuses bound secrets. Without a binding use secret_run. The call waits for your owner\'s answer (up to an hour), so ask only when they are expecting it.', listed: () => Boolean(secrets()), available: () => (secrets() ? true : 'Secret requests are not available here.'), - offered: (turn) => requestOffered(turn) && Boolean(secrets()), + offered: () => Boolean(secrets()), describe: (args) => `Asked for a secret: ${text(args.label, 120) || 'secret'}`, handler: (args, ctx) => request(args, ctx) }, @@ -230,7 +225,7 @@ export function secretTools(host: AppToolHost): MousseTool[] { class: 'mutation', listed: () => Boolean(secrets()), available: (turn) => (secrets() ? runAvailable(turn) : 'secret_run is not available here.'), - offered: (turn) => !turn.subagent && runAvailable(turn) === true && Boolean(secrets()), + offered: (turn) => runAvailable(turn) === true && Boolean(secrets()), describe: (args) => `Ran a command with ${Array.isArray(args.secrets) ? args.secrets.map((entry) => (entry && typeof entry === 'object' ? String((entry as Record).name ?? '') : '')).filter(Boolean).join(', ') : 'a secret'}`, handler: (args, ctx) => runCommand(args, ctx) }, diff --git a/src/mms/run/mcp/appTools/tasks.ts b/src/mms/run/mcp/appTools/tasks.ts index 0e29b694fd..5b7aa48e17 100644 --- a/src/mms/run/mcp/appTools/tasks.ts +++ b/src/mms/run/mcp/appTools/tasks.ts @@ -34,7 +34,7 @@ async function createOnce(queue: TaskQueue, args: Record, ctx: return answer } -/** The thread's task-queue tools, for the main orchestrator in every chat mode (not subagents). */ +/** The thread's task-queue tools, for every thread's agent, subagents included, in every chat mode. */ export function taskTools(host: AppToolHost): MousseTool[] { return new TaskControlTools(new TaskQueue()).getToolDefinitions().map((tool): MousseTool => ({ name: tool.name, @@ -48,7 +48,7 @@ export function taskTools(host: AppToolHost): MousseTool[] { if (!turn.settingsEnabled(tool.name)) return disabledInSettings(tool.name) return host.tasks(turn.threadId || undefined) ? true : `Unknown tool: ${tool.name}` }, - offered: (turn) => !turn.subagent && turn.settingsEnabled(tool.name) && Boolean(host.tasks(turn.threadId || undefined)), + offered: (turn) => turn.settingsEnabled(tool.name) && Boolean(host.tasks(turn.threadId || undefined)), describe: () => `Task tool ${tool.name}`, handler: async (args, ctx) => { const queue = host.tasks(ctx.turn.threadId || undefined) diff --git a/src/mms/run/mcp/appTools/thread.ts b/src/mms/run/mcp/appTools/thread.ts index 2983ec3683..4222645a24 100644 --- a/src/mms/run/mcp/appTools/thread.ts +++ b/src/mms/run/mcp/appTools/thread.ts @@ -162,7 +162,7 @@ const BOT_NAMES_THREAD = 'Name one of your owner\'s threads with threadId (threa /** `thread_fork`'s arguments for every caller; a personal bot's schema adds `hidden`. */ const FORK_PROPERTIES = { - sourceThreadId: { type: 'string', description: 'Defaults to your thread; otherwise a thread of your lineage.' }, + sourceThreadId: { type: 'string', description: 'Defaults to your thread; otherwise any thread of the profile (thread_list).' }, atRunOrdinal: { type: 'integer', minimum: 1, description: 'The source run to fork after; the latest finished run when omitted.' }, title: { type: 'string' }, seedFrom: { type: 'string', enum: ['checkpoint', 'current_head'], description: 'When the fork point has no code checkpoint the fork is refused (fork_point_unavailable) unless this is current_head: start from the source\'s current code.' }, @@ -424,8 +424,18 @@ export function lineageRelation(engine: RunEngine, callerThreadId: string, targe } -function isRelated(engine: RunEngine, callerThreadId: string, targetThreadId: string): boolean { - return lineageRelation(engine, callerThreadId, targetThreadId) !== null +/** + * What an agent's fork may start from besides its own thread: any thread of the profile, as every agent reads every + * thread, except a bot's and, from a shared thread, a private one (its content would reach the user's other devices). + * A thread it may not fork is refused the same way whether it exists or not. + */ +function assertForkSource(host: AppToolHost, callerThreadId: string, sourceThreadId: string): void { + const source = host.threadMeta?.(sourceThreadId) + const inventory = () => host.listThreads?.() ?? [] + const hidden = !source + || isBotThread(host, sourceThreadId, source) + || (isLocalOnlyThread(source, source.lineage?.rootThreadId ? inventory() : undefined) && host.threadMeta?.(callerThreadId)?.localOnly !== true) + if (hidden) throw new McpToolError('mousse_scope_denied', `Thread ${sourceThreadId} is not available to you.`) } const notAvailable = (tool: string): ToolOutcome => ({ text: `${tool} is not available in this host.`, isError: true }) @@ -2519,7 +2529,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, { name: 'thread_archive', - description: 'Archive a thread, as Archive in the app does: it leaves the sidebar for Archived and nothing is deleted. Only when the user asks you to archive a thread once its work is done (merged, or dropped), never on your own. Archiving stops everything the thread still runs, so it is refused while anything would be stopped (a turn, a subagent, a queued message, a background command or monitor, a wake-up, a question to the user), and the refusal names each one. Without threadId it archives this thread when your turn ends: call it last, in the turn that finishes the work, once nothing is outstanding; a failed or stopped turn leaves the thread open, and so does anything that still runs by then, which the user is shown. With threadId it archives that thread now, or unarchives it with archived: false. A subagent that runs on another computer is archived or unarchived on that computer first, and here only once it said so; status uncertain means that computer did not confirm it (call again with the same clientRequestId to get its first answer; it never acts twice). A qualified id (:) archives a thread on another computer, within the reach that computer gives this one\'s agents (by default only the threads this computer\'s agents started there; outside_agent_reach otherwise). Needs a turn the user started, in a thread that is not a subagent.', + description: 'Archive a thread, as Archive in the app does: it leaves the sidebar for Archived and nothing is deleted. Only when the user asks you to archive a thread once its work is done (merged, or dropped), never on your own. Archiving stops everything the thread still runs, so it is refused while anything would be stopped (a turn, a subagent, a queued message, a background command or monitor, a wake-up, a question to the user), and the refusal names each one. Without threadId it archives this thread when your turn ends: call it last, in the turn that finishes the work, once nothing is outstanding; a failed or stopped turn leaves the thread open, and so does anything that still runs by then, which the user is shown. With threadId it archives that thread now, or unarchives it with archived: false. A subagent that runs on another computer is archived or unarchived on that computer first, and here only once it said so; status uncertain means that computer did not confirm it (call again with the same clientRequestId to get its first answer; it never acts twice). A qualified id (:) archives a thread on another computer, within the reach that computer gives this one\'s agents (by default only the threads this computer\'s agents started there; outside_agent_reach otherwise).', botDescription: 'Archive one of your owner\'s threads when its work is merged or dropped and your owner asks you to tidy it away, as Archive in the app does: it leaves the sidebar for Archived and nothing is deleted. archived: false unarchives it again. Archiving stops everything the thread still runs, so a thread with anything still going (a turn, a background command, a wake-up, a question to your owner) is refused, and the refusal names each one: stop it first with thread_stop, or tell your owner.', inputSchema: { type: 'object', @@ -2537,9 +2547,8 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, required: ['threadId'] }, - // One rule (§1.5): `person` (a bot: its grant), and `threads.manage` for another thread, as every thread tool reaches it. + // One rule (§1.5): `threads.manage` for another thread, as every thread tool reaches it (a bot: its grant). access: 'managesOthers', - needsPerson: true, // A thread on another computer (a qualified id) is decided by that computer's reach (`archiveOnComputer`). Without // threadId the call is about the caller's own thread, as before. target: (args) => (isQualifiedId(args.threadId) ? undefined : { threadId: args.threadId as string | undefined }), @@ -2585,14 +2594,8 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B const result = host.archiveOwnThreadAfterTurn({ actor: actorOf(ctx) }) if (result.status === 'rejected' && result.reason === 'busy') throw new McpToolError('mousse_conflict', `Not archived. Archiving would stop:\n${archiveBlockersForAgent(result.blockers)}\nStop them first (background_stop, reminder_cancel), or tell the user what is still going.`, { conflict: 'thread_busy' }) - if (result.status === 'rejected') { - const why = result.reason === 'subagent' - ? 'A subagent cannot archive its thread.' - : result.reason === 'not_started_by_person' - ? 'Only a turn the user started can archive its thread.' - : 'This turn is not the thread\'s running turn.' - throw new McpToolError('mousse_scope_denied', `Not archived. ${why}`, { conflict: result.reason }) - } + if (result.status === 'rejected') + throw new McpToolError('mousse_scope_denied', 'Not archived. This turn is not the thread\'s running turn.', { conflict: result.reason }) const own = ctx.caller.threadId return json({ threadId: own, @@ -3041,7 +3044,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B } }, access: 'startsThreads', - authorize: checkedInHandler('the handler accepts the caller\'s own thread or its lineage as the source (a personal bot: a thread it may reach)'), + authorize: checkedInHandler('the handler accepts any thread the caller may read as the source (a personal bot: a thread it may reach)'), class: 'mutation', offered: () => false, // A personal bot's source, held to what it may reach (`botThreadScope`); an agent's is checked in the handler. @@ -3051,8 +3054,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B const bot = botThreadCall(bots, ctx) const sourceThreadId = bot ? targetThread(args, ctx, 'sourceThreadId') : args.sourceThreadId === undefined ? ctx.caller.threadId : args.sourceThreadId if (typeof sourceThreadId !== 'string' || !sourceThreadId) throw new Error('sourceThreadId must be a non-empty string') - if (!bot && sourceThreadId !== ctx.caller.threadId && !isRelated(engine, ctx.caller.threadId, sourceThreadId)) - throw new McpToolError('mousse_scope_denied', `Thread ${sourceThreadId} is not this thread or one of its lineage.`) + if (!bot && sourceThreadId !== ctx.caller.threadId) assertForkSource(host, ctx.caller.threadId, sourceThreadId) const atRunOrdinal = args.atRunOrdinal === undefined ? 'latest_stable' : boundedInt(args.atRunOrdinal, 'atRunOrdinal', 1, Number.MAX_SAFE_INTEGER, 1) if (args.title !== undefined && typeof args.title !== 'string') throw new Error('title must be a string') if (args.seedFrom !== undefined && args.seedFrom !== 'checkpoint' && args.seedFrom !== 'current_head') diff --git a/src/mms/run/mcp/appTools/threadWakes.ts b/src/mms/run/mcp/appTools/threadWakes.ts index eb44197974..d053ac41e9 100644 --- a/src/mms/run/mcp/appTools/threadWakes.ts +++ b/src/mms/run/mcp/appTools/threadWakes.ts @@ -2,17 +2,11 @@ import { DEFAULT_EVENT_WAKE_HOURS, MAX_EVENT_WAKE_HOURS, MAX_SAME_WAKES, pullReq import { ThreadWakeError, type ThreadWakes } from '../../../wakes/ThreadWakes' import { reminderLabel, reminderTime } from './bots' import type { AppToolHost } from './host' -import { json, type AppToolTurn, type MousseTool, type ToolCallContext, type ToolOutcome } from './types' +import { json, type MousseTool, type ToolCallContext, type ToolOutcome } from './types' /** The names a thread's agent shares with a personal bot: the same tools, parameters and limits. */ export const THREAD_WAKE_TOOL_NAMES = ['wake', 'reminder_list', 'reminder_cancel'] as const -/** - * Why a subagent sets no wake-ups: its task ends with its result to its parent, and a later turn of its own would have - * nobody to report to. The parent, which holds the context, waits instead: on the subagent's thread or the pull request. - */ -export const SUBAGENT_WAKE_REFUSAL = 'A subagent cannot set wake-ups: finish your task and return what you found. The thread that started you can wake on your thread or on the pull request.' - const error = (text: string): ToolOutcome => ({ text, isError: true }) function threadOf(ctx: ToolCallContext): string { @@ -38,16 +32,15 @@ const WAKE_SCHEMA = { /** * `wake`, `reminder_list` and `reminder_cancel` for a thread's agent (`ThreadWakes`): it carries on later in its own * thread without the person writing. A personal bot keeps its own versions of these names (`botTools`); `shareWakeTools` - * makes each one tool that serves both. A subagent sets none (`SUBAGENT_WAKE_REFUSAL`). Each acts on the caller's own + * makes each one tool that serves both. A subagent sets them like any thread. Each acts on the caller's own * thread only; a `thread` it waits on is checked by the service (`ThreadWakesDeps.threadState`: a thread that exists, * no bot's, and not a private one from a shared thread). */ export function threadWakeTools(host: AppToolHost): MousseTool[] { if (!host.threadWakes) return [] const service = (): ThreadWakes | undefined => host.threadWakes?.() - const subagent = (threadId: string | undefined): boolean => Boolean(threadId && host.subagentThread?.(threadId)) - const listed = (listing: { botRole?: unknown; subagent?: boolean; threadId?: string }): boolean => !listing.botRole && !listing.subagent && !subagent(listing.threadId) && Boolean(service()) - const available = (turn: AppToolTurn): true | string => (subagent(turn.threadId) ? SUBAGENT_WAKE_REFUSAL : service() ? true : 'Wake-ups are not available here.') + const listed = (listing: { botRole?: unknown }): boolean => !listing.botRole && Boolean(service()) + const available = (): true | string => (service() ? true : 'Wake-ups are not available here.') return [ { name: 'wake', @@ -58,7 +51,7 @@ export function threadWakeTools(host: AppToolHost): MousseTool[] { 'Checks settle when none are queued or running; checks waiting for approval are reported too. Checks describe only the rollup GitHub currently reports, which may omit required checks or briefly show the previous head after a push: read the framed head commit before acting. Reviews by anyone count, including the person\'s own account and review bots: do not post a review to trigger your own wake.', `A wake on a thread or pull request gives up after hours (default ${DEFAULT_EVENT_WAKE_HOURS}, at most ${MAX_EVENT_WAKE_HOURS}) or when the pull request is closed or the thread archived or deleted, and you still wake once and are told why.`, `There is no count of wake-ups in a row; only a loop is refused: the same brief, waiting on the same thing, set more than ${MAX_SAME_WAKES} times before the person writes again.`, - 'List and cancel yours with reminder_list and reminder_cancel. The person sees them with the thread\'s background work, and stopping or archiving the thread cancels them. Subagents cannot set wake-ups.', + 'List and cancel yours with reminder_list and reminder_cancel. The person sees them with the thread\'s background work, and stopping or archiving the thread cancels them.', 'End your turn after setting it, and tell the person in a few words what you will follow up on.' ].join(' '), inputSchema: WAKE_SCHEMA, @@ -70,7 +63,6 @@ export function threadWakeTools(host: AppToolHost): MousseTool[] { describe: () => 'Set a wake-up', handler: async (args, ctx) => { const threadId = threadOf(ctx) - if (subagent(threadId)) return error(SUBAGENT_WAKE_REFUSAL) const wakes = service() if (!wakes) return error('Wake-ups are not available here.') const brief = typeof args.brief === 'string' ? args.brief.trim() : '' diff --git a/src/mms/run/mcp/appTools/types.ts b/src/mms/run/mcp/appTools/types.ts index 4a17adfd8f..0dbc2097ca 100644 --- a/src/mms/run/mcp/appTools/types.ts +++ b/src/mms/run/mcp/appTools/types.ts @@ -66,7 +66,7 @@ export type ToolClass = 'read' | 'mutation' | 'delegation' * child no wider than yourself) is every delegation tool's and every thread holds it, readers included; * `threads.start` (an independent thread or a fork) is not held by a read-only child. */ -export type ToolCapability = 'threads.delegate' | 'threads.start' | 'themes' | 'quick_actions' +export type ToolCapability = 'threads.delegate' | 'threads.start' export const TOOL_CLASSES: ReadonlySet = new Set(['read', 'mutation', 'delegation']) @@ -130,7 +130,7 @@ export interface AppToolTurn { * The agent access level recorded for the run (SPEC §15.1). It no longer limits anything. */ accessLevel?: AgentAccessLevel - /** The thread is a Mousse subagent (its lineage says so): the owner's own preferences do not pass down to it. */ + /** The thread is a Mousse subagent (its lineage says so); it holds what its parent holds. */ subagent: boolean projectPath?: string actor: IntegrationActor @@ -243,7 +243,7 @@ export interface ToolListing { /** The thread the list is for, when it is one thread's. */ threadId?: string readOnly: boolean - /** The thread is a Mousse subagent: it does not list what never passes down (the owner's own preferences). */ + /** The thread is a Mousse subagent; it lists what its parent lists. */ subagent?: boolean /** The thread's role when it is a personal bot's thread (PR 6 §5): only bot threads list the bot tools. */ botRole?: 'activation' | 'context' | 'subagent' @@ -317,8 +317,7 @@ export interface MousseTool { messageIntent?(args: Record): MessageIntent | undefined /** * Capabilities the tool needs beyond what its `access` says (docs/plans/tool-api.md §1.3): `threads.start` for a tool - * that starts an independent thread (a read-only child lacks it), `themes` and `quick_actions` for - * the owner's own preferences, which never pass down to a subagent. + * that starts an independent thread (a read-only child lacks it). */ capabilities?: readonly ToolCapability[] /** @@ -326,12 +325,6 @@ export interface MousseTool { * open, act or change tabs, read from the arguments. A read-only child, and a mode that denies edits, do not hold `browser.act`. */ browserRight?(args: Record): 'browser.read' | 'browser.act' - /** - * The call needs `person` (docs/plans/tool-api.md §1.3 "Provenance"): only a turn a person started holds it, and it - * never passes down to a subagent. `true` for every call, or the variants that need it, read from the arguments. A bot's - * turn is held to its grant instead. - */ - needsPerson?: true | ((args: Record) => boolean) /** * `in_process`: never callable over MCP (an older name kept for replayed transcripts). Whether it is listed is * `listed`'s to say. diff --git a/src/mms/run/mcp/instructions.ts b/src/mms/run/mcp/instructions.ts index a27a3f8f61..4a46cda8ef 100644 --- a/src/mms/run/mcp/instructions.ts +++ b/src/mms/run/mcp/instructions.ts @@ -22,7 +22,7 @@ export function mousseOrchestrationInstructions(): string { '- schedule_list, schedule_create, schedule_update, schedule_pause, schedule_run and schedule_delete manage the scheduled jobs your own thread made; schedule_delete also removes one your subagents made. The first job your thread creates is not made at once: the user is asked and answers Allow or Not now (tell them it waits for their answer; do not retry); after Allow your thread may add more within the limits; a subagent\'s every job is asked. Creating, starting or changing what a job does works only in a turn the user started, or a subagent of one (not from a job, another agent\'s message or a remote send). A job outlives your turn and runs later as a turn of its own, with no permission mode beyond yours; changing one can only narrow that. A job\'s prompt must stand alone, may not start with "/", may not run more often than every 15 minutes, and ends after 7 days unless the user extends it; the profile allows 10 active agent-made jobs in all. The user resumes a paused job. Remove a job with schedule_delete once its work is done.', '- queue_list and queue_update (op edit, remove, move or send_now) work on the messages queued on your thread or another thread. queue_list gives the queue\'s revision: pass it as expectedRevision to every call that changes the queue (and the run you read as expectedRunId to op send_now); if the queue changed meanwhile you are told and nothing changes, so read it again. What you write into a queue is labelled as yours, runs under your permission mode when that is stricter than the message\'s, and counts toward the few agent messages a thread keeps waiting; a removal is recorded with its text. op send_now is refused while the user has a question or approval waiting. A message sent now joins only the run you named, and runs as its own turn if that run ends first.', '- Background work: to wait on something (CI, a review, a deploy, a log line, a long build), do not poll in a loop or wait in your turn. monitor_start runs a script (each printed line is an event) or watches a wss:// socket (each message is an event) and sends you notices while you keep working or after your turn ends; background_run runs one command and tells you once when it ends, with its exit code and output. Make the script of a monitor print on failure, on exit and on timeout too, not only on success, so silence never hides a crash; filter its output to what you need. Every monitor and command tells you when it ends and why (one you stop with background_stop, in the result of that call); the time of a monitor runs out after at most 30 minutes, so start it again if you still need it. keep_working keeps the thread shown as Working while you wait on something outside Mousse; release it when the wait is over. background_stop stops any of them by id.', - '- Wake-ups: to carry on later in this thread without the user writing (at a time, when another thread finishes its turn, or when a pull request merges, its checks settle or it gets a review), call wake with a brief of what you will do then, and end your turn. Unlike a monitor it has no time limit of minutes and survives restarts and sleep, so prefer it for pull requests and anything that takes longer than a monitor\'s 30 minutes. reminder_list and reminder_cancel list and cancel yours. A subagent cannot set one.', + '- Wake-ups: to carry on later in this thread without the user writing (at a time, when another thread finishes its turn, or when a pull request merges, its checks settle or it gets a review), call wake with a brief of what you will do then, and end your turn. Unlike a monitor it has no time limit of minutes and survives restarts and sleep, so prefer it for pull requests and anything that takes longer than a monitor\'s 30 minutes. reminder_list and reminder_cancel list and cancel yours.', ...appToolGuidance(), '- Never ask for passwords, API keys, tokens or other secrets in chat, and never repeat a secret you were given. When you need one, ask with secret_request: the user types it into a private card and you get its name, and, where your runtime\'s tool results can be masked, a private file holding it (the result says which). With the file, use it directly wherever the work needs it (commands, config files, API calls, logins) by passing the file inside the command (gh auth login --with-token < file, $(cat file) in a header), so the value never comes back as output; never open the file to look at it, since a tool\'s result stays in your session\'s saved history. Without one, use secret_run. ${secret:NAME} reads it in an MCP server\'s settings. The card only keeps it out of the chat, so never print or echo the value there.' ].join('\n') diff --git a/src/mms/run/nativeHelpers.ts b/src/mms/run/nativeHelpers.ts index 5cf748e4f4..de3c3eda1b 100644 --- a/src/mms/run/nativeHelpers.ts +++ b/src/mms/run/nativeHelpers.ts @@ -245,16 +245,14 @@ const HOSTING_TURN = Symbol('hostingTurn') const delegableViews = new WeakMap() /** - * The hosting run's turn as a helper's call holds it: delegable authority only (§1.3 "Subagents"), as a Mousse subagent - * of the run would. Owner-level tools (theme, applets, questions to the person, secrets, tasks, goals, quick actions) - * refuse as they do for a subagent. One view per turn, so a check that compares turns still finds the live one - * (`hostingTurn`). + * The hosting run's turn as a helper's call holds it: what a Mousse subagent of the run would hold (§1.3 "Subagents"), + * which is what the run holds, applets included. One view per turn, so a check that compares turns still finds the live + * one (`hostingTurn`). */ export function delegableTurn(turn: AppToolTurn): AppToolTurn { let view = delegableViews.get(turn) if (!view) { - const { onPublishApplet: _applet, onReadApplet: _read, ...rest } = turn - view = Object.assign({ ...rest, subagent: true }, { [HOSTING_TURN]: turn }) as AppToolTurn + view = Object.assign({ ...turn, subagent: true }, { [HOSTING_TURN]: turn }) as AppToolTurn delegableViews.set(turn, view) } return view diff --git a/tests/wakes/threadWakeTools.test.ts b/tests/wakes/threadWakeTools.test.ts index 9990c6bb8d..b1e496cf75 100644 --- a/tests/wakes/threadWakeTools.test.ts +++ b/tests/wakes/threadWakeTools.test.ts @@ -5,7 +5,7 @@ */ import { describe, expect, it, vi } from 'vitest' import { botTools } from '../../src/mms/run/mcp/appTools/bots' -import { SUBAGENT_WAKE_REFUSAL, shareWakeTools, threadWakeTools } from '../../src/mms/run/mcp/appTools/threadWakes' +import { shareWakeTools, threadWakeTools } from '../../src/mms/run/mcp/appTools/threadWakes' import type { AppToolHost } from '../../src/mms/run/mcp/appTools/host' import type { MousseTool, ToolCallContext } from '../../src/mms/run/mcp/appTools/types' import { ThreadWakeError, type ThreadWakes } from '../../src/mms/wakes/ThreadWakes' @@ -35,12 +35,12 @@ describe('thread wake tools', () => { expect([...tools.keys()].filter((name) => name === 'wake')).toHaveLength(1) }) - it('a subagent neither sees nor sets one', async () => { + it('a subagent sees and sets one like any thread', async () => { const { tools, call, add } = setup({ subagent: true }) - expect(tools.get('wake')!.listed?.({ threadId: 'child-1' } as never)).toBe(false) - expect(tools.get('wake')!.available?.({ threadId: 'child-1' } as never)).toBe(SUBAGENT_WAKE_REFUSAL) - expect(await call('wake', { brief: 'x', inMinutes: 5 })).toEqual({ text: SUBAGENT_WAKE_REFUSAL, isError: true }) - expect(add).not.toHaveBeenCalled() + expect(tools.get('wake')!.listed?.({ threadId: 'child-1', subagent: true } as never)).toBe(true) + expect(tools.get('wake')!.available?.({ threadId: 'child-1' } as never)).toBe(true) + expect((await call('wake', { brief: 'x', inMinutes: 5 })).isError).toBeFalsy() + expect(add).toHaveBeenCalledTimes(1) }) it('checks its arguments as the bot\'s wake does, and sets it on the caller\'s own thread', async () => { From 54302a98bfbdec33dab97c49c66538d81a8021cc Mon Sep 17 00:00:00 2001 From: TheAnimatrix Date: Mon, 30 Nov 2026 03:49:43 +0530 Subject: [PATCH 02/15] feat(schedules): agents make, see and change any job of the profile without a first ask The first-job Allow / Not now ask, the legacy scheduled.agentJobs switch and its inbox card are gone. Creating, starting and changing a job no longer needs a turn a person started. Agents may set the permission mode up to their own, a project, a saved agent, a thread per run, a workflow prompt, an existing worktree, resume and re-enable a job and change its number of runs. Every agent sees and changes every job of the profile, a person's too; a bot still sees its own. The job limits stay the owner's settings, and webhook triggers stay refused. --- docs/CLI.md | 2 +- src/mms/MmsProfileServices.ts | 43 +- src/mms/MousseMainService.ts | 1 - src/mms/automations/AgentJobAsks.ts | 120 ---- src/mms/automations/AutomationIndex.ts | 53 -- src/mms/automations/registerMethods.ts | 27 +- src/mms/config/MousseConfigStore.ts | 9 - src/mms/config/types.ts | 2 - src/mms/run/mcp/appTools/schedules.ts | 386 ++++++------ src/renderer/components/asks/AskCard.tsx | 4 +- .../automations/inbox/AutomationsInbox.tsx | 32 +- .../components/automations/inbox/inbox.css | 9 - .../settings/AgentAutomationsSettings.tsx | 7 +- src/renderer/services/automationsClient.ts | 8 +- src/shared/automations.ts | 15 +- src/shared/bridge/routed.ts | 4 +- src/shared/types.ts | 2 - tests/automations.test.ts | 47 +- tests/renderer/automationsPage.test.ts | 3 +- tests/run/botThreadParity.test.ts | 7 +- tests/run/scheduleTools.test.ts | 559 +++++++----------- tests/scheduledJobs.test.ts | 19 +- tests/scheduledTurn.test.ts | 165 +----- tests/scheduledWebhookTrigger.test.ts | 38 +- tests/themeSelectors.test.ts | 1 - 25 files changed, 493 insertions(+), 1070 deletions(-) delete mode 100644 src/mms/automations/AgentJobAsks.ts diff --git a/docs/CLI.md b/docs/CLI.md index 61620190d0..4402e2c948 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -207,7 +207,7 @@ An automation runs as a turn on a thread. `--instance` and `--model` choose the ### Jobs agents create -Agents can manage the jobs their own thread made through Mousse's tools (`schedule_list`, `schedule_create`, `schedule_update`, `schedule_pause`, `schedule_run`, `schedule_delete`). A thread may also remove a job one of its subagents made; a subagent cannot remove any job, not even its own. A removal works like Delete in Automations and shows in the thread's transcript. The first job a thread's agent creates is not made at once: you are asked at the top of the Automations inbox, under Needs you, and Allow adds it and lets that thread add more; Not now drops it. Only a turn you started can create or start a job. A job an agent creates runs no wider than that agent, runs at most every 15 minutes, ends after 7 days unless you keep it (Keep, in its Edit details, removes only that end) or extend it (`mousse-cli automation extend [--days 7]`), counts against 10 active agent-made jobs in the profile (these three numbers are defaults: Settings, Agent access changes them, for new creates and changes only), shows "added by" its thread, and takes a webhook only after you keep it. The rules are in `docs/CONFIGURATION.md` (scheduled jobs). These limits bind the Mousse tools. An agent that can run shell commands can reach the daemon's local protocol as you do (`mousse-cli automation ...`), which is what the permission mode of that thread governs. +Agents can manage every job of the profile through Mousse's tools (`schedule_list`, `schedule_create`, `schedule_update`, `schedule_pause`, `schedule_run`, `schedule_delete`): yours, their own and other agents', except across the private line. A removal works like Delete in Automations and shows in the thread's transcript. A job an agent creates is made at once and runs no wider than that agent, runs at most every 15 minutes, ends after 7 days unless you keep it (Keep, in its Edit details, removes only that end) or extend it (`mousse-cli automation extend [--days 7]`), counts against 10 active agent-made jobs in the profile (these three numbers are defaults: Settings, Agent access changes them, for new creates and changes only), shows "added by" its thread, and takes a webhook only after you keep it. The rules are in `docs/CONFIGURATION.md` (scheduled jobs). These limits bind the Mousse tools. An agent that can run shell commands can reach the daemon's local protocol as you do (`mousse-cli automation ...`), which is what the permission mode of that thread governs. ### Webhook trigger diff --git a/src/mms/MmsProfileServices.ts b/src/mms/MmsProfileServices.ts index 3abca6b0c4..baa047a763 100644 --- a/src/mms/MmsProfileServices.ts +++ b/src/mms/MmsProfileServices.ts @@ -61,7 +61,7 @@ import { OrchestratorService } from './orchestrator/OrchestratorService' import { ProfileDatabase } from './run/db/ProfileDatabase' import { McpCredentials } from './run/mcp/McpCredentials' import { MousseMcpServer } from './run/mcp/MousseMcpServer' -import { isPersonMessage, personTurnRequest } from './run/mcp/appTools/agentMessage' +import { isPersonMessage } from './run/mcp/appTools/agentMessage' import { EffectWorker } from './run/EffectWorker' import { TERMINAL_RUN_STATUSES, type RunRecord, type ThreadEvent } from './run/types' import { jobThreadIn, launchedHereAndThere, launchedThreadsIn, watchLaunchedThreads } from './bots/launchedThreads' @@ -190,8 +190,6 @@ import { jobSharedWithComputers, privateThreadOf } from './automations/sharedAut import type { RemoteAutomationsPart, RemoteAutomationsPort } from './protocol/remoteAutomationsPort' import { usedWallpapers, WallpaperStore } from './appearance/WallpaperStore' import { ThemeRestoreStore } from './appearance/ThemeRestoreStore' -import { AgentJobAskStore, type AgentJobAsk } from './automations/AgentJobAsks' -import { agentJobExpiry, isActiveAgentJob } from './scheduled/agentJobLimits' import type { AutomationIndex, ManagerTurn } from '../shared/automations' import { resolveThreadProjectPath } from './data/resolveActiveProjectPath' import { SpeechRelay } from './speech/SpeechRelay' @@ -1354,7 +1352,7 @@ export class MmsProfileServices { } catch (error) { console.warn('scheduled job permission ceilings could not be stamped; jobs without one follow their thread\'s mode', error instanceof Error ? error.message : String(error)) } - // Agents' schedule tools: the same checks and store the protocol uses, behind `scheduled.agentJobs` (off by default). + // Agents' schedule tools: the same checks and store the protocol uses. const jobOptionDeps = scheduledJobOptionsDepsFrom({ providerInstances: this.providerInstances, harness: () => { @@ -1364,7 +1362,6 @@ export class MmsProfileServices { projects: this.projects, threads: this.threads }) - this.agentJobAsks = new AgentJobAskStore(homeDir) this.themeRestore = new ThemeRestoreStore(homeDir) this.wallpapers = new WallpaperStore(homeDir, { used: () => this.usedWallpaperIds() }) // The agents' theme tools: a change is saved like one made in Settings and reaches every window of the profile. @@ -1380,13 +1377,6 @@ export class MmsProfileServices { restorePoint: this.themeRestore }) this.orchestrator.setScheduledJobs({ - // A thread whose first ask the person allowed; a profile that turned the old switch on lets every thread add them. - threadAllowed: (threadId) => config.agentJobsEnabled() || this.agentJobAsks.threadAllowed(threadId), - askFirst: (input) => { - const ask = this.agentJobAsks.ask(input) - this.events.emit({ channel: 'scheduled:updated', data: this.scheduled.listJobs() }) - return ask - }, jobLimits: () => config.agentJobLimits(), // A bot's schedules are the bot's: an agent's schedule tools never see or change them. list: () => this.scheduled.listJobs().filter((job) => !job.bot), @@ -1398,6 +1388,7 @@ export class MmsProfileServices { create: (input) => this.scheduled.createJob(input), update: (id, patch) => this.scheduled.updateJob(id, patch), pause: (id, reason) => this.scheduled.pauseJob(id, reason), + resume: (id) => this.scheduled.resumeJob(id), remove: (id) => this.deleteScheduledJob(id), trigger: (id) => this.scheduled.triggerJob(id), wake: () => this.scheduled.wake() @@ -1427,8 +1418,6 @@ export class MmsProfileServices { this.orchestrator.setAutomationTools({ drafts: this.automationDrafts, isManagerThread: (threadId) => this.threads.getThread(threadId)?.automationManager === true, - // The person's own message that started the manager's current turn: none when an agent's or a bot's message did. - personRequest: (threadId, runId) => this.automationManagerRequest(threadId, runId), managerWorkspace: () => automationManagerWorkspace(this.homeDir, this.automationManagerProjectId ? this.projects.getProject(this.automationManagerProjectId)?.path : undefined), botOf: (threadId) => this.personalBots?.tools.activationOf(threadId)?.botId, activationOf: (threadId) => this.personalBots?.tools.activationOf(threadId)?.activationId, @@ -2284,9 +2273,6 @@ export class MmsProfileServices { return record } - /** First-creation asks of agents that add automations (`AgentJobAskStore`). */ - agentJobAsks!: AgentJobAskStore - /** The profile's wallpaper images (`/wallpapers`); settings name them by id only. */ wallpapers!: WallpaperStore @@ -2299,21 +2285,6 @@ export class MmsProfileServices { return usedWallpapers([...this.settings.get().appearance.userThemes, ...kept]) } - /** - * Answers an agent's first-creation ask. Allow makes the automation as the agent asked, ending after the lifetime - * limit from now and counted against the active limit, and lets that thread add more; Not now closes the ask. - */ - answerAgentJobAsk(askId: string, answer: 'allow' | 'not_now'): AgentJobAsk { - const limits = this.config.agentJobLimits() - const answered = this.agentJobAsks.answer(askId, answer, (ask) => { - const active = this.scheduled.listJobs().filter(isActiveAgentJob).length - if (active >= limits.maxActive) throw new Error(`Agents already have ${active} active automations (the limit is ${limits.maxActive}). Pause or delete one, or raise the limit in Settings, Agent access.`) - return this.scheduled.createJob({ ...ask.input, expiresAt: agentJobExpiry(limits.lifetimeDays) }) - }) - this.events.emit({ channel: 'scheduled:updated', data: this.scheduled.listJobs() }) - return answered - } - /** The Automations page's one list (`automations.list`): jobs (bots' schedules among them) and pull request watches. */ /** * A thread's pull request watch for its thread-event automations: on (in `event` mode, unless Notify already serves it) @@ -2390,13 +2361,6 @@ export class MmsProfileServices { } } - /** - * The person's request in the manager's turn `runId`: the person's own message that started that turn, else none. An - * agent's or a bot's message that started it has none, so an older message of the person's never stands in for one. - */ - automationManagerRequest(threadId: string, runId: string): string | undefined { - return personTurnRequest(this.orchestrator.getMessagesForPersistence(threadId), runId) - } /** The Automations inbox (`automations/automations.db`); absent when it could not be opened. */ automationRuns: AutomationRuns | undefined @@ -2462,7 +2426,6 @@ export class MmsProfileServices { } }, ...(bots ? { bot: (botId: string, scheduleId: string) => bots.service.automationFacts(botId, scheduleId) } : {}), - asks: () => this.agentJobAsks?.open() ?? [], pendingApproval: (threadId) => { const pending = this.questions.listPendingForThread(threadId)[0] const question = pending?.questions.length === 1 ? pending.questions[0] : undefined diff --git a/src/mms/MousseMainService.ts b/src/mms/MousseMainService.ts index 90d6bceafc..d22e0f2ba3 100644 --- a/src/mms/MousseMainService.ts +++ b/src/mms/MousseMainService.ts @@ -365,7 +365,6 @@ export class MousseMainService extends MmsProfileServices { const services = await profile(profileId) return { index: (viewer, signal) => viewer === 'window' ? services.automationIndexForWindow(signal) : viewer === 'computer' ? services.automationIndexForComputer() : services.automationIndex(), - answerAsk: (askId, answer) => services.answerAgentJobAsk(askId, answer), keep: (jobId) => services.scheduled.keepJob(jobId), resend: (jobId, occurrenceId) => services.scheduled.resendWebhook(jobId, occurrenceId), keys: services.automationKeys, diff --git a/src/mms/automations/AgentJobAsks.ts b/src/mms/automations/AgentJobAsks.ts deleted file mode 100644 index 5d9ad4240f..0000000000 --- a/src/mms/automations/AgentJobAsks.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { existsSync, mkdirSync, readFileSync } from 'node:fs' -import { join } from 'node:path' -import { randomUUID } from 'node:crypto' -import { atomicWriteJsonSync } from '../data/AtomicFs' -import { withFileLock } from '../scheduled/fileLock' -import type { CreateScheduledJobInput } from '../../shared/types' - -/** - * The first-creation ask (Path step 2): the first time a thread's agent adds an automation, the automation is not made; - * a durable ask is, and the person answers it with Allow or Not now. Allow makes the automation and lets that thread add - * more within the limits; Not now closes the ask. It replaces the old "Agents may add automations" switch. - */ -export interface AgentJobAsk { - id: string - /** The thread whose agent asked. */ - threadId: string - /** The creating call's key, so a retried call finds its ask instead of asking again. */ - requestKey: string - /** The automation as it will be made, without its end (set from the moment the person allows it). */ - input: Omit - createdAt: string - state: 'open' | 'allowed' | 'declined' - answeredAt?: string - /** The automation Allow made. */ - jobId?: string -} - -interface AskFile { - version: 1 - asks: AgentJobAsk[] - /** Threads whose agents the person allowed to add automations. */ - allowedThreads: string[] -} - -const EMPTY: AskFile = { version: 1, asks: [], allowedThreads: [] } -/** Answered asks kept for the record, newest last. */ -const ANSWERED_KEPT = 50 - -export class AgentJobAskStore { - private readonly dir: string - private readonly path: string - - constructor(homeDir: string) { - this.dir = join(homeDir, 'scheduled') - this.path = join(this.dir, 'agent-asks.json') - } - - private read(): AskFile { - if (!existsSync(this.path)) return structuredClone(EMPTY) - try { - const parsed = JSON.parse(readFileSync(this.path, 'utf8')) as Partial - return { - version: 1, - asks: Array.isArray(parsed.asks) ? parsed.asks : [], - allowedThreads: Array.isArray(parsed.allowedThreads) ? parsed.allowedThreads.filter((id): id is string => typeof id === 'string') : [] - } - } catch { - return structuredClone(EMPTY) - } - } - - private change(edit: (file: AskFile) => T): T { - mkdirSync(this.dir, { recursive: true }) - return withFileLock(join(this.dir, '.agent-asks.lock'), () => { - const file = this.read() - const result = edit(file) - const open = file.asks.filter((ask) => ask.state === 'open') - const answered = file.asks.filter((ask) => ask.state !== 'open').slice(-ANSWERED_KEPT) - atomicWriteJsonSync(this.path, { ...file, asks: [...answered, ...open] }) - return result - }) - } - - list(): AgentJobAsk[] { - return this.read().asks - } - - open(): AgentJobAsk[] { - return this.list().filter((ask) => ask.state === 'open') - } - - get(id: string): AgentJobAsk | undefined { - return this.list().find((ask) => ask.id === id) - } - - threadAllowed(threadId: string): boolean { - return this.read().allowedThreads.includes(threadId) - } - - /** Records the ask, or returns the one the same call already made. */ - ask(input: { threadId: string; requestKey: string; job: AgentJobAsk['input'] }, now = new Date()): AgentJobAsk { - return this.change((file) => { - const earlier = file.asks.find((ask) => ask.requestKey === input.requestKey) - if (earlier) return earlier - const ask: AgentJobAsk = { id: randomUUID(), threadId: input.threadId, requestKey: input.requestKey, input: input.job, createdAt: now.toISOString(), state: 'open' } - file.asks.push(ask) - return ask - }) - } - - /** - * Answers an open ask. Allow runs `create` under the store's lock (so two answers cannot make two automations) and - * lets the thread add more; Not now only closes the ask. An ask already answered is refused. - */ - answer(id: string, answer: 'allow' | 'not_now', create: (ask: AgentJobAsk) => { id: string }, now = new Date()): AgentJobAsk { - return this.change((file) => { - const ask = file.asks.find((entry) => entry.id === id) - if (!ask) throw new Error('This request is gone.') - if (ask.state !== 'open') throw new Error('This request was already answered.') - if (answer === 'allow') { - const job = create(ask) - ask.jobId = job.id - if (!file.allowedThreads.includes(ask.threadId)) file.allowedThreads.push(ask.threadId) - } - ask.state = answer === 'allow' ? 'allowed' : 'declined' - ask.answeredAt = now.toISOString() - return ask - }) - } -} diff --git a/src/mms/automations/AutomationIndex.ts b/src/mms/automations/AutomationIndex.ts index 0423770f81..dd33450024 100644 --- a/src/mms/automations/AutomationIndex.ts +++ b/src/mms/automations/AutomationIndex.ts @@ -18,8 +18,6 @@ import { tellMeOf, type ScheduledJob, type ScheduledJobRunRecord, type Scheduled import { deliveryStartedRun, takesRequests } from '../../shared/requestTrigger' import { threadEventsOfOccurrence, threadEventText } from '../../shared/threadEvents' import type { BotAutomationFacts, BotAutomationRunStatus } from '../bots/chat/BotChatService' -import type { AgentJobAsk } from './AgentJobAsks' -import { describeSchedule } from '../../shared/scheduleLabel' import type { RemoteAutomationsPart } from '../protocol/remoteAutomationsPort' /** How many runs of each automation the list carries (the job keeps at most 20). */ @@ -40,8 +38,6 @@ export interface AutomationIndexSources { pendingApproval?(threadId: string): Extract | undefined /** A workflow run's open step approval, when it waits for one. */ workflowApproval?(runId: string): Extract | undefined - /** Agents' open first-creation asks: each is a Needs you item until it is answered. */ - asks?(): AgentJobAsk[] /** A saved agent's name, for a job whose Who is one; undefined when it is gone. */ savedAgentName?(definitionId: string): string | undefined watchStatus?(threadId: string): { state: 'watching' | 'paused' | 'ended' | 'off'; nextCheckAt: string | null } @@ -91,12 +87,6 @@ function savedAgentName(definitionId: string, sources: AutomationIndexSources): } } -/** One line of a prompt, cut, for a name. */ -function lineOf(text: string, max = 70): string { - const line = text.trim().split(/\r?\n/).find((part) => part.trim())?.trim() ?? '' - return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line -} - /** The effective May of a job: the strictest of its mode, its ceiling and the mode its thread runs in (a workflow's too, #338). */ export function jobEffectiveMay(job: ScheduledJob, threadMode: PermissionMode): PermissionMode { return narrowPermissionMode(job.permissionMode, job.permissionCeiling, threadMode) @@ -278,44 +268,6 @@ function jobItem(job: ScheduledJob, sources: AutomationIndexSources, computer: A } } -/** - * The words of an agent's first-creation ask: " wants to ", with what cut to one short line. - */ -export function askText(ask: Pick, threadName: string | undefined, now: Date = new Date()): string { - const what = lineOf(ask.input.prompt, 60) - const lowered = what ? what.charAt(0).toLowerCase() + what.slice(1) : 'add an automation' - return `${threadName ?? 'An agent'} wants to ${lowered} ${scheduleWords(ask.input.schedule, now)}`.trim() -} - -function scheduleWords(schedule: AgentJobAsk['input']['schedule'], now: Date): string { - if (schedule.kind === 'manual') return 'when you run it' - const text = describeSchedule(schedule, now) - return text.charAt(0).toLowerCase() + text.slice(1) -} - -function askItem(ask: AgentJobAsk, sources: AutomationIndexSources, computer: AutomationItem['computer']): AutomationItem { - const thread = sources.thread(ask.threadId) - const projectName = ask.input.projectId ? sources.projectName(ask.input.projectId) : undefined - const trigger = ask.input.schedule.kind === 'manual' ? 'on_demand' : 'time' - return { - key: `ask:${ask.id}`, - kind: 'ask', - id: ask.id, - name: ask.input.name, - trigger, - schedule: ask.input.schedule, - whenText: '', - who: { kind: 'agent', name: thread?.name ?? 'An agent' }, - ...(ask.input.projectId ? { where: { projectId: ask.input.projectId, name: projectName ?? 'Removed project' } } : {}), - paused: false, - runs: [], - addedBy: { threadId: ask.threadId, ...(thread?.name ? { threadName: thread.name } : {}) }, - attention: { kind: 'ask', text: askText(ask, thread?.name, sources.now?.()), threadId: ask.threadId, answer: { kind: 'agent_ask', askId: ask.id } }, - link: { kind: 'ask', askId: ask.id, threadId: ask.threadId }, - computer - } -} - /** * A scheduled run parked on a question or a wait (#1360), as work parks: not stopped at a missing permission. A question * waits for the owner's answer, as a held call does; a wait for a time or an event carries on by itself. Undefined for @@ -406,11 +358,6 @@ export function buildAutomationIndex(sources: AutomationIndexSources): Automatio } if (facts) items.push(botJobItem(job as ScheduledJob & { bot: NonNullable }, facts, computer, sources)) } - try { - for (const ask of sources.asks?.() ?? []) items.push(askItem(ask, sources, computer)) - } catch { - // The asks file could not be read: the jobs and the rest still show. - } if (sources.watchStatus) { try { for (const thread of sources.threads()) { diff --git a/src/mms/automations/registerMethods.ts b/src/mms/automations/registerMethods.ts index de64e84d67..fd1ced8594 100644 --- a/src/mms/automations/registerMethods.ts +++ b/src/mms/automations/registerMethods.ts @@ -3,7 +3,6 @@ import { isId } from '../../shared/net' import { isKeyName, MAX_KEY_VALUE_BYTES } from '../../shared/automationKeys' import type { ScheduledJob } from '../../shared/types' import type { AutomationInbox, InboxCounts, TuningNote } from '../../shared/automationInbox' -import type { AgentJobAsk } from './AgentJobAsks' import type { DraftWho } from './AutomationDrafts' import { DomainRpcError, domainObject, type DomainHandlerRegistry } from '../protocol/domainRegistry' @@ -14,8 +13,6 @@ export interface AutomationsDomain { * (over Bridge) gets only what it may see; anyone else (the CLI) gets this computer's. */ index(viewer: 'window' | 'computer' | 'local', signal?: AbortSignal): AutomationIndex | Promise - /** Allow or Not now on an agent's first-creation ask. */ - answerAsk(askId: string, answer: 'allow' | 'not_now'): AgentJobAsk /** Keep on an agent-added automation: removes only its end. */ keep(jobId: string): ScheduledJob | null /** Resend: runs a request automation again with the payload one of its deliveries stored. */ @@ -52,9 +49,8 @@ export interface AutomationsDomain { } /** - * The Automations page's methods: `automations.list` (jobs, bot schedules, pull request watches and agents' asks in one - * list; the page refreshes it when the scheduler or a bot changes, and every 15 seconds while it is open), - * `automations.asks.answer` and `automations.keep`. + * The Automations page's methods: `automations.list` (jobs, bot schedules and pull request watches in one list; the + * page refreshes it when the scheduler or a bot changes, and every 15 seconds while it is open) and `automations.keep`. */ export function registerAutomationMethods( domains: DomainHandlerRegistry, @@ -75,25 +71,6 @@ export function registerAutomationMethods( return (await bound(binding)).index(viewer, context.connection?.lifetime) } }) - domains.register({ - method: 'automations.asks.answer', - scope: 'profile', - capability: AUTOMATIONS_CAPABILITY, - validate: (params) => { - const p = domainObject(params ?? {}, ['profileId', 'askId', 'answer']) - if (typeof p.askId !== 'string' || !/^[0-9a-f-]{36}$/i.test(p.askId)) throw new DomainRpcError('invalid_params', 'An ask id is required') - if (p.answer !== 'allow' && p.answer !== 'not_now') throw new DomainRpcError('invalid_params', 'The answer is allow or not_now') - return p - }, - async handle(_context, params, binding) { - try { - return { ask: (await bound(binding)).answerAsk(params.askId as string, params.answer as 'allow' | 'not_now') } - } catch (error) { - if (error instanceof DomainRpcError) throw error - throw new DomainRpcError('ask_refused', error instanceof Error ? error.message : String(error)) - } - } - }) domains.register({ method: 'automations.request.resend', scope: 'profile', diff --git a/src/mms/config/MousseConfigStore.ts b/src/mms/config/MousseConfigStore.ts index a1bf25f03e..f1a1b92ace 100644 --- a/src/mms/config/MousseConfigStore.ts +++ b/src/mms/config/MousseConfigStore.ts @@ -336,7 +336,6 @@ export class MousseConfigStore { return level ? { ...rest, tellMe: level } : rest }), ...(raw.scheduled?.webhooks ? { webhooks: raw.scheduled.webhooks } : {}), - ...(typeof raw.scheduled?.agentJobs === 'boolean' ? { agentJobs: raw.scheduled.agentJobs } : {}), ...savedAgentJobLimits(raw.scheduled) }, mms: { ...base.mms, ...(raw.mms ?? {}) }, @@ -557,9 +556,6 @@ export class MousseConfigStore { if (partial.webhooks !== undefined) { this.conf.scheduled.webhooks = { ...partial.webhooks } } - if (partial.agentJobs !== undefined) { - this.conf.scheduled.agentJobs = partial.agentJobs === true - } // Checked before anything is written, so a refused value leaves every setting as it was. for (const key of Object.keys(AGENT_JOB_LIMIT_SETTINGS) as AgentJobLimitKey[]) { const value = partial[AGENT_JOB_LIMIT_SETTINGS[key]] @@ -572,11 +568,6 @@ export class MousseConfigStore { this.persist() } - /** Whether agents may use the scheduled-job tools (`scheduled.agentJobs`, off by default). Cheap: read at every tool call. */ - agentJobsEnabled(): boolean { - return this.conf.scheduled.agentJobs === true - } - /** * The limits on jobs agents create as they are now (`scheduled.agentJobMaxActive` and its siblings), each at its * default when unset or not a whole number in range. Cheap: read at every use, so a change needs no restart. diff --git a/src/mms/config/types.ts b/src/mms/config/types.ts index 574f9b1e6a..e40ed088a4 100644 --- a/src/mms/config/types.ts +++ b/src/mms/config/types.ts @@ -59,8 +59,6 @@ export interface ScheduledConfigSection { jobs: ScheduledJobDefinition[] /** The loopback listener for job webhooks; off until a job's webhook is enabled. */ webhooks?: { enabled: boolean; port: number } - /** Agents may list, create, change, pause and run jobs through the Mousse tools; off until a person turns it on. */ - agentJobs?: boolean /** Active jobs agents may have in the profile at once (1 to 100; unset reads as 10). Only a person sets it. */ agentJobMaxActive?: number /** The fewest minutes between runs of a job an agent creates or changes (1 to 1440; unset reads as 15). Only a person sets it. */ diff --git a/src/mms/run/mcp/appTools/schedules.ts b/src/mms/run/mcp/appTools/schedules.ts index 6b9f9e1a91..925e56ce3c 100644 --- a/src/mms/run/mcp/appTools/schedules.ts +++ b/src/mms/run/mcp/appTools/schedules.ts @@ -1,22 +1,21 @@ import type { PermissionMode } from '../../../../shared/permissionMode' -import { isWorkflowPrompt, permissionsAfterEdit } from '../../../scheduled/jobPermission' +import { permissionAboveCeiling, permissionsAfterEdit } from '../../../scheduled/jobPermission' import type { JobSchedule, ScheduledJob } from '../../../../shared/types' import { AGENT_JOB_LIMIT_DEFAULTS, type AgentJobLimits } from '../../../../shared/agentJobLimits' +import { isLocalOnlyThread } from '../../../../shared/threadLineage' import { agentJobExpiry, isActiveAgentJob, isExpired } from '../../../scheduled/agentJobLimits' import { runNowRefusal } from '../../../scheduled/runNowRefusal' import { cronProblem, minCronGapMinutes } from '../../../scheduled/computeNextRun' import { asCreateScheduledJobInput, asScheduledJobPatch } from '../../../protocol/validators' import type { RunEngine } from '../../RunEngine' import type { AgentScheduleHost, AppToolHost } from './host' -import { botThreadReach, lineageRelation } from './thread' +import { botThreadReach } from './thread' import { checkedInHandler, CLIENT_REQUEST_ID_SCHEMA, json, McpToolError, type MousseTool, type ToolCallContext } from './types' /** The prompt `schedule_list` returns is cut to this many characters. */ const PROMPT_LIST_CHARS = 2000 /** Run records `schedule_list` returns per job. */ const RECENT_RUNS = 3 -/** Subagent links followed up from a job's creating thread to the caller; a deeper chain is not the caller's. */ -const SUBAGENT_DEPTH = 64 /** * The run-store receipt kind that keeps what `schedule_delete` removed (docs/plans/tool-api.md §1.2 "Retry"), under three * keys: the delete's own request key, the job (`job:`), and the request key that created it (`created:`). A retry @@ -28,7 +27,7 @@ export const SCHEDULE_DELETE_RECEIPT = 'schedule_delete' function scheduleSchema(minMinutes: number) { return { type: 'object', - description: `When the job runs. kind "interval": minutes (at least ${minMinutes}). kind "cron": expr with exactly five fields whose minute field is a fixed list such as "0" or "15,45", with runs at least ${minMinutes} minutes apart. kind "once": runAt, an ISO date. kind "manual": no clock; a person's turn starts it with schedule_run.`, + description: `When the job runs. kind "interval": minutes (at least ${minMinutes}). kind "cron": expr with exactly five fields whose minute field is a fixed list such as "0" or "15,45", with runs at least ${minMinutes} minutes apart. kind "once": runAt, an ISO date. kind "manual": no clock; schedule_run starts it.`, properties: { kind: { type: 'string', enum: ['once', 'interval', 'cron', 'manual'] }, minutes: { type: 'integer', minimum: minMinutes }, @@ -48,11 +47,14 @@ const SELECTION_SCHEMA = { const WORKSPACE_SCHEMA = { type: 'object', - description: 'Where a per-run thread works: "project" (the project checkout, the default) or "newWorktree" (a fresh Git worktree per run, agent mode only). A job bound to a thread runs in that thread\'s own workspace.', - properties: { kind: { type: 'string', enum: ['project', 'newWorktree'] } }, + description: 'Where a per-run thread works: "project" (the project checkout, the default), "newWorktree" (a fresh Git worktree per run, agent mode only) or "worktree" with path (an existing worktree; the job then runs in the thread that owns it). A job bound to a thread runs in that thread\'s own workspace.', + properties: { kind: { type: 'string', enum: ['project', 'newWorktree', 'worktree'] }, path: { type: 'string' } }, required: ['kind'] } +const PERMISSION_MODE_SCHEMA = { type: 'string', enum: ['ask', 'edit', 'full'], description: 'The permission mode its runs work in; at most your own. Leave it out for the thread\'s mode.' } +const AGENT_SCHEMA = { type: 'object', description: 'A saved agent does the work instead of a model: { definitionId }.', properties: { definitionId: { type: 'string' } }, required: ['definitionId'] } + /** `args` without the named keys. */ function without(args: Record, ...keys: string[]): Record { return Object.fromEntries(Object.entries(args).filter(([key]) => !keys.includes(key))) @@ -70,19 +72,20 @@ function requiredId(args: Record, name: string): string { return value } -/** Inputs an agent may never set, with the reason it is told. */ +/** + * Inputs an agent never sets, with the reason it is told: a trigger from outside (a webhook, a pull request's events) + * would let input nobody checked start the agent's work, the saved keys its runs read are the person's secrets, and the + * fields that hold a job to its maker are Mousse's. + */ const FORBIDDEN_INPUTS: Readonly> = { trigger: 'Agent-created jobs cannot have a webhook trigger.', webhook: 'Agent-created jobs cannot have a webhook trigger.', + threadEvent: 'Agent-created jobs cannot wake on a pull request\'s events: use wake with pr instead.', + keys: 'The saved keys a job\'s runs read are chosen by a person.', accessCap: 'The access a job may be granted is set by Mousse from your own; you cannot choose it.', - permissionCeiling: 'The permission mode a job may run in is set by Mousse from your own; you cannot choose it.', - permissionMode: 'The permission mode a job runs in is set by Mousse from your own; you cannot choose it.', - heldTo: 'The permission mode a job may run in is set by Mousse from your own; you cannot choose it.', - createdBy: 'createdBy is set by Mousse.', - expiresAt: 'When a job ends is set by Mousse; only a person extends it.', - projectId: 'A job takes the project of your own thread; you cannot name another.', - createThread: 'createThread is not available to agents: leave threadId out for a thread per run.', - agent: 'A saved agent is chosen by a person; a job you create runs as you, no wider.' + permissionCeiling: 'The widest mode a job may run in is set by Mousse from your own; choose permissionMode instead.', + heldTo: 'The widest mode a job may run in is set by Mousse from your own; choose permissionMode instead.', + createdBy: 'createdBy is set by Mousse.' } function refuseForbidden(args: Record): void { @@ -117,37 +120,51 @@ export function scheduleRefusal(schedule: JobSchedule, minMinutes: number): stri return undefined } -/** A job that would start a workflow is refused: only a person starts one from a schedule. */ -function promptRefusal(prompt: string): string | undefined { - return isWorkflowPrompt(prompt) ? 'A job an agent creates cannot run workflows: its prompt may not start with "/".' : undefined +/** + * When an agent's job ends, as the agent asked (`expiresAt`): a time to come, never later than the end it may give. A new + * job ends at most the profile's lifetime from now; a job that already has an end may be brought forward, never pushed + * back (only a person extends a job past its lifetime); a job without an end (a person's, or one a person kept) may be + * given one. Undefined when the call does not name it. + */ +function expiryOf(value: unknown, latest: string | undefined, lifetimeDays: number): string | undefined { + if (value === undefined) return undefined + if (value === null) { + if (latest === undefined) return undefined + throw new Error('A job\'s end cannot be removed by an agent: only a person keeps a job past its lifetime.') + } + const at = typeof value === 'string' ? Date.parse(value) : NaN + if (!Number.isFinite(at)) throw new Error('expiresAt must be an ISO date and time.') + if (at <= Date.now()) throw new Error('expiresAt must be in the future.') + if (latest !== undefined && at > Date.parse(latest)) + throw new Error(`expiresAt can be at most ${latest}: a job made by an agent lasts ${lifetimeDays} ${lifetimeDays === 1 ? 'day' : 'days'}, and only a person extends it.`) + return new Date(at).toISOString() } /** * The job's permission mode and ceiling after an agent changed what it does: the stricter of the stored ceiling and the - * editor's, with the mode brought down to it (`permissionsAfterEdit`, an editor that cannot raise a ceiling). + * editor's, with the mode brought down to it, or the mode the agent chose when that is no wider (`permissionsAfterEdit`, + * an editor that cannot raise a ceiling). */ -function permissionFieldsAfterAgentEdit(job: ScheduledJob, editor: PermissionMode): Pick { - const edit = permissionsAfterEdit({ stored: job, editor, patchMode: undefined, executable: true, canRaise: false }) +function permissionFieldsAfterAgentEdit(job: ScheduledJob, editor: PermissionMode, patchMode: PermissionMode | null | undefined): Pick { + const edit = permissionsAfterEdit({ stored: job, editor, patchMode, executable: true, canRaise: false }) if (!edit.ok) throw new Error(edit.error) return { permissionMode: edit.permissionMode, permissionCeiling: edit.permissionCeiling } } /** * `schedule_list`, `schedule_create`, `schedule_update`, `schedule_pause`, `schedule_run` and `schedule_delete`: an - * agent's hand on the jobs its own thread made (docs/run-engine/SPEC.md §15.1). `schedule_delete` also removes a job one - * of the thread's subagents made; a subagent has these tools as its parent has them. The - * first automation a thread's agent adds is an ask the person answers (Allow or Not now); after Allow it adds more - * within the limits. Only a turn that holds `person` (a person started it, in a thread that is not a subagent: §1.3) may - * create or start a job or change what one does (`needsPerson`), so no scheduled run, agent message, remote send or - * subagent can make jobs of its own and no chain of jobs can form. A job an - * agent creates runs no wider than the agent that made it (its permission mode is recorded on the job, and a later - * change can only narrow it), ends after the profile's lifetime for such jobs unless a person - * extends it, and counts against a profile-wide cap. The three limits are settings only a person changes - * (`schedules.jobLimits`, read at every use, so the tool text and checks follow a change at once; no tool writes - * them). Offered over MCP only, like the other tools that act on the profile. + * agent's hand on the profile's scheduled jobs (docs/run-engine/SPEC.md §15.1). Every agent, a subagent's included, sees + * and changes every job of the profile, a person's too, across the private line only as every thread tool does; a + * personal bot sees and changes only the jobs it made ("schedule work in your threads"). A job an agent creates is made + * at once. It runs no wider than the agent that made or last changed it (its ceiling is that agent's permission mode, + * recorded on the job, and a change never raises it), cannot be started by input from outside (no webhook or pull + * request trigger), ends after the profile's lifetime for such jobs unless a person extends it, and counts against a + * profile-wide cap. The three limits are settings only a person changes (`schedules.jobLimits`, read at every use, so the + * tool text and checks follow a change at once; no tool writes them). Offered over MCP only, like the other tools that + * act on the profile. */ -/** A private thread's job runs only in that thread or its lineage, never in new threads that are shared. */ -const PRIVATE_JOB_REFUSAL = 'This is a private thread: a job that makes a new thread for each run would share that thread with the user\'s other devices. Give threadId (this thread or one of its lineage) so the job runs here.' +/** A private thread's job runs only in a private thread, never in new threads that are shared. */ +const PRIVATE_JOB_REFUSAL = 'This is a private thread: a job that makes a new thread for each run would share that thread with the user\'s other devices. Give threadId (a private thread) so the job runs there.' export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[] { // The profile hands its scheduled jobs over after the registry is built: every use reads them then. @@ -160,35 +177,34 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ } }) const limitsNow = (): AgentJobLimits => (host.schedules ? host.schedules.jobLimits() : AGENT_JOB_LIMIT_DEFAULTS) - const allowed = (threadId: string): boolean => { - try { - return schedules.threadAllowed(threadId) - } catch { - return false - } - } const projectOf = (job: Pick): string | undefined => job.projectId ?? (job.threadId ? host.threadMeta?.(job.threadId)?.projectId : undefined) /** - * Whose jobs the caller makes and sees: its own thread's. A personal bot's are the bot's ("schedule work in your - * threads"), whichever of its turns made them: they are filed under its chat thread. + * The thread a job is filed under when the caller makes it: its own thread's. A personal bot's are the bot's ("schedule + * work in your threads"), whichever of its turns made them: they are filed under its chat thread. */ const ownerOf = (ctx: ToolCallContext): string => (ctx.turn.bot ? host.botHomeOf?.(ctx.caller.threadId) ?? ctx.caller.threadId : ctx.caller.threadId) - /** The jobs an agent may see and change: the ones made through these tools by its own thread. A person's job is never one. */ - const visible = (job: ScheduledJob, ctx: ToolCallContext): boolean => job.createdBy?.threadId === ownerOf(ctx) - /** The thread that delegated `threadId` as a subagent; undefined for a thread that is no one's subagent (a fork is not one). */ - const subagentParent = (threadId: string): string | undefined => { - const lineage = engine.delegations.getLineage(threadId) - return lineage?.relationship === 'subagent' ? lineage.parentThreadId : undefined + /** Whether `threadId` is a private thread, or one below a private thread. */ + const privateThread = (threadId: string | undefined): boolean => { + if (!threadId) return false + const thread = host.threadMeta?.(threadId) + if (!thread) return false + return isLocalOnlyThread(thread, thread.lineage?.rootThreadId ? host.listThreads?.() ?? [] : undefined) } - /** Whether a subagent of the caller (or a subagent of one of those) made the job through these tools. */ - const madeBySubagent = (job: ScheduledJob, ctx: ToolCallContext): boolean => { - let current = job.createdBy?.threadId - for (let depth = 0; current && depth < SUBAGENT_DEPTH; depth += 1) { - current = subagentParent(current) - if (current === ctx.caller.threadId) return true - } - return false + /** A job of a private thread: bound to one, or made by one. */ + const privateJob = (job: ScheduledJob): boolean => privateThread(job.threadId) || privateThread(job.createdBy?.threadId) + /** + * The jobs an agent sees: every job of the profile (a bot's schedules are never among them), except across the private + * line: a shared thread's agent never sees a private thread's job. A personal bot sees only the ones it made. + */ + const visible = (job: ScheduledJob, ctx: ToolCallContext): boolean => { + if (ctx.turn.bot) return job.createdBy?.threadId === ownerOf(ctx) + return !privateJob(job) || privateThread(ctx.caller.threadId) + } + /** The jobs an agent changes: those it sees, and from a private thread only private threads' jobs. */ + const changeable = (job: ScheduledJob, ctx: ToolCallContext): boolean => { + if (!visible(job, ctx)) return false + return ctx.turn.bot !== undefined || !privateThread(ctx.caller.threadId) || privateJob(job) } /** Jobs this tool set removed, by job id and by request key, so a repeat or a retry is answered rather than refused. */ type Removal = { removedBy: string; job: { id: string; name: string } } @@ -201,10 +217,11 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ if (engine.store.getReceipt(clientRequestId)) return engine.store.putReceipt({ clientRequestId, threadId: entry.removedBy, commandKind: SCHEDULE_DELETE_RECEIPT, status: 'accepted', result: entry, createdAt: new Date().toISOString() }) } - const findVisible = (id: string, ctx: ToolCallContext): ScheduledJob => { + const findChangeable = (id: string, ctx: ToolCallContext): ScheduledJob => { const job = schedules.get(id) // A job the caller may not see is refused the same way whether it exists or not. - if (!job || !visible(job, ctx)) throw new McpToolError('mousse_scope_denied', `No scheduled job ${id} that you made.`) + if (!job || !visible(job, ctx)) throw new McpToolError('mousse_scope_denied', `No scheduled job ${id}. schedule_list shows the jobs you can change.`) + if (!changeable(job, ctx)) throw new McpToolError('mousse_scope_denied', 'This is a private thread: its agents cannot change a job of a thread that is shared with the user\'s other devices.') return job } /** Every change an agent makes is an `agent.action` event on its own thread, with a row in its transcript. */ @@ -220,16 +237,24 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ console.warn('a scheduled-job change by an agent could not be recorded', { jobId: job.id, error: error instanceof Error ? error.message : String(error) }) } } - /** A thread a job may be bound to: the caller's own or one in its delegation lineage; never a bot's, never an archived one. */ + /** A change to a job another agent's thread made shows in that thread too, by whom. */ + const recordForMaker = (ctx: ToolCallContext, action: string, job: ScheduledJob, summaryText: string): void => { + const maker = job.createdBy?.threadId + if (maker && maker !== ctx.caller.threadId && maker !== ownerOf(ctx)) record(ctx, action, job, `${summaryText}, which this thread made; by thread ${ctx.caller.threadId}`, { threadId: maker }) + } + /** A thread a job may be bound to: any thread of the profile the caller may reach; never a bot's, never an archived one. */ const checkTarget = (threadId: string, ctx: ToolCallContext): void => { // A personal bot binds a job to one of its owner's threads it may reach (`botThreadReach`), never its own. if (ctx.turn.bot) { const reach = botThreadReach(host, engine, ctx.caller.threadId, threadId) if ('refused' in reach) throw new McpToolError('mousse_scope_denied', reach.refused) - } else if (threadId !== ctx.caller.threadId && lineageRelation(engine, ctx.caller.threadId, threadId) === null) - throw new McpToolError('mousse_scope_denied', `Thread ${threadId} is not this thread or one of its lineage; a job can only be bound to those.`) + } const thread = host.threadMeta?.(threadId) - if (!thread) throw new Error(`Thread ${threadId} was not found.`) + const callerPrivate = privateThread(ctx.caller.threadId) + const targetPrivate = privateThread(threadId) + // A private thread is refused the same way whether it exists or not. + if (!thread || (targetPrivate && !callerPrivate)) throw new Error(`Thread ${threadId} was not found.`) + if (callerPrivate && !targetPrivate) throw new McpToolError('mousse_scope_denied', 'This is a private thread: its agents cannot bind a job to a thread that is shared with the user\'s other devices.') if (thread.archivedAt) throw new Error(`Thread ${threadId} is archived; a job cannot be bound to it.`) let role: string | undefined try { @@ -239,6 +264,13 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ } if (role) throw new McpToolError('mousse_scope_denied', `Thread ${threadId} belongs to a bot; a job cannot be bound to it.`) } + /** A project the job may run in: one of the profile's. */ + const checkProject = (projectId: unknown): string => { + if (typeof projectId !== 'string' || !projectId.trim()) throw new Error('projectId must be one of the profile\'s projects (thread_list).') + const id = projectId.trim() + if (!host.listProjects?.().some((project) => project.id === id)) throw new Error(`There is no project ${id}.`) + return id + } const summary = (job: ScheduledJob, ctx: ToolCallContext) => ({ id: job.id, name: job.name, @@ -255,13 +287,17 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ projectId: job.projectId ?? null, selection: job.selection ?? null, workspace: job.workspace ?? null, + ...(job.agent ? { agent: job.agent } : {}), + ...(job.createThread ? { createThread: true } : {}), ...(job.repeat ? { repeat: job.repeat } : {}), createdByAgent: Boolean(job.createdBy), createdByYou: job.createdBy?.threadId === ownerOf(ctx), - ...(job.createdBy && job.createdBy.threadId !== ownerOf(ctx) ? { createdBySubagent: job.createdBy.threadId } : {}), + ...(job.createdBy && job.createdBy.threadId !== ownerOf(ctx) ? { createdByThread: job.createdBy.threadId } : {}), ...(job.expiresAt ? { expiresAt: job.expiresAt } : {}), ...(job.pausedReason ? { pausedReason: job.pausedReason } : {}), + ...(job.permissionMode ? { permissionMode: job.permissionMode } : {}), ...(job.permissionCeiling ? { permissionCeiling: job.permissionCeiling } : {}), + ...(job.trigger?.webhook ? { webhook: true } : {}), ...(job.pendingOccurrence ? { pendingRun: job.pendingOccurrence.state } : job.state === 'running' ? { pendingRun: 'running' } : {}), recentRuns: (job.runHistory ?? []).slice(-RECENT_RUNS).reverse().map((record) => ({ runAt: record.runAt, @@ -277,13 +313,20 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ if (active >= maxActive) throw new Error(`The profile already has ${active} active jobs made by agents (the limit is ${maxActive}). Pause one with schedule_pause, wait for one to end, or ask the user.`) } + /** Resumes a paused job; one an agent made counts against the cap again, so it needs room. */ + const resume = (job: ScheduledJob): ScheduledJob => { + if (job.createdBy && !isActiveAgentJob(job)) assertRoomForAnotherJob() + const resumed = schedules.resume(job.id) + if (!resumed) throw new Error(`Job ${job.id} no longer exists.`) + return resumed + } const common = { access: 'managesOthers' as const, - // The central check reads this as a listing. Which jobs the caller may touch is the handler's decision (`visible`): - // the ones its own thread made. + // The central check reads this as a listing. Which jobs the caller may touch is the handler's decision (`visible`, + // `changeable`), and the thread it binds one to is checked there too (`checkTarget`). target: () => ({}), - authorize: checkedInHandler('the handlers accept the caller\'s own thread or its lineage only (checkTarget)'), + authorize: checkedInHandler('the handlers check every job and thread they reach (visible, changeable, checkTarget)'), offered: () => false, listed: () => host.schedules !== undefined, available: () => (host.schedules ? true as const : 'Scheduled jobs are not available in this profile.') @@ -294,11 +337,12 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ ...common, name: 'schedule_list', description: - 'List the scheduled jobs your thread created, and the ones your subagents created (createdBySubagent names the subagent\'s thread: you may remove those with schedule_delete, not change them). Jobs a person made, and jobs other threads made, are not shown and cannot be changed. Each job shows its cadence, state, when it ends, last runs and the limits its runs have.', + 'List the profile\'s scheduled jobs: the ones people made, yours, and those other agents made (createdByThread names the thread that made one). Each job shows its cadence, state, when it ends, last runs and the limits its runs have. You may change any of them with the other schedule_* tools.', + botDescription: 'List the scheduled jobs you made for your owner, with their cadence, state, when each ends, last runs and the limits its runs have.', inputSchema: { type: 'object', properties: {} }, class: 'read', handler: (_args, ctx) => { - const jobs = schedules.list().filter((job) => visible(job, ctx) || madeBySubagent(job, ctx)).map((job) => summary(job, ctx)) + const jobs = schedules.list().filter((job) => visible(job, ctx)).map((job) => summary(job, ctx)) return json({ jobs }) } }, @@ -308,12 +352,12 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ // Read at every listing: the tool is built once, and a person may change the limits at any time. get description() { const limits = limitsNow() - return `Create a scheduled job that runs a prompt later or on a cadence, as a turn in a thread (needs a turn a person started, or a subagent of one: a job, another agent's message or a remote send cannot create jobs; the first time, the person is asked and the job is made only if they allow it; a subagent's every job is asked). The job outlives this run. It runs no wider than you do: its runs get at most your permission mode. It takes your thread's project. Leave threadId out for a new thread per run, or give your own thread or one of your lineage. Not allowed: a prompt that starts with "/", a webhook trigger, a worktree workspace, an interval under ${limits.minIntervalMinutes} minutes. The profile allows ${limits.maxActive} active jobs made by agents in all, and a job ends ${limits.lifetimeDays} days after it is made unless a person extends it. A person sets these limits; you cannot change them. The job is labelled as made by an agent and each change you make is recorded in your thread. Use schedule_run to start it at once.` + return `Create a scheduled job that runs a prompt later or on a cadence, as a turn in a thread; it is made at once and outlives this run. It runs no wider than you do: permissionMode may be at most your own mode. Leave threadId out for a new thread per run (in projectId, else your thread's project), or bind it to any thread. You may pick a model (selection), a saved agent (agent), a workspace (an existing worktree too), a prompt that starts with "/" (a workflow), a number of runs (repeat) and an earlier end (expiresAt). Not allowed: a webhook or pull request trigger, an interval under ${limits.minIntervalMinutes} minutes. The profile allows ${limits.maxActive} active jobs made by agents in all, and a job ends ${limits.lifetimeDays} days after it is made unless a person extends it. A person sets these limits; you cannot change them. The job is labelled as made by an agent and each change you make is recorded in your thread. Use schedule_run to start it at once.` }, // A personal bot ("schedule work in your threads"): its owner allowed its jobs once, and it names where they run. get botDescription() { const limits = limitsNow() - return `Create a scheduled job for your owner that runs a prompt later or on a cadence, as Mousse's Scheduled jobs do: a turn in one of your owner's threads (threadId) or a new thread per run in one of their projects (projectId). Use it when your owner asks for work in their threads on a schedule; for something only you do at a time, use bot_schedule_add. Your owner allowed this, so nothing asks first. Its runs work in Full access (or no wider than the device your owner wrote from). Not allowed: a prompt that starts with "/", a webhook trigger, a worktree workspace, an interval under ${limits.minIntervalMinutes} minutes. The profile allows ${limits.maxActive} active jobs made by agents in all, and a job ends ${limits.lifetimeDays} days after it is made unless your owner extends it. You see and change only the jobs you made. Use schedule_run to start it at once.` + return `Create a scheduled job for your owner that runs a prompt later or on a cadence, as Mousse's Scheduled jobs do: a turn in one of your owner's threads (threadId) or a new thread per run in one of their projects (projectId). Use it when your owner asks for work in their threads on a schedule; for something only you do at a time, use bot_schedule_add. Your owner allowed this, so nothing asks first. Its runs work in Full access (or no wider than the device your owner wrote from). Not allowed: a webhook or pull request trigger, an interval under ${limits.minIntervalMinutes} minutes. The profile allows ${limits.maxActive} active jobs made by agents in all, and a job ends ${limits.lifetimeDays} days after it is made unless your owner extends it. You see and change only the jobs you made. Use schedule_run to start it at once.` }, get botInputSchema() { const schema = this.inputSchema as { properties: Record } @@ -331,12 +375,17 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ type: 'object', properties: { name: { type: 'string' }, - prompt: { type: 'string', description: 'What the run is asked to do, written for an agent that has none of this conversation.' }, + prompt: { type: 'string', description: 'What the run is asked to do, written for an agent that has none of this conversation. A prompt that starts with "/" runs that workflow.' }, schedule: scheduleSchema(limitsNow().minIntervalMinutes), selection: SELECTION_SCHEMA, + agent: AGENT_SCHEMA, workspace: WORKSPACE_SCHEMA, - threadId: { type: 'string', description: 'Run in this thread (yours or one of your lineage); a new thread per run when omitted.' }, + permissionMode: PERMISSION_MODE_SCHEMA, + threadId: { type: 'string', description: 'Run in this thread (thread_list); a new thread per run when omitted.' }, + projectId: { type: 'string', description: 'For a new thread per run: this project (thread_list\'s projects) instead of your thread\'s.' }, + createThread: { type: 'boolean', description: 'With threadId: true makes a new thread per run in that thread\'s project instead of running in it.' }, repeat: { type: 'object', properties: { times: { type: 'integer', minimum: 1 } }, description: 'Stop after this many runs.' }, + expiresAt: { type: 'string', description: `When the job ends, an ISO date and time; at most ${limitsNow().lifetimeDays} days from now (the default).` }, clientRequestId: CLIENT_REQUEST_ID_SCHEMA }, required: ['name', 'prompt', 'schedule'] @@ -344,14 +393,8 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ }, class: 'mutation', handler: (args, ctx) => { - // A personal bot has no project of its own: a job that starts a new thread per run names the project. Any other - // caller's job takes its thread's project, so naming one is refused as before. + refuseForbidden(args) const bot = Boolean(ctx.turn.bot) - const { projectId: _named, ...checkedArgs } = args - refuseForbidden(bot ? checkedArgs : args) - if (bot && args.projectId !== undefined && (typeof args.projectId !== 'string' || !args.projectId.trim())) - throw new Error('projectId must be one of your owner\'s projects (thread_list).') - const botProject = bot && typeof args.projectId === 'string' ? args.projectId.trim() : undefined const owner = ownerOf(ctx) const requestKey = `schedule_create:${owner}:${toolRequestId(args, ctx)}` // A retry of a call that already made its job returns that job and changes nothing, however many jobs exist. @@ -360,51 +403,47 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ // The job this key made was removed since: a stale retry says so and does not make it again. const gone = removal(`created:${requestKey}`) if (gone) return json({ job: gone.job, replayed: true, removed: true, note: 'This call already made this job, and it was removed since; nothing was made. Use a new clientRequestId to make a new one.' }) - const { projectId: _botProject, ...rest } = args - const input = asCreateScheduledJobInput(without(rest, 'clientRequestId')) - const refusal = scheduleRefusal(input.schedule, limitsNow().minIntervalMinutes) ?? promptRefusal(input.prompt) + const limits = limitsNow() + const maxEnd = agentJobExpiry(limits.lifetimeDays) + const expiresAt = expiryOf(args.expiresAt, maxEnd, limits.lifetimeDays) ?? maxEnd + const input = asCreateScheduledJobInput(without(args, 'clientRequestId', 'expiresAt')) + const refusal = scheduleRefusal(input.schedule, limits.minIntervalMinutes) if (refusal) throw new Error(refusal) - if (input.workspace?.kind === 'worktree') throw new Error('A job an agent creates cannot run in an existing worktree.') const caller = host.threadMeta?.(ctx.caller.threadId) if (!caller) throw new Error(`Thread ${ctx.caller.threadId} was not found.`) - if (!input.threadId && caller.localOnly === true) throw new Error(PRIVATE_JOB_REFUSAL) - let projectId = bot ? botProject : caller.projectId - if (input.threadId) { - checkTarget(input.threadId, ctx) - projectId = host.threadMeta?.(input.threadId)?.projectId - } else if (bot && !botProject) { + const namedProject = input.projectId !== undefined ? checkProject(input.projectId) : undefined + if (input.threadId) checkTarget(input.threadId, ctx) + const perRun = !input.threadId || input.createThread === true + if (perRun && privateThread(ctx.caller.threadId) && input.workspace?.kind !== 'worktree') throw new Error(PRIVATE_JOB_REFUSAL) + if (bot && !input.threadId && !namedProject) throw new Error('Name where its runs happen: threadId (one of your owner\'s threads) for a turn there, or projectId (one of their projects) for a new thread per run.') - } else if (bot && !host.listProjects?.().some((project) => project.id === botProject)) { - throw new Error(`There is no project ${botProject}.`) - } + const projectId = namedProject ?? (input.threadId ? host.threadMeta?.(input.threadId)?.projectId : bot ? undefined : caller.projectId) const candidate = { ...(input.threadId ? { threadId: input.threadId } : {}), ...(projectId ? { projectId } : {}), ...(input.selection ? { selection: input.selection } : {}), ...(input.workspace ? { workspace: input.workspace } : {}) } const checked = schedules.validate(candidate) - const limits = schedules.limits(ctx.caller) + // A `worktree` workspace names the thread that owns it: the job runs there, and that thread is checked like any. + if (checked.threadId && checked.threadId !== input.threadId) checkTarget(checked.threadId, ctx) + const held = schedules.limits(ctx.caller) + const tooWide = permissionAboveCeiling(input.permissionMode, held.permissionCeiling) + if (tooWide) throw new Error(tooWide) const job = { name: input.name, prompt: input.prompt, schedule: input.schedule, ...candidate, + ...(checked.threadId ? { threadId: checked.threadId } : {}), ...(checked.selection ? { selection: checked.selection } : {}), + ...(input.createThread !== undefined ? { createThread: input.createThread } : {}), + ...(input.agent ? { agent: input.agent } : {}), + ...(input.permissionMode ? { permissionMode: input.permissionMode } : {}), + ...(input.tellMe ? { tellMe: input.tellMe } : {}), ...(input.repeat ? { repeat: input.repeat } : {}), createdBy: { threadId: owner, runId: ctx.caller.runId, requestId: requestKey }, - permissionCeiling: limits.permissionCeiling, - ...(limits.heldTo ? { heldTo: limits.heldTo } : {}) - } - // The first time, the person is asked; the job is made only when they allow it, which also lets this thread add more. - // A personal bot's owner allowed "schedule work in your threads" once: that is their Allow for the bot's jobs. - // A subagent never gets here: it does not hold `person`. - if (!bot && !allowed(ctx.caller.threadId)) { - const ask = schedules.askFirst({ threadId: ctx.caller.threadId, requestKey, job }) - return json({ - waiting: true, - askId: ask.id, - message: `Not created yet: the person is asked whether to add "${job.name}" (Allow or Not now). It is made only if they allow it; do not ask again or retry. Tell them it is waiting for their answer in Automations.` - }) + permissionCeiling: held.permissionCeiling, + ...(held.heldTo ? { heldTo: held.heldTo } : {}) } // Counted from the saved jobs, right before the job is saved, with nothing awaited in between. assertRoomForAnotherJob() - const created = schedules.create({ ...job, expiresAt: agentJobExpiry(limitsNow().lifetimeDays) }) + const created = schedules.create({ ...job, expiresAt }) record(ctx, 'scheduled_job_created', created, `created scheduled job "${created.name}" (${created.id})`) return json({ job: summary(created, ctx) }) } @@ -413,7 +452,8 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ ...common, name: 'schedule_update', description: - 'Change a scheduled job your thread created. Pass jobId and only the fields to change; null clears model, workspace or thread back to the default. Changing anything but the name needs a turn a person started. The rules of schedule_create hold. A change can only narrow the access and permission mode its runs get, to yours at most, and can only shorten how many runs it has; it never lengthens the job\'s life. To pause a job use schedule_pause; resuming or extending one is for a person.', + 'Change any scheduled job of the profile (schedule_list), a person\'s too. Pass jobId and only the fields to change; null clears model, saved agent, workspace, thread, project, permission mode or repeat back to the default. enabled: true resumes a paused job, false pauses it. The rules of schedule_create hold: a change can raise the job\'s permission mode up to your own, never its ceiling, and never wider than yours; expiresAt may bring its end forward, never past the end it has (only a person extends a job).', + botDescription: 'Change a scheduled job you made. Pass jobId and only the fields to change; null clears model, workspace or thread back to the default. enabled: true resumes it, false pauses it. Its runs never get wider access than your owner gave you; only your owner extends a job past its end.', get inputSchema() { return { type: 'object', @@ -422,10 +462,16 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ name: { type: 'string' }, prompt: { type: 'string' }, schedule: scheduleSchema(limitsNow().minIntervalMinutes), + enabled: { type: 'boolean', description: 'true resumes the job, false pauses it.' }, selection: { ...SELECTION_SCHEMA, type: ['object', 'null'] }, + agent: { ...AGENT_SCHEMA, type: ['object', 'null'] }, workspace: { ...WORKSPACE_SCHEMA, type: ['object', 'null'] }, - threadId: { type: ['string', 'null'], description: 'Your thread or one of your lineage; null for a new thread per run.' }, - repeat: { type: ['object', 'null'], properties: { times: { type: 'integer', minimum: 1 } } } + permissionMode: { ...PERMISSION_MODE_SCHEMA, type: ['string', 'null'] }, + threadId: { type: ['string', 'null'], description: 'A thread to run in (thread_list); null for a new thread per run.' }, + projectId: { type: ['string', 'null'], description: 'The project of a new thread per run.' }, + createThread: { type: 'boolean' }, + repeat: { type: ['object', 'null'], properties: { times: { type: 'integer', minimum: 1 } } }, + expiresAt: { type: 'string', description: 'An earlier end, as an ISO date and time.' } }, required: ['jobId'] } @@ -433,57 +479,62 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ class: 'mutation', handler: (args, ctx) => { refuseForbidden(args) - if (args.enabled !== undefined) throw new Error('schedule_update does not change whether a job is enabled: pause it with schedule_pause; a person resumes it.') - const job = findVisible(requiredId(args, 'jobId'), ctx) - const patch = asScheduledJobPatch(without(args, 'jobId')) - if (Object.keys(patch).length === 0) throw new Error('Pass at least one field to change.') - const executable = Object.keys(patch).some((key) => key !== 'name') - if (executable && isWorkflowPrompt(job.prompt)) throw new Error('This job runs a workflow; an agent does not change those.') - if (patch.repeat === null) throw new Error('A job\'s number of runs cannot be removed; it can only be shortened.') - if (patch.repeat?.times !== undefined && job.repeat?.times !== undefined && patch.repeat.times > job.repeat.times) - throw new Error(`A job's number of runs can only be shortened (it has ${job.repeat.times}).`) - if (patch.prompt !== undefined) { - const refusal = promptRefusal(patch.prompt) - if (refusal) throw new Error(refusal) - } + const job = findChangeable(requiredId(args, 'jobId'), ctx) + const expiresAt = expiryOf(args.expiresAt, job.expiresAt, limitsNow().lifetimeDays) + const { enabled, ...patch } = asScheduledJobPatch(without(args, 'jobId', 'expiresAt')) + if (Object.keys(patch).length === 0 && enabled === undefined && expiresAt === undefined) throw new Error('Pass at least one field to change.') if (patch.schedule) { const refusal = scheduleRefusal(patch.schedule, limitsNow().minIntervalMinutes) if (refusal) throw new Error(refusal) } - if (patch.workspace?.kind === 'worktree') throw new Error('A job an agent changes cannot run in an existing worktree.') + if (job.trigger?.webhook && patch.schedule?.kind === 'once') throw new Error('A job with a webhook cannot become a one-time job.') + if (job.trigger?.threadEvent && patch.schedule && patch.schedule.kind !== 'manual') throw new Error('It wakes on its pull request, so it has no clock.') + const namedProject = typeof patch.projectId === 'string' ? checkProject(patch.projectId) : undefined + if (typeof patch.threadId === 'string') checkTarget(patch.threadId, ctx) // The thread the job is bound to follows the project it belongs to; a cleared thread keeps the project it had. - let projectId = job.projectId - if (typeof patch.threadId === 'string') { - checkTarget(patch.threadId, ctx) - projectId = host.threadMeta?.(patch.threadId)?.projectId - } else if (patch.threadId === null) { - if (host.threadMeta?.(ctx.caller.threadId)?.localOnly === true) throw new Error(PRIVATE_JOB_REFUSAL) - projectId = projectOf(job) - } + let projectId = patch.projectId === null ? undefined : namedProject ?? job.projectId + if (typeof patch.threadId === 'string' && namedProject === undefined) projectId = host.threadMeta?.(patch.threadId)?.projectId + else if (patch.threadId === null && namedProject === undefined && patch.projectId === undefined) projectId = projectOf(job) + const threadAfter = patch.threadId === undefined ? job.threadId : patch.threadId ?? undefined + const perRunAfter = !threadAfter || (patch.createThread ?? job.createThread) === true + const workspaceAfter = patch.workspace === undefined ? job.workspace : patch.workspace ?? undefined + if (perRunAfter && privateThread(ctx.caller.threadId) && workspaceAfter?.kind !== 'worktree') throw new Error(PRIVATE_JOB_REFUSAL) const merged = { - threadId: patch.threadId === undefined ? job.threadId : patch.threadId ?? undefined, + threadId: threadAfter, projectId, selection: patch.selection === undefined ? job.selection : patch.selection ?? undefined, - workspace: patch.workspace === undefined ? job.workspace : patch.workspace ?? undefined + workspace: workspaceAfter } - const touchesOptions = ['selection', 'workspace', 'threadId'].some((key) => (patch as Record)[key] !== undefined) + const touchesOptions = ['selection', 'workspace', 'threadId', 'projectId'].some((key) => (patch as Record)[key] !== undefined) const checked = touchesOptions ? schedules.validate(merged) : {} - const limits = executable ? schedules.limits(ctx.caller) : undefined + if (checked.threadId && checked.threadId !== threadAfter) checkTarget(checked.threadId, ctx) + const executable = Object.keys(patch).some((key) => key !== 'name') + const held = executable ? schedules.limits(ctx.caller) : undefined const changes: Partial = { ...(patch.name !== undefined ? { name: patch.name } : {}), ...(patch.prompt !== undefined ? { prompt: patch.prompt.trim() } : {}), ...(patch.schedule !== undefined ? { schedule: patch.schedule } : {}), - ...(patch.threadId !== undefined ? { threadId: patch.threadId ?? undefined, projectId } : {}), + ...(patch.threadId !== undefined || checked.threadId ? { threadId: checked.threadId ?? threadAfter } : {}), + ...(patch.threadId !== undefined || patch.projectId !== undefined ? { projectId } : {}), + ...(patch.createThread !== undefined ? { createThread: patch.createThread } : {}), ...(patch.selection !== undefined ? { selection: patch.selection === null ? undefined : checked.selection ?? patch.selection } : {}), + ...(patch.agent !== undefined ? { agent: patch.agent ?? undefined } : {}), ...(patch.workspace !== undefined ? { workspace: patch.workspace ?? undefined } : {}), - ...(patch.repeat !== undefined && patch.repeat !== null ? { repeat: { times: patch.repeat.times, completed: job.repeat?.completed ?? 0 } } : {}), - // Whatever mode the job could run in before, it can run in no wider one now: the narrower of what it had and what - // this caller holds. It is never raised. - ...(limits ? permissionFieldsAfterAgentEdit(job, limits.permissionCeiling) : {}) + ...(patch.tellMe !== undefined ? { tellMe: patch.tellMe } : {}), + ...(patch.repeat === null ? { repeat: undefined } : patch.repeat !== undefined ? { repeat: { times: patch.repeat.times, completed: job.repeat?.completed ?? 0 } } : {}), + ...(expiresAt !== undefined ? { expiresAt } : {}), + // Whatever mode the job could run in before, its ceiling is now no wider than this caller's: the narrower of what + // it had and what this caller holds. A mode the caller chose is kept when it is no wider than that. + ...(held ? permissionFieldsAfterAgentEdit(job, held.permissionCeiling, patch.permissionMode) : {}) } - const updated = schedules.update(job.id, changes) + let updated = Object.keys(changes).length ? schedules.update(job.id, changes) : job if (!updated) throw new Error(`Job ${job.id} no longer exists.`) - record(ctx, 'scheduled_job_updated', updated, `changed ${Object.keys(patch).join(', ')} of scheduled job "${updated.name}" (${updated.id})`) + if (enabled === true && (!updated.enabled || updated.state === 'paused')) updated = resume(updated) + if (enabled === false && updated.enabled && updated.state !== 'paused') updated = schedules.pause(job.id, 'Paused by an agent') ?? updated + const changed = [...Object.keys(patch), ...(enabled !== undefined ? ['enabled'] : []), ...(expiresAt !== undefined ? ['expiresAt'] : [])].join(', ') + const text = `changed ${changed} of scheduled job "${updated.name}" (${updated.id})` + record(ctx, 'scheduled_job_updated', updated, text) + recordForMaker(ctx, 'scheduled_job_updated', updated, text) return json({ job: summary(updated, ctx) }) } }, @@ -491,7 +542,8 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ ...common, name: 'schedule_pause', description: - 'Pause a scheduled job your thread created, so it starts no further runs. A run in progress finishes. Only a person resumes a paused job.', + 'Pause any scheduled job of the profile, so it starts no further runs. A run in progress finishes. schedule_update with enabled: true, or schedule_run, resumes it.', + botDescription: 'Pause a scheduled job you made, so it starts no further runs. A run in progress finishes.', inputSchema: { type: 'object', properties: { jobId: { type: 'string' }, reason: { type: 'string', description: 'Shown next to the paused job.' } }, @@ -499,12 +551,14 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ }, class: 'mutation', handler: (args, ctx) => { - const job = findVisible(requiredId(args, 'jobId'), ctx) + const job = findChangeable(requiredId(args, 'jobId'), ctx) if (args.reason !== undefined && typeof args.reason !== 'string') throw new Error('reason must be a string') const reason = `Paused by an agent${typeof args.reason === 'string' && args.reason.trim() ? `: ${args.reason.trim()}` : ''}`.slice(0, 512) const paused = schedules.pause(job.id, reason) if (!paused) throw new Error(`Job ${job.id} no longer exists.`) - record(ctx, 'scheduled_job_paused', paused, `paused scheduled job "${paused.name}" (${paused.id})`) + const text = `paused scheduled job "${paused.name}" (${paused.id})` + record(ctx, 'scheduled_job_paused', paused, text) + recordForMaker(ctx, 'scheduled_job_paused', paused, text) return json({ job: summary(paused, ctx) }) } }, @@ -512,23 +566,24 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ ...common, name: 'schedule_run', description: - 'Start a scheduled job your thread created now, as Run now does (needs a turn a person started: a job cannot start another). It starts within seconds, runs under the limits recorded on the job, and is refused while the job is running, waits in a queue, is paused, or has ended (a person resumes or extends it). The result is in the job\'s run history: read it with schedule_list.', + 'Start any scheduled job of the profile now, as Run now does; a paused job is resumed first. It starts within seconds, runs under the limits recorded on the job, and is refused while the job is running or waits in a queue, or once it has ended (only a person extends it). The result is in the job\'s run history: read it with schedule_list.', + botDescription: 'Start a scheduled job you made now, as Run now does; a paused one is resumed first. It is refused while the job is running or waits in a queue, or once it has ended.', inputSchema: { type: 'object', properties: { jobId: { type: 'string' } }, required: ['jobId'] }, class: 'mutation', handler: (args, ctx) => { - const job = findVisible(requiredId(args, 'jobId'), ctx) - if (isWorkflowPrompt(job.prompt)) return { text: 'This job runs a workflow; an agent does not start those.', isError: true } - const refusal = runNowRefusal(job) - if (refusal) return { text: refusal, isError: true } - // Starting a job also resumes it; a person's pause is not undone by an agent's run. - if (!job.enabled || job.state === 'paused') return { text: `Job ${job.name} is paused; only a person resumes it.`, isError: true } + let job = findChangeable(requiredId(args, 'jobId'), ctx) // A finished job (a one-time job that ran, a job that ran out of runs or time) is not brought back. if (job.state === 'completed' || isExpired(job)) return { text: `Job ${job.name} has ended; only a person extends or recreates it.`, isError: true } + if (!job.enabled || job.state === 'paused') job = resume(job) + const refusal = runNowRefusal(job) + if (refusal) return { text: refusal, isError: true } const started = schedules.trigger(job.id) if (!started) throw new Error(`Job ${job.id} no longer exists.`) // Run now starts within seconds: the scheduler ticks now instead of at the next minute. schedules.wake() - record(ctx, 'scheduled_job_run', started, `started scheduled job "${started.name}" (${started.id})`) + const text = `started scheduled job "${started.name}" (${started.id})` + record(ctx, 'scheduled_job_run', started, text) + recordForMaker(ctx, 'scheduled_job_run', started, text) return json({ job: summary(started, ctx), started: true }) } }, @@ -536,7 +591,8 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ ...common, name: 'schedule_delete', description: - 'Remove a scheduled job your thread created, or one your subagents created, for good: it leaves Automations and schedule_list and starts no further runs. A run that already started, or already waits in its thread\'s queue, still runs and finishes in that thread; its result is not recorded on any job. A person\'s job and another thread\'s job are never removed. A subagent removes the jobs it made, as its parent does. Any turn of your thread may remove one, so a job bound to your thread can remove itself when its work is done. The removal is recorded in your thread with the job\'s name. A repeat for a job already removed, or a retry with the same clientRequestId, says it is gone and changes nothing.', + 'Remove any scheduled job of the profile for good, a person\'s too: it leaves Automations and schedule_list and starts no further runs. A run that already started, or already waits in its thread\'s queue, still runs and finishes in that thread; its result is not recorded on any job. A job bound to your thread can remove itself when its work is done. The removal is recorded in your thread with the job\'s name, and in the thread that made it. A repeat for a job already removed, or a retry with the same clientRequestId, says it is gone and changes nothing.', + botDescription: 'Remove a scheduled job you made for good: it starts no further runs. A run that already started still finishes. A retry with the same clientRequestId says it is gone and changes nothing.', inputSchema: { type: 'object', properties: { jobId: { type: 'string' }, clientRequestId: CLIENT_REQUEST_ID_SCHEMA }, required: ['jobId'] }, class: 'mutation', handler: (args, ctx) => { @@ -545,15 +601,13 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ const replay = removal(requestKey) if (replay) return json({ removed: true, alreadyRemoved: true, replayed: true, job: replay.job }) const job = schedules.get(id) - if (!job || !(visible(job, ctx) || madeBySubagent(job, ctx))) { - // A job this thread removed before is gone, not refused; anything else is refused the same way whether it exists or not. + if (!job) { + // A job removed before through these tools is gone, not refused; anything else is refused whether it exists or not. const earlier = removal(`job:${id}`) - if (!job && earlier?.removedBy === ctx.caller.threadId) return json({ removed: true, alreadyRemoved: true, job: earlier.job }) - throw new McpToolError( - 'mousse_scope_denied', - `No scheduled job ${id} that you or your subagents made. A thread removes only the jobs it made and the ones its subagents made; a person's job and another thread's job are not removed by an agent. A job you removed already is gone: schedule_list shows the ones you can remove.` - ) + if (earlier) return json({ removed: true, alreadyRemoved: true, job: earlier.job }) } + if (!job || !visible(job, ctx)) throw new McpToolError('mousse_scope_denied', `No scheduled job ${id}. schedule_list shows the jobs you can remove.`) + findChangeable(id, ctx) const entry = { removedBy: ctx.caller.threadId, job: { id: job.id, name: job.name } } // The deletion Automations' Delete makes. False: someone removed it in between, which is the same outcome. if (!schedules.remove(job.id)) return json({ removed: true, alreadyRemoved: true, job: entry.job }) @@ -562,9 +616,7 @@ export function scheduleTools(host: AppToolHost, engine: RunEngine): MousseTool[ if (job.createdBy?.requestId) remember(`created:${job.createdBy.requestId}`, entry) const summaryText = `removed scheduled job "${job.name}" (${job.id})` record(ctx, 'scheduled_job_deleted', job, summaryText) - // A subagent's job: its own thread shows the removal too, by whom. - const creator = job.createdBy!.threadId - if (creator !== ctx.caller.threadId) record(ctx, 'scheduled_job_deleted', job, `${summaryText}, which this thread made; removed by thread ${ctx.caller.threadId}`, { threadId: creator }) + recordForMaker(ctx, 'scheduled_job_deleted', job, summaryText) const started = job.state === 'running' || job.pendingOccurrence !== undefined return json({ removed: true, diff --git a/src/renderer/components/asks/AskCard.tsx b/src/renderer/components/asks/AskCard.tsx index 559e505a6d..e688ee59bc 100644 --- a/src/renderer/components/asks/AskCard.tsx +++ b/src/renderer/components/asks/AskCard.tsx @@ -5,8 +5,8 @@ import { RowMenu, type RowMenuItem } from '../integrations/RowMenu' /** * The one Needs you ask: something asks for a right, and the person answers Allow or Not now. Every ask renders - * through it: a bot's ask (in its chat and in Needs you), a thread's permission request, a workflow step's approval - * and an agent's first-creation ask. `card` is the ask in a conversation (the line, its note, Not now and Allow); `row` + * through it: a bot's ask (in its chat and in Needs you), a thread's permission request and a workflow step's approval. + * `card` is the ask in a conversation (the line, its note, Not now and Allow); `row` * is its Needs you row (the line, Allow as the one action, Not now in "…"). Once answered it is one line. */ export interface AskCardProps { diff --git a/src/renderer/components/automations/inbox/AutomationsInbox.tsx b/src/renderer/components/automations/inbox/AutomationsInbox.tsx index 8746e902b1..f0e4500914 100644 --- a/src/renderer/components/automations/inbox/AutomationsInbox.tsx +++ b/src/renderer/components/automations/inbox/AutomationsInbox.tsx @@ -7,7 +7,6 @@ import type { AutomationItem } from '../../../../shared/automations' import { useCommand } from '../../../commands/commandRegistry' import { ChevronRight, CircleAlert, LayoutGrid, Loader2, Search, Undo2, X } from '../../../lib/icons' import { useAppStore } from '../../../stores/appStore' -import { answerAttention } from '../../../services/automationsClient' import { createPersonalBotsClient } from '../../../services/personalBotsClient' import { ownedWhenText, viewerTimeZone } from '../automationTime' import { DeleteConfirm } from '../AutomationDialogs' @@ -97,7 +96,6 @@ export function AutomationsInbox({ active }: { active: boolean }) { const automations = useMemo(() => automationsById(index?.items), [index]) const jobs = useMemo(() => (index?.items ?? []).filter((item) => item.kind === 'job' && !item.draft), [index]) const drafts = useMemo(() => (index?.items ?? []).filter((item) => item.kind === 'job' && item.draft), [index]) - const asks = useMemo(() => (index?.items ?? []).filter((item) => item.kind === 'ask' && item.attention?.answer), [index]) const runs = useMemo(() => inbox?.runs ?? [], [inbox]) const groups = useMemo(() => inboxGroups(runs, filter, automations, folds), [runs, filter, automations, folds]) const rows = useMemo(() => groups.flatMap((group) => group.rows), [groups]) @@ -178,7 +176,6 @@ export function AutomationsInbox({ active }: { active: boolean }) { const editItem = editJobId ? jobs.find((item) => item.id === editJobId) ?? drafts.find((item) => item.id === editJobId) : undefined const empty = Boolean(inbox && index) && runs.length === 0 const lastResolved = inbox?.undo - const needsCount = groups.find((group) => group.key === 'needs_you')?.count ?? 0 // The Drafts row shows while there are drafts, or while the person's words to the manager are pending or failed. const requestShows = Boolean(request && !request.draftId && request.status !== 'done') // Writing… only until the draft lands: the manager may still be replying, but the person has what they asked for. @@ -219,16 +216,10 @@ export function AutomationsInbox({ active }: { active: boolean }) { : request?.status === 'failed' ? : null} ) : null} - {asks.length && !filter.automationId ? ( -
- {!needsCount ?
Needs you{asks.length}
: null} - {asks.map((item) => )} -
- ) : null} {groups.map((group) => (
{group.key !== 'live' && group.key !== 'quiet' && ( -
{group.label}{group.count + (group.key === 'needs_you' ? asks.length : 0) > 0 && {group.count + (group.key === 'needs_you' ? asks.length : 0)}}
+
{group.label}{group.count > 0 && {group.count}}
)} {group.rows.map((row) => ( activate(row)} /> @@ -339,27 +330,6 @@ function InboxRow({ row, automation, automations, cursor, open, folds, now, onAc ) } -/** An agent asks to add an automation: Allow makes it, Not now drops the ask (`automations.asks.answer`). */ -function AskRow({ item }: { item: AutomationItem }) { - const [busy, setBusy] = useState(false) - const answer = (allow: boolean) => { - const target = item.attention?.answer - if (!target) return - setBusy(true) - void answerAttention(target, allow, { - transport: window.mousse.platformRequest, - answerQuestions: (requestId, answers, threadId) => window.mousse.orchestrator.answerQuestionsDetailed(requestId, answers, threadId) - }).catch((cause) => useInboxStore.setState({ actionError: cause instanceof Error ? cause.message : String(cause) })).finally(() => { setBusy(false); void refreshInbox() }) - } - return ( -
- {item.attention?.text ?? item.name} - - -
- ) -} - /** The list scoped to one automation (its name and one line: when, next, where) or to one project group. */ function FilterHeader({ filter, automation, now, viewerZone }: { filter: InboxFilter; automation: AutomationItem | undefined; now: Date; viewerZone: string }) { const clear = () => setInboxFilter({ ...(filter.text ? { text: filter.text } : {}) }) diff --git a/src/renderer/components/automations/inbox/inbox.css b/src/renderer/components/automations/inbox/inbox.css index 805042f5db..2f69ddfd86 100644 --- a/src/renderer/components/automations/inbox/inbox.css +++ b/src/renderer/components/automations/inbox/inbox.css @@ -838,15 +838,6 @@ .inbox-drafts-row { width: 100%; margin-bottom: 2px; } -.inbox-ask-row { - display: flex; - align-items: center; - gap: 6px; - padding: 6px 4px 6px 10px; - border-radius: 8px; -} -.inbox-ask-row .inbox-run-icon { color: var(--status-input); } - /* ── The run strip, above the run's thread in the conversation ── */ .inbox-strip-name { max-width: 220px; diff --git a/src/renderer/components/settings/AgentAutomationsSettings.tsx b/src/renderer/components/settings/AgentAutomationsSettings.tsx index 49d21cea55..a702943001 100644 --- a/src/renderer/components/settings/AgentAutomationsSettings.tsx +++ b/src/renderer/components/settings/AgentAutomationsSettings.tsx @@ -5,11 +5,10 @@ import { MoreDetails, SettingsGroup } from './SettingsRow' import { Repeat } from '../../lib/icons' export const AGENT_AUTOMATIONS_HELP = - "The first time an agent adds an automation, you are asked in Automations, Needs you: Allow adds it and lets that thread add more within these limits; Not now drops it. Automations agents add run no wider than that agent and end after the days below unless you Keep them." + "Agents add, change, pause and remove automations within these limits. Automations agents add run no wider than that agent and end after the days below unless you Keep them." /** - * Settings → Agents → Automations: the limits on the automations agents add. Whether an agent may add them at all is asked the - * first time it tries (Allow / Not now in Needs you), so there is no switch. + * Settings → Agents → Automations: the limits on the automations agents add. Agents add them without asking, so there is no switch. */ export function AgentAutomationsSettings() { const [settings, setSettings] = useState(null) @@ -37,7 +36,7 @@ export function AgentAutomationsSettings() { icon={Repeat} anchor="agents-automations" description={<> - Limits on the automations agents add. You are asked the first time one is added. + Limits on the automations agents add. {AGENT_AUTOMATIONS_HELP} } > diff --git a/src/renderer/services/automationsClient.ts b/src/renderer/services/automationsClient.ts index ce4bc1db57..95b5fc01f7 100644 --- a/src/renderer/services/automationsClient.ts +++ b/src/renderer/services/automationsClient.ts @@ -6,8 +6,6 @@ import type { ScheduledJob, QuestionAnswerOutcome } from '../../shared/types' export interface AutomationsClient { /** Every automation of the bound profile in one read-only list (`automations.list`). */ list(): Promise - /** Allow or Not now on an agent's first-creation ask (`automations.asks.answer`). */ - answerAsk(askId: string, answer: 'allow' | 'not_now'): Promise /** Keep: an agent-added automation loses only its end (`automations.keep`). */ keep(jobId: string): Promise /** Resend: runs a request automation again with a delivery's stored payload (`automations.request.resend`). */ @@ -54,7 +52,6 @@ export type AutomationWhoPick = { kind: 'default' } | { kind: 'bot'; botId: stri export function createAutomationsClient(transport: PlatformRequestApi): AutomationsClient { return { list: () => transport.request('automations.list', {}), - answerAsk: async (askId, answer) => { await transport.request('automations.asks.answer', { askId, answer }) }, keep: async (jobId) => (await transport.request<{ job: ScheduledJob }>('automations.keep', { jobId })).job, resend: async (jobId, occurrenceId) => { await transport.request('automations.request.resend', { jobId, occurrenceId }) }, listKeys: async () => (await transport.request<{ keys: Array<{ name: string }> }>('automations.keys.list', {})).keys.map((key) => key.name), @@ -84,7 +81,7 @@ export interface AnswerPorts { /** * Answers an open ask from Needs you with the same daemon method its own surface uses: the thread's permission request, - * the workflow step's approval, the agent's first-creation ask or the bot's ask. Throws what the person should read when + * the workflow step's approval or the bot's ask. Throws what the person should read when * the ask was answered elsewhere first or is gone. */ export async function answerAttention(answer: AttentionAnswer, allow: boolean, ports: AnswerPorts): Promise { @@ -97,9 +94,6 @@ export async function answerAttention(answer: AttentionAnswer, allow: boolean, p case 'workflow_approval': await ports.transport.request('workflowRuns.approve', { runId: answer.runId, approvalId: answer.approvalId, nodeId: answer.nodeId, instanceKey: answer.instanceKey, attempt: answer.attempt, approved: allow }) return - case 'agent_ask': - await ports.transport.request('automations.asks.answer', { askId: answer.askId, answer: allow ? 'allow' : 'not_now' }) - return case 'bot_ask': await ports.transport.request('bots.asks.answer', { botId: answer.botId, askId: answer.askId, answer: allow ? 'allow' : 'not_now' }) } diff --git a/src/shared/automations.ts b/src/shared/automations.ts index 26d6c44880..560daaec8c 100644 --- a/src/shared/automations.ts +++ b/src/shared/automations.ts @@ -10,7 +10,7 @@ import type { JobSchedule, ScheduledEventLogEntry, ScheduledJob, ScheduledJobRun */ export const AUTOMATIONS_METHODS = [ - 'automations.list', 'automations.asks.answer', 'automations.keep', 'automations.request.resend', 'automations.keys.list', 'automations.keys.set', + 'automations.list', 'automations.keep', 'automations.request.resend', 'automations.keys.list', 'automations.keys.set', 'automations.drafts.turnOn', 'automations.drafts.discard', 'automations.drafts.create', 'automations.drafts.answered', 'automations.drafts.setWho', 'automations.drafts.nextWho', 'automations.manager.thread', 'automations.manager.turn', 'automations.inbox.list', 'automations.inbox.counts', 'automations.inbox.resolve', 'automations.inbox.undo', 'automations.inbox.calibrate', 'automations.tuning.remove' @@ -31,7 +31,7 @@ export interface ManagerTurn { * What an automation is, underneath: where its record lives and what opens it. A bot's schedule is a job whose Who is * the bot. */ -export type AutomationKind = 'job' | 'watch' | 'ask' +export type AutomationKind = 'job' | 'watch' /** What starts it: a time, a signed request (webhook), something on its thread (a pull request), or a person. */ export type AutomationTrigger = 'time' | 'request' | 'thread_event' | 'on_demand' @@ -198,22 +198,19 @@ export type AutomationWho = | { kind: 'workflow'; name: string } | { kind: 'none'; name: string } -/** What opens it: the job's detail (a bot's schedule names its bot too), an agent's ask, or the thread that watches. */ +/** What opens it: the job's detail (a bot's schedule names its bot too), or the thread that watches. */ export type AutomationLink = | { kind: 'job'; jobId: string; botId?: string } - /** An agent's first-creation ask: Allow makes the automation (`automations.asks.answer`). */ - | { kind: 'ask'; askId: string; threadId: string } | { kind: 'thread'; threadId: string } /** * How Needs you answers an open ask in place, with the same daemon method its own surface uses: a thread's permission - * request (`orchestrator.answerQuestions`), a workflow step's approval (`workflowRuns.approve`), an agent's - * first-creation ask (`automations.asks.answer`) or a bot's ask (`bots.asks.answer`). + * request (`orchestrator.answerQuestions`), a workflow step's approval (`workflowRuns.approve`) or a bot's ask + * (`bots.asks.answer`). */ export type AttentionAnswer = | { kind: 'thread_approval'; threadId: string; requestId: string; questionId: string; allow: string; deny: string } | { kind: 'workflow_approval'; runId: string; approvalId: string; nodeId: string; instanceKey: string; attempt: number } - | { kind: 'agent_ask'; askId: string } | { kind: 'bot_ask'; botId: string; askId: string } /** Why it needs the person: an open ask (answered where it was asked), or a run that ended Failed or Incomplete. */ @@ -228,7 +225,7 @@ export interface AutomationAttention { } export interface AutomationItem { - /** Unique in the list: `job:`, `ask:`, `watch:`. */ + /** Unique in the list: `job:`, `watch:`. */ key: string kind: AutomationKind id: string diff --git a/src/shared/bridge/routed.ts b/src/shared/bridge/routed.ts index 1d6494097f..fef11df674 100644 --- a/src/shared/bridge/routed.ts +++ b/src/shared/bridge/routed.ts @@ -1295,8 +1295,8 @@ export const ROUTED_LOCAL_METHODS: readonly RoutedLocalRule[] = [ reason: 'Cua Driver is found and installed on the computer itself; only a person at a window of that computer installs software.' }, { - methods: ['automations.asks.answer', 'automations.keep'], - reason: 'An agent’s ask and Keep are answered on the computer that holds them.' + methods: ['automations.keep'], + reason: 'Keep is answered on the computer that holds the automation.' }, { methods: ['secrets.requests.list', 'secrets.requests.answer', 'secrets.requests.useSaved', 'secrets.requests.decline', 'secrets.list', 'secrets.delete', 'secrets.keepPasted'], diff --git a/src/shared/types.ts b/src/shared/types.ts index 36e5073b38..ebea1fd45c 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -403,8 +403,6 @@ export interface AutomationDraftState { /** Profile settings of the scheduler that people choose on the Scheduled page. */ export interface ScheduledSettings { - /** Agents may list, create, change, pause and run jobs through the Mousse tools. Off by default. */ - agentJobs: boolean /** Active jobs agents may have in the profile at once (1 to 100; 10 unless a person changes it). */ agentJobMaxActive: number /** The fewest minutes between runs of a job an agent creates or changes (1 to 1440; 15 unless changed). */ diff --git a/tests/automations.test.ts b/tests/automations.test.ts index e03e88f18b..b983f8007f 100644 --- a/tests/automations.test.ts +++ b/tests/automations.test.ts @@ -5,8 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { MousseConfigStore } from '../src/mms/config/MousseConfigStore' import { missedWhileOffline, recordTickerHeartbeat, ScheduledJobStore } from '../src/mms/scheduled/ScheduledJobStore' import { ScheduledJobService } from '../src/mms/scheduled/ScheduledJobService' -import { askText, botRun, buildAutomationIndex, jobEffectiveMay, type AutomationIndexSources } from '../src/mms/automations/AutomationIndex' -import { AgentJobAskStore } from '../src/mms/automations/AgentJobAsks' +import { botRun, buildAutomationIndex, jobEffectiveMay, type AutomationIndexSources } from '../src/mms/automations/AutomationIndex' import type { BotAutomationFacts } from '../src/mms/bots/chat/BotChatService' import { asCreateScheduledJobInput, asScheduledJobPatch } from '../src/mms/protocol/validators' import { @@ -406,50 +405,6 @@ describe('the scheduler', () => { }) }) -describe('the first-creation ask', () => { - let home: string - beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'mousse-agent-asks-')) }) - afterEach(() => { rmSync(home, { recursive: true, force: true }) }) - const job = { name: 'Check PR #42', prompt: 'Check PR #42 for new review comments', schedule: { kind: 'interval' as const, minutes: 30 }, createdBy: { threadId: 't1', requestId: 'k1' } } - - it('is durable, asked once per call, and Allow makes the automation and lets the thread add more', () => { - const store = new AgentJobAskStore(home) - const ask = store.ask({ threadId: 't1', requestKey: 'k1', job }) - expect(store.ask({ threadId: 't1', requestKey: 'k1', job }).id).toBe(ask.id) - // Another store over the same folder (a daemon restart) still has it. - const again = new AgentJobAskStore(home) - expect(again.open().map((entry) => entry.id)).toEqual([ask.id]) - expect(again.threadAllowed('t1')).toBe(false) - const created: string[] = [] - const answered = again.answer(ask.id, 'allow', (entry) => { created.push(entry.input.name); return { id: 'job-1' } }) - expect(answered).toMatchObject({ state: 'allowed', jobId: 'job-1' }) - expect(created).toEqual(['Check PR #42']) - expect(again.threadAllowed('t1')).toBe(true) - expect(again.open()).toEqual([]) - expect(() => again.answer(ask.id, 'allow', () => ({ id: 'x' }))).toThrow(/already answered/) - }) - - it('Not now closes it and allows nothing; a refused Allow (a limit) leaves it open', () => { - const store = new AgentJobAskStore(home) - const ask = store.ask({ threadId: 't1', requestKey: 'k1', job }) - expect(() => store.answer(ask.id, 'allow', () => { throw new Error('Agents already have 10 active automations') })).toThrow(/10 active/) - expect(store.open()).toHaveLength(1) - expect(store.answer(ask.id, 'not_now', () => { throw new Error('not called') })).toMatchObject({ state: 'declined' }) - expect(store.threadAllowed('t1')).toBe(false) - }) - - it('is one Needs you item that says who wants what, and when', () => { - const store = new AgentJobAskStore(home) - store.ask({ threadId: 't1', requestKey: 'k1', job }) - const reviewer = { id: 't1', name: 'Reviewer' } as unknown as Thread - const index = buildAutomationIndex({ ...sources({ threads: [reviewer] }), asks: () => store.open() }) - expect(index.items).toHaveLength(1) - expect(index.items[0]).toMatchObject({ kind: 'ask', name: 'Check PR #42', attention: { kind: 'ask', threadId: 't1' }, link: { kind: 'ask', threadId: 't1' } }) - expect(index.items[0]!.attention!.text).toBe(askText(store.open()[0]!, 'Reviewer', new Date('2026-11-08T10:00:00.000Z'))) - expect(index.items[0]!.attention!.text).toMatch(/^Reviewer wants to check PR #42 for new review comments every 30 min$/i) - }) -}) - it('C11 a held schedule stays live and shows why later occurrences are skipped', () => { const pip: BotAutomationFacts = { botName: 'Pip', look: { colour: 'cream', accessory: 'none' }, paused: false, runs: [{ id: 'held', status: 'blocked', endReason: 'approval', at: PAST }] } const scheduled = job({ id: 'b--s', bot: { botId: 'b', scheduleId: 's', createdBy: 'owner' }, botSkip: { at: PAST, reason: 'bot_waiting_for_owner' } }) diff --git a/tests/renderer/automationsPage.test.ts b/tests/renderer/automationsPage.test.ts index 7d1fcbbac1..f3b5bfbc23 100644 --- a/tests/renderer/automationsPage.test.ts +++ b/tests/renderer/automationsPage.test.ts @@ -170,7 +170,6 @@ const LIBRARY: Record = { }, 'bots.personal.list': { bots: [{ id: 'bot_1', name: 'Pip', look: { colour: 'teal', accessory: 'headphones' } }] }, 'bots.schedules.add': { runs: [] }, - 'automations.asks.answer': { ask: {} }, 'automations.keep': { job: {} }, 'bots.asks.answer': { message: {} }, 'automations.manager.thread': { threadId: 'mgr' }, @@ -202,7 +201,7 @@ function api(index: AutomationIndex, jobs: ScheduledJob[]) { resume: vi.fn(async () => null), run: vi.fn(async () => null), extend: vi.fn(async () => null), - settings: { get: vi.fn(async () => ({ agentJobs: false, agentJobMaxActive: 10, agentJobMinIntervalMinutes: 15, agentJobLifetimeDays: 7 })) }, + settings: { get: vi.fn(async () => ({ agentJobMaxActive: 10, agentJobMinIntervalMinutes: 15, agentJobLifetimeDays: 7 })) }, webhook: { enable: vi.fn(), rotate: vi.fn(), disable: vi.fn(), deliveries: vi.fn(async () => ({ deliveries: [], url: '' })) } }, personalBots: { onChanged: vi.fn(() => () => undefined) }, diff --git a/tests/run/botThreadParity.test.ts b/tests/run/botThreadParity.test.ts index b88fb605c3..660b261639 100644 --- a/tests/run/botThreadParity.test.ts +++ b/tests/run/botThreadParity.test.ts @@ -285,8 +285,6 @@ describe('a bot uses what a thread\'s agent can', () => { const scheduleHost = () => { const jobs: ScheduledJob[] = [] const schedules = { - threadAllowed: vi.fn(() => false), - askFirst: vi.fn(() => ({ id: 'ask-1' })), jobLimits: () => ({ maxActive: 10, minIntervalMinutes: 15, lifetimeDays: 7 }), list: () => jobs, get: (id: string) => jobs.find((job) => job.id === id), @@ -305,13 +303,12 @@ describe('a bot uses what a thread\'s agent can', () => { return { schedules, jobs } } - it('makes a job in a project for its owner without the thread\'s first ask, filed as the bot\'s', async () => { + it('makes a job in a project for its owner at once, filed as the bot\'s', async () => { const { schedules, jobs } = scheduleHost() const { call } = await world({ host: { schedules } }) const job = { name: 'Nightly tests', prompt: 'Run the test suite and report failures.', schedule: { kind: 'cron', expr: '0 2 * * *' } } expect(await call('schedule_create', job)).toMatchObject({ error: true, text: expect.stringMatching(/threadId .* or projectId/) }) expect(await call('schedule_create', { ...job, projectId: 'p1' })).toMatchObject({ error: false }) - expect(schedules.askFirst).not.toHaveBeenCalled() // Its jobs are the bot's, whichever turn made them: its chat's thread. expect(jobs[0]).toMatchObject({ projectId: 'p1', createdBy: { threadId: 'home' } }) expect(JSON.parse((await call('schedule_list')).text).jobs.map((entry: { id: string }) => entry.id)).toEqual(['job-1']) @@ -319,7 +316,7 @@ describe('a bot uses what a thread\'s agent can', () => { expect(await call('schedule_create', { ...job, threadId: 'private' })).toMatchObject({ error: true, text: expect.stringMatching(/not available to you/) }) }) - it('a turn that may only read is told why, and nothing is asked or made', async () => { + it('a turn that may only read is told why, and nothing is made', async () => { const { schedules } = scheduleHost() const { call } = await world({ host: { schedules }, botTools: { escalate: true, consult: false, threads: 'read', owner: true } }) expect(await call('schedule_create', { name: 'x', prompt: 'y', schedule: { kind: 'cron', expr: '0 2 * * *' }, projectId: 'p1' })).toEqual({ error: true, text: BOT_SCHEDULES_NOT_OWNER_TEXT }) diff --git a/tests/run/scheduleTools.test.ts b/tests/run/scheduleTools.test.ts index 8300548daf..a74c1341a4 100644 --- a/tests/run/scheduleTools.test.ts +++ b/tests/run/scheduleTools.test.ts @@ -1,8 +1,9 @@ /** * `schedule_list`, `schedule_create`, `schedule_update`, `schedule_pause`, `schedule_run` and `schedule_delete` through the registry's - * central check (docs/run-engine/SPEC.md §15.1), over a real scheduled-job store: the `scheduled.agentJobs` setting, that only a turn a person started may create or start jobs, that an agent sees and - * changes only the jobs its own thread made, what a job records of its creator, that an agent can never raise a job's - * limits, the total cap, the lifetime and the cadence floor, Run now's refusals, and that every change is recorded. + * central check (docs/run-engine/SPEC.md §15.1), over a real scheduled-job store: that an agent sees and changes every job of + * the profile across the private line only as other thread tools do, what a job records of its creator, that an agent can + * never raise a job's ceiling above its own mode or push its end past the lifetime, the total cap, the lifetime and the + * cadence floor, Run now's refusals, and that every change is recorded. */ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -39,8 +40,8 @@ describe('the schedule tools (SPEC §15.1)', () => { }) /** - * `caller` holds a live run in project p1. `state` is what the profile says now (limits, whether a person - * started the run): read at every call. The jobs live in a real store, so what a call changes is what a reload would find. + * `caller` holds a live run in project p1. `state` is what the profile says now (limits): read at every call. The jobs + * live in a real store, so what a call changes is what a reload would find. */ const world = async () => { fx = delegationFixture() @@ -50,10 +51,6 @@ describe('the schedule tools (SPEC §15.1)', () => { const callerRun = await fx.runningRun('caller') const jobs = new ScheduledJobStore(MousseConfigStore.load(home)) const state = { - /** Whether the person allowed the caller's thread (Allow on its first ask); read at every call. */ - allowed: true, - /** Whether the calling run holds `person` (`personHeld`); the real rule is tested against a daemon. */ - person: true, limits: { permissionCeiling: 'full' as PermissionMode }, /** The limits on agent jobs a person set (`scheduled.agentJob*`): read at every call. */ jobLimits: { ...AGENT_JOB_LIMIT_DEFAULTS } @@ -67,8 +64,6 @@ describe('the schedule tools (SPEC §15.1)', () => { const readOnly = new Set() const woke = vi.fn() const schedules = { - threadAllowed: vi.fn(() => state.allowed), - askFirst: vi.fn((input: { threadId: string; requestKey: string }) => ({ id: `ask-${input.requestKey}` })), jobLimits: vi.fn(() => ({ ...state.jobLimits })), list: vi.fn(() => jobs.listJobs()), get: vi.fn((id: string) => jobs.getJob(id)), @@ -77,16 +72,17 @@ describe('the schedule tools (SPEC §15.1)', () => { create: vi.fn((input: Parameters[0]) => jobs.createJob(input)), update: vi.fn((id: string, patch: Partial) => jobs.updateJob(id, patch)), pause: vi.fn((id: string, reason?: string) => jobs.pauseJob(id, reason)), + resume: vi.fn((id: string) => jobs.resumeJob(id)), remove: vi.fn((id: string) => jobs.deleteJob(id)), trigger: vi.fn((id: string) => jobs.triggerJob(id)), wake: woke } satisfies AgentScheduleHost const recordAgentAction = vi.fn() - const personHeld = vi.fn((_caller: { threadId: string; runId: string }) => state.person) const fake = fakeAppToolHost({ - personHeld, subagentThread: (id) => fx!.engine.delegations.getLineage(id)?.relationship === 'subagent', threadMeta: (id) => threads.get(id), + listThreads: () => [...threads.values()], + listProjects: () => [{ id: 'p1', name: 'One' }, { id: 'p2', name: 'Two' }] as never, botRole: (id) => (botThreads.has(id) ? 'activation' : undefined), readOnlyThread: (id) => readOnly.has(id), recordAgentAction, @@ -107,29 +103,26 @@ describe('the schedule tools (SPEC §15.1)', () => { const personJob = (extra: Partial[0]> = {}) => jobs.createJob({ name: 'By a person', prompt: 'Do it', schedule: { kind: 'manual' }, ...extra }) /** A job another thread's agent made. */ const otherJob = (extra: Partial[0]> = {}) => - jobs.createJob({ name: 'By another agent', prompt: 'Do it', schedule: { kind: 'manual' }, createdBy: { threadId: 'someone-else', runId: 'r' }, ...extra }) - return { fx, jobs, state, threads, botThreads, readOnly, schedules, personHeld, woke, recordAgentAction, registry, request, turns, callerRun, call, as, denied, result, create, stored, personJob, otherJob, ...fake } + jobs.createJob({ name: 'By another agent', prompt: 'Do it', schedule: { kind: 'manual' }, createdBy: { threadId: 'second', runId: 'r' }, ...extra }) + /** A live run of `threadId` whose calls go through the registry. */ + const liveCaller = async (threadId: string, runId?: string) => { + if (runId) { + fx!.engine.markStarting(runId) + fx!.engine.markRunning(runId) + } else runId = (await fx!.runningRun(threadId)).runId + turns.register(appTurn({ threadId, runId })) + return (name: string, args: Record = {}) => registry.call(name, args, request({ threadId, runId: runId! })) + } + return { fx, jobs, state, threads, botThreads, readOnly, schedules, woke, recordAgentAction, registry, request, turns, callerRun, call, as, denied, result, create, stored, personJob, otherJob, liveCaller, ...fake } } - describe('the first ask and the listing', () => { - it('the first job a thread asks for is an ask the person answers: nothing is made, and the agent is told it waits', async () => { - const { call, state, jobs, schedules } = await world() - state.allowed = false - const outcome = await call('schedule_create', { ...CREATE, clientRequestId: 'first' }) - expect(outcome.isError).toBeFalsy() - const answer = JSON.parse(outcome.text) - expect(answer).toMatchObject({ waiting: true, askId: expect.any(String), message: expect.stringContaining('do not ask again') }) - expect(schedules.askFirst).toHaveBeenCalledWith(expect.objectContaining({ threadId: 'caller', job: expect.objectContaining({ name: CREATE.name, createdBy: expect.objectContaining({ threadId: 'caller' }) }) })) - expect(schedules.create).not.toHaveBeenCalled() - expect(jobs.listJobs()).toEqual([]) - // Once the person allowed the thread, it adds more at once, within the limits. - state.allowed = true - expect(JSON.parse((await call('schedule_create', { ...CREATE, clientRequestId: 'second' })).text).job).toMatchObject({ name: CREATE.name }) - }) - - it('lists the six tools for a host that has scheduled jobs', async () => { - const { registry } = await world() + describe('the listing', () => { + it('lists the six tools for a host that has scheduled jobs, to a subagent too', async () => { + const { registry, fx: f, callerRun, threads } = await world() expect(registry.listForThread('caller').map((tool) => tool.name).filter((name) => name.startsWith('schedule_')).sort()).toEqual(TOOLS) + const child = await f.delegate(callerRun.runId, 'call-a') + threads.set(child.childThreadId, thread(child.childThreadId)) + expect(registry.listForThread(child.childThreadId).map((tool) => tool.name).filter((name) => name.startsWith('schedule_')).sort()).toEqual(TOOLS) }) it('the tools are only for a host that has scheduled jobs', async () => { @@ -140,84 +133,8 @@ describe('the schedule tools (SPEC §15.1)', () => { }) }) - describe('only a turn a person started may create or start jobs', () => { - it.each([ - ['schedule_create', () => ({ ...CREATE })], - ['schedule_run', (id: string) => ({ jobId: id })], - ['schedule_update of the prompt', (id: string) => ({ jobId: id, prompt: 'Something else' })], - ['schedule_update of the schedule', (id: string) => ({ jobId: id, schedule: { kind: 'interval', minutes: 60 } })], - ['schedule_update of the workspace', (id: string) => ({ jobId: id, workspace: { kind: 'newWorktree' } })], - ['schedule_update of the thread', (id: string) => ({ jobId: id, threadId: 'caller' })], - ['schedule_update of the model', (id: string) => ({ jobId: id, selection: { instanceId: 'claude', model: 'sonnet' } })] - ])('%s is refused for any other run, and changes nothing', async (label, args) => { - const { call, denied, create, state, stored, schedules, jobs, woke } = await world() - const job = await create({ schedule: { kind: 'manual' } }) - const before = stored(job.id) - const writes = jobs.listJobs().length - state.person = false - const name = label.split(' ')[0] - const error = await denied(call(name, args(job.id))) - expect(error?.refused, label).toMatchObject({ code: 'lacks_capability', lacks: 'person' }) - expect(error!.code).toBe('mousse_scope_denied') - expect(error!.message).toMatch(/only for a turn a person started/) - expect(stored(job.id)).toEqual(before) - expect(jobs.listJobs()).toHaveLength(writes) - expect(schedules.update).not.toHaveBeenCalled() - expect(schedules.trigger).not.toHaveBeenCalled() - expect(woke).not.toHaveBeenCalled() - }) - - it('asks the owner who started the run, with the caller as it is', async () => { - const { create, personHeld, callerRun } = await world() - await create() - expect(personHeld).toHaveBeenCalledWith(expect.objectContaining({ threadId: 'caller', runId: callerRun.runId })) - }) - - it('refuses when the owner cannot say, and when it throws', async () => { - const { call, denied, personHeld, jobs } = await world() - personHeld.mockImplementation(() => { throw new Error('the run engine is closed') }) - expect((await denied(call('schedule_create', CREATE)))!.code).toBe('mousse_scope_denied') - expect(jobs.listJobs()).toEqual([]) - }) - - it('a run that is not a person\'s may still list, rename and pause its own thread\'s jobs, and nothing else', async () => { - const { call, create, result, state, stored } = await world() - const job = await create() - state.person = false - expect((await result(call('schedule_list'))).jobs.map((entry: { id: string }) => entry.id)).toEqual([job.id]) - expect((await call('schedule_update', { jobId: job.id, name: 'Renamed' })).isError).toBeUndefined() - expect((await call('schedule_pause', { jobId: job.id })).isError).toBeUndefined() - expect(stored(job.id)).toMatchObject({ name: 'Renamed', state: 'paused' }) - }) - - it('two manual jobs cannot start each other: a run that a job made starts nothing', async () => { - const { call, create, state, jobs, woke, result } = await world() - // A person's turn makes A and B, each told to start the other when it is done. - const a = await create({ name: 'A', prompt: 'work, then run B', schedule: { kind: 'manual' } }) - const b = await create({ name: 'B', prompt: 'work, then run A', schedule: { kind: 'manual' } }) - expect((await call('schedule_run', { jobId: a.id })).isError).toBeUndefined() - expect(woke).toHaveBeenCalledTimes(1) - // A's run (source schedule: not a person's) tries to start B, and B's run would try A. - state.person = false - for (const target of [b.id, a.id]) { - expect(await refusalIn(call('schedule_run', { jobId: target }))).toMatchObject({ code: 'mousse_scope_denied' }) - } - expect(woke).toHaveBeenCalledTimes(1) - expect(jobs.getJob(b.id)?.nextRunAt).toBeNull() - expect((await result(call('schedule_list'))).jobs).toHaveLength(2) - }) - - it('a job\'s run cannot create jobs, so nothing grows from one', async () => { - const { call, state, jobs, create } = await world() - await create({ schedule: { kind: 'manual' } }) - state.person = false - for (let attempt = 0; attempt < 3; attempt += 1) expect(await refusalIn(call('schedule_create', { ...CREATE, name: `Child ${attempt}` }))).toMatchObject({ code: 'mousse_scope_denied' }) - expect(jobs.listJobs()).toHaveLength(1) - }) - }) - describe('schedule_create', () => { - it('makes a job in the caller\'s project and records who made it, labelled as an agent\'s', async () => { + it('makes a job at once in the caller\'s project and records who made it, labelled as an agent\'s', async () => { const { call, result, schedules, stored, callerRun } = await world() const { job } = await result(call('schedule_create', CREATE, { toolCallId: 'mcp:c1' })) expect(job).toMatchObject({ name: 'Nightly report', prompt: 'Write the nightly report', schedule: { kind: 'interval', minutes: 30 }, projectId: 'p1', threadId: null, createdByAgent: true, createdByYou: true }) @@ -229,6 +146,15 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(schedules.validate).toHaveBeenCalledWith(expect.objectContaining({ projectId: 'p1' })) }) + it('a subagent makes one at once too', async () => { + const w = await world() + const child = await w.fx.delegate(w.callerRun.runId, 'call-a') + w.threads.set(child.childThreadId, thread(child.childThreadId)) + const asChild = await w.liveCaller(child.childThreadId, child.childRunId) + const made = JSON.parse((await asChild('schedule_create', CREATE)).text).job + expect(w.stored(made.id).createdBy).toMatchObject({ threadId: child.childThreadId }) + }) + it('records the caller\'s limits on the job, asking the owner who is calling', async () => { const { call, result, schedules, stored, state, callerRun } = await world() state.limits = { permissionCeiling: 'accept_edits' } @@ -238,6 +164,16 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(job).toMatchObject({ permissionCeiling: 'accept_edits' }) }) + it('takes a permission mode up to the caller\'s own, and refuses a wider one', async () => { + const { call, result, stored, state, jobs } = await world() + state.limits = { permissionCeiling: 'accept_edits' } + const { job } = await result(call('schedule_create', { ...CREATE, permissionMode: 'ask' })) + expect(stored(job.id)).toMatchObject({ permissionMode: 'ask', permissionCeiling: 'accept_edits' }) + const wider = await call('schedule_create', { ...CREATE, name: 'Wider', permissionMode: 'full' }) + expect(wider).toMatchObject({ isError: true, text: expect.stringContaining('wider than') }) + expect(jobs.listJobs()).toHaveLength(1) + }) + it('a bot\'s turn held to another device saves that device on the job, and a reload keeps it', async () => { const { call, result, stored, state } = await world() const heldTo = { botId: 'b1', node: 'n_phone', limit: 'accept_edits' as PermissionMode } @@ -255,16 +191,26 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(stored(job.id).createdBy?.requestId).toMatch(/^schedule_create:caller:/) }) + it('takes another project, a new thread per run, a saved agent, a workflow prompt and an existing worktree', async () => { + const { create, stored, schedules } = await world() + expect(stored((await create({ projectId: 'p2' })).id)).toMatchObject({ projectId: 'p2' }) + expect(stored((await create({ threadId: 'second', createThread: true })).id)).toMatchObject({ threadId: 'second', createThread: true }) + expect(stored((await create({ agent: { definitionId: 'agent-1' } })).id).agent).toEqual({ definitionId: 'agent-1' }) + expect(stored((await create({ prompt: '/deploy production' })).id).prompt).toBe('/deploy production') + // An existing worktree names the thread that owns it: the job runs there. + schedules.validate.mockImplementation(() => ({ threadId: 'second' })) + expect(stored((await create({ workspace: { kind: 'worktree', path: '/work/wt' } })).id)).toMatchObject({ threadId: 'second', workspace: { kind: 'worktree', path: '/work/wt' } }) + }) + it.each([ ['a webhook trigger', { trigger: { webhook: {} } }, /webhook/], ['a webhook field', { webhook: true }, /webhook/], + ['a pull request trigger', { threadEvent: { events: ['merged'] } }, /pull request/], + ['saved keys', { keys: ['GITHUB_TOKEN'] }, /keys/], ['an access cap', { accessCap: 'manage' }, /access/], - ['a permission ceiling', { permissionCeiling: 'full' }, /permission mode/], - ['a permission mode', { permissionMode: 'full' }, /permission mode/], + ['a permission ceiling', { permissionCeiling: 'full' }, /set by Mousse/], ['a creator', { createdBy: { threadId: 'someone-else' } }, /createdBy/], - ['an end', { expiresAt: '2099-01-01T00:00:00.000Z' }, /ends is set by Mousse|When a job ends/], - ['another project', { projectId: 'p2' }, /project/], - ['createThread', { createThread: true }, /createThread/] + ['a project that does not exist', { projectId: 'p9' }, /no project p9/] ])('refuses %s, and makes nothing', async (_name, extra, message) => { const { call, jobs, schedules } = await world() const outcome = await call('schedule_create', { ...CREATE, ...extra }) @@ -281,8 +227,6 @@ describe('the schedule tools (SPEC §15.1)', () => { }) it.each([ - ['a prompt that starts with a slash', { prompt: '/workflow run ship' }, /workflows/], - ['a prompt that starts with a slash after whitespace', { prompt: ' \n /workflow run ship' }, /workflows/], ['an interval of one minute', { schedule: { kind: 'interval', minutes: 1 } }, new RegExp(`less than ${MIN_INTERVAL} minutes`)], ['an interval of fourteen minutes', { schedule: { kind: 'interval', minutes: 14 } }, new RegExp(`less than ${MIN_INTERVAL} minutes`)], ['every minute in cron', { schedule: { kind: 'cron', expr: '* * * * *' } }, /fixed list of minutes/], @@ -291,8 +235,7 @@ describe('the schedule tools (SPEC §15.1)', () => { ['cron minutes closer than the floor', { schedule: { kind: 'cron', expr: '0,10 * * * *' } }, new RegExp(`at least ${MIN_INTERVAL} apart`)], ['cron minutes that wrap closer than the floor', { schedule: { kind: 'cron', expr: '5,55 * * * *' } }, new RegExp(`at least ${MIN_INTERVAL} apart`)], ['a cron minute past 59', { schedule: { kind: 'cron', expr: '75 * * * *' } }, /cron field is invalid/], - ['a cron expression with six fields', { schedule: { kind: 'cron', expr: '0 0 9 * * *' } }, /five fields/], - ['an existing worktree', { workspace: { kind: 'worktree', path: '/work/wt' } }, /existing worktree/] + ['a cron expression with six fields', { schedule: { kind: 'cron', expr: '0 0 9 * * *' } }, /five fields/] ])('refuses %s', async (_name, extra, message) => { const { call, jobs } = await world() const outcome = await call('schedule_create', { ...CREATE, ...extra }) @@ -312,28 +255,20 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(jobs.listJobs()).toHaveLength(1) }) - it('binds a job to the caller\'s own thread or to one of its lineage, and to no other', async () => { - const { call, result, callerRun, fx: f, threads, denied, stored } = await world() - const child = await f.delegate(callerRun.runId, 'call-a') - threads.set(child.childThreadId, thread(child.childThreadId, { projectId: 'p1' })) - const own = (await result(call('schedule_create', { ...CREATE, threadId: 'caller' }))).job - expect(stored(own.id)).toMatchObject({ threadId: 'caller', projectId: 'p1' }) - const below = (await result(call('schedule_create', { ...CREATE, threadId: child.childThreadId }))).job - expect(stored(below.id)).toMatchObject({ threadId: child.childThreadId }) - expect((await denied(call('schedule_create', { ...CREATE, threadId: 'elsewhere' })))!.code).toBe('mousse_scope_denied') - }) - - it('refuses an archived thread, a bot\'s thread and one that does not exist, though they are in its lineage', async () => { - const { call, denied, jobs, fx: f, callerRun, threads, botThreads } = await world() - const archived = await f.delegate(callerRun.runId, 'call-a') - const bot = await f.delegate(callerRun.runId, 'call-b') - const missing = await f.delegate(callerRun.runId, 'call-c') - threads.set(archived.childThreadId, thread(archived.childThreadId, { archivedAt: NOW })) - threads.set(bot.childThreadId, thread(bot.childThreadId)) - botThreads.add(bot.childThreadId) - expect(await call('schedule_create', { ...CREATE, threadId: archived.childThreadId })).toMatchObject({ isError: true, text: expect.stringContaining('archived') }) - expect((await denied(call('schedule_create', { ...CREATE, threadId: bot.childThreadId })))!.message).toMatch(/belongs to a bot/) - expect(await call('schedule_create', { ...CREATE, threadId: missing.childThreadId })).toMatchObject({ isError: true, text: expect.stringContaining('was not found') }) + it('binds a job to any thread of the profile, and takes that thread\'s project', async () => { + const { create, stored } = await world() + expect(stored((await create({ threadId: 'caller' })).id)).toMatchObject({ threadId: 'caller', projectId: 'p1' }) + expect(stored((await create({ threadId: 'elsewhere' })).id)).toMatchObject({ threadId: 'elsewhere', projectId: 'p2' }) + }) + + it('refuses an archived thread, a bot\'s thread and one that does not exist', async () => { + const { call, denied, jobs, threads, botThreads } = await world() + threads.set('archived', thread('archived', { archivedAt: NOW })) + threads.set('bot', thread('bot')) + botThreads.add('bot') + expect(await call('schedule_create', { ...CREATE, threadId: 'archived' })).toMatchObject({ isError: true, text: expect.stringContaining('archived') }) + expect((await denied(call('schedule_create', { ...CREATE, threadId: 'bot' })))!.message).toMatch(/belongs to a bot/) + expect(await call('schedule_create', { ...CREATE, threadId: 'missing' })).toMatchObject({ isError: true, text: expect.stringContaining('was not found') }) expect(jobs.listJobs()).toEqual([]) }) @@ -362,6 +297,23 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(ends).toBeLessThanOrEqual(Date.now() + LIFETIME_DAYS * DAY) }) + it('an agent may give a job an earlier end, never one past the lifetime, and never removes it', async () => { + const { call, create, stored, jobs } = await world() + const soon = new Date(Date.now() + DAY).toISOString() + const job = await create({ expiresAt: soon }) + expect(stored(job.id).expiresAt).toBe(soon) + expect(await call('schedule_create', { ...CREATE, name: 'Too long', expiresAt: new Date(Date.now() + (LIFETIME_DAYS + 1) * DAY).toISOString() })).toMatchObject({ isError: true, text: expect.stringContaining('only a person extends') }) + expect(jobs.listJobs()).toHaveLength(1) + // A change may bring it forward, never push it back past the end it has, or remove it. + const sooner = new Date(Date.now() + DAY / 2).toISOString() + expect((await call('schedule_update', { jobId: job.id, expiresAt: sooner })).isError).toBeUndefined() + expect(stored(job.id).expiresAt).toBe(sooner) + expect(await call('schedule_update', { jobId: job.id, expiresAt: soon })).toMatchObject({ isError: true, text: expect.stringContaining('only a person extends') }) + expect(await call('schedule_update', { jobId: job.id, expiresAt: null })).toMatchObject({ isError: true }) + expect(await call('schedule_update', { jobId: job.id, expiresAt: new Date(Date.now() - DAY).toISOString() })).toMatchObject({ isError: true, text: expect.stringContaining('future') }) + expect(stored(job.id).expiresAt).toBe(sooner) + }) + it('refuses the eleventh active job of the profile, however many runs, threads and restarts made them', async () => { const { call, create, otherJob, jobs } = await world() // Jobs other threads' agents made count too; a person's do not. @@ -377,7 +329,7 @@ describe('the schedule tools (SPEC §15.1)', () => { expect((await call('schedule_create', { ...CREATE, name: 'Still too many' })).isError).toBe(true) }) - it('paused and ended jobs do not count, so pausing one makes room', async () => { + it('paused and ended jobs do not count, so pausing one makes room, and resuming one needs room', async () => { const { call, create, jobs } = await world() const ids: string[] = [] for (let made = 0; made < MAX_ACTIVE; made += 1) ids.push((await create({ name: `Job ${made}` })).id) @@ -387,6 +339,7 @@ describe('the schedule tools (SPEC §15.1)', () => { expect((await call('schedule_create', { ...CREATE, name: 'Room 1' })).isError).toBeUndefined() expect((await call('schedule_create', { ...CREATE, name: 'Room 2' })).isError).toBeUndefined() expect((await call('schedule_create', { ...CREATE, name: 'Over again' })).isError).toBe(true) + expect(await call('schedule_update', { jobId: ids[0], enabled: true })).toMatchObject({ isError: true, text: expect.stringContaining(`the limit is ${MAX_ACTIVE}`) }) }) it('a retry with the same clientRequestId returns the first job, makes no other, even at the cap', async () => { @@ -408,15 +361,13 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(again.id).not.toBe(other.id) }) - it('an agent can only shorten a job\'s number of runs, never remove or lengthen them, and cannot touch its end', async () => { + it('an agent may lengthen or remove a job\'s number of runs', async () => { const { call, create, stored } = await world() const job = await create({ repeat: { times: 5 } }) - expect(await call('schedule_update', { jobId: job.id, repeat: null })).toMatchObject({ isError: true, text: expect.stringContaining('only be shortened') }) - expect(await call('schedule_update', { jobId: job.id, repeat: { times: 9 } })).toMatchObject({ isError: true, text: expect.stringContaining('only be shortened') }) - expect(await call('schedule_update', { jobId: job.id, expiresAt: '2099-01-01T00:00:00.000Z' })).toMatchObject({ isError: true }) - expect(stored(job.id).repeat?.times).toBe(5) - expect((await call('schedule_update', { jobId: job.id, repeat: { times: 2 } })).isError).toBeUndefined() - expect(stored(job.id).repeat?.times).toBe(2) + expect((await call('schedule_update', { jobId: job.id, repeat: { times: 9 } })).isError).toBeUndefined() + expect(stored(job.id).repeat?.times).toBe(9) + expect((await call('schedule_update', { jobId: job.id, repeat: null })).isError).toBeUndefined() + expect(stored(job.id).repeat).toBeUndefined() }) }) @@ -509,18 +460,53 @@ describe('the schedule tools (SPEC §15.1)', () => { }) }) - describe('an agent sees and changes only the jobs its own thread made', () => { - it('lists them and no others: not a person\'s, not another thread\'s', async () => { + describe('an agent sees and changes every job of the profile', () => { + it('lists a person\'s jobs and other agents\' with its own, saying who made each', async () => { const { call, result, personJob, otherJob, create } = await world() const mine = await create() - personJob({ name: 'In p1', projectId: 'p1' }) - personJob({ name: 'Nowhere' }) - otherJob({ name: 'Other agent, p1', projectId: 'p1' }) - const ids = async () => (await result(call('schedule_list'))).jobs.map((job: { id: string }) => job.id) - expect(await ids()).toEqual([mine.id]) + const theirs = personJob({ name: 'In p1', projectId: 'p1' }) + const other = otherJob({ name: 'Other agent, p1', projectId: 'p1' }) + const listed = (await result(call('schedule_list'))).jobs as Array> + expect(listed.map((job) => job.id).sort()).toEqual([mine.id, theirs.id, other.id].sort()) + expect(listed.find((job) => job.id === theirs.id)).toMatchObject({ createdByAgent: false, createdByYou: false }) + expect(listed.find((job) => job.id === other.id)).toMatchObject({ createdByAgent: true, createdByYou: false, createdByThread: 'second' }) + }) + + it('changes, pauses, resumes, starts and removes a person\'s job, and records it', async () => { + const { call, personJob, stored, jobs, recordAgentAction, woke } = await world() + const theirs = personJob({ projectId: 'p1' }) + expect((await call('schedule_update', { jobId: theirs.id, prompt: 'Rewritten', schedule: { kind: 'interval', minutes: 60 } })).isError).toBeUndefined() + expect(stored(theirs.id)).toMatchObject({ prompt: 'Rewritten', schedule: { kind: 'interval', minutes: 60 }, permissionCeiling: 'full' }) + expect((await call('schedule_pause', { jobId: theirs.id })).isError).toBeUndefined() + expect(stored(theirs.id)).toMatchObject({ state: 'paused' }) + expect((await call('schedule_update', { jobId: theirs.id, enabled: true })).isError).toBeUndefined() + expect(stored(theirs.id)).toMatchObject({ enabled: true, state: 'scheduled' }) + expect((await call('schedule_run', { jobId: theirs.id })).isError).toBeUndefined() + expect(woke).toHaveBeenCalledTimes(1) + expect((await call('schedule_delete', { jobId: theirs.id })).isError).toBeUndefined() + expect(jobs.getJob(theirs.id)).toBeUndefined() + expect(recordAgentAction.mock.calls.map((entry) => entry[2])).toEqual(['scheduled_job_updated', 'scheduled_job_paused', 'scheduled_job_updated', 'scheduled_job_run', 'scheduled_job_deleted']) + }) + + it('a change to another agent\'s job shows in the thread that made it too', async () => { + const { call, otherJob, recordAgentAction } = await world() + const other = otherJob({ projectId: 'p1' }) + await call('schedule_update', { jobId: other.id, name: 'Renamed' }) + expect(recordAgentAction.mock.calls.map(([target, , action]) => [target.threadId, action])).toEqual([ + ['caller', 'scheduled_job_updated'], + ['second', 'scheduled_job_updated'] + ]) + }) + + it('a job that does not exist is refused', async () => { + const { call, denied, schedules } = await world() + for (const name of ['schedule_update', 'schedule_pause', 'schedule_run', 'schedule_delete']) { + expect((await denied(call(name, { jobId: 'no-such-job', name: 'x' })))!.code, name).toBe('mousse_scope_denied') + } + expect(schedules.update).not.toHaveBeenCalled() }) - it('shows when a job ends and why it is paused, and never a webhook', async () => { + it('shows when a job ends and why it is paused', async () => { const { call, result, create, jobs } = await world() const job = await create() await call('schedule_pause', { jobId: job.id, reason: 'not needed' }) @@ -529,51 +515,38 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(listed[0]).toMatchObject({ createdByAgent: true, createdByYou: true, expiresAt: expect.any(String), pausedReason: 'Paused by an agent: not needed' }) expect(listed[0].recentRuns.map((run: { runAt: string }) => run.runAt)).toEqual(['2026-10-27T04:00:00.000Z', '2026-10-27T03:00:00.000Z', '2026-10-27T02:00:00.000Z']) expect(JSON.stringify(listed)).not.toContain('long output') - expect(listed[0].hasWebhook).toBeUndefined() - }) - - it.each([ - ['schedule_update', { name: 'Renamed' }], - ['schedule_update', { prompt: 'Rewritten' }], - ['schedule_pause', {}], - ['schedule_run', {}] - ])('%s of a person\'s job is refused the same way as one that does not exist, and changes nothing', async (name, args) => { - const { call, denied, personJob, schedules, stored } = await world() - const theirs = personJob({ name: 'In p1', projectId: 'p1' }) - const before = stored(theirs.id) - const real = await denied(call(name, { jobId: theirs.id, ...args })) - const missing = await denied(call(name, { jobId: 'no-such-job', ...args })) - expect(real?.refused.code).toBe('scope_denied') - expect(real!.code).toBe('mousse_scope_denied') - expect(real!.message.replace(theirs.id, 'X')).toBe(missing!.message.replace('no-such-job', 'X')) - expect(schedules.update).not.toHaveBeenCalled() - expect(schedules.pause).not.toHaveBeenCalled() - expect(schedules.trigger).not.toHaveBeenCalled() - expect(stored(theirs.id)).toEqual(before) - }) - - it('another agent\'s job is refused too, and so is a person\'s job with a webhook or a workflow prompt', async () => { - const { call, denied, otherJob, personJob, jobs, stored } = await world() - const other = otherJob({ projectId: 'p1' }) - const hooked = personJob({ projectId: 'p1' }) - jobs.updateJob(hooked.id, { trigger: { webhook: { scheme: 'mousse', secretRef: 'ref', createdAt: NOW } } }) - const flow = personJob({ name: 'Deploy', prompt: '/deploy production', projectId: 'p1', schedule: { kind: 'interval', minutes: 1440 } }) - for (const job of [other, hooked, flow]) { - for (const [name, args] of [['schedule_update', { prompt: 'x' }], ['schedule_update', { schedule: { kind: 'interval', minutes: 15 } }], ['schedule_pause', {}], ['schedule_run', {}]] as const) - expect((await denied(call(name, { jobId: job.id, ...args })))!.code, `${name} ${job.name}`).toBe('mousse_scope_denied') - } - expect(stored(flow.id).schedule).toEqual({ kind: 'interval', minutes: 1440 }) - expect(stored(hooked.id).trigger).toBeDefined() }) + }) - it('another thread made job under the same caller project is not reachable by a different thread of the same person', async () => { - const { create, registry, request, turns, fx: f, denied } = await world() - const job = await create() - const second = await f.runningRun('second') - turns.register(appTurn({ threadId: 'second', runId: second.runId })) - const as = request({ threadId: 'second', runId: second.runId }) - expect((await denied(registry.call('schedule_pause', { jobId: job.id }, as)))!.code).toBe('mousse_scope_denied') - expect(JSON.parse((await registry.call('schedule_list', {}, as)).text).jobs).toEqual([]) + describe('the private line', () => { + it('a shared thread\'s agent never sees or binds a private thread\'s job; a private thread\'s agent never changes a shared one', async () => { + const w = await world() + w.threads.set('hidden', thread('hidden', { localOnly: true })) + const privateJob = w.personJob({ threadId: 'hidden' }) + const sharedJob = w.personJob({ projectId: 'p1' }) + const ids = async () => (await w.result(w.call('schedule_list'))).jobs.map((job: { id: string }) => job.id) + expect(await ids()).toEqual([sharedJob.id]) + expect((await w.denied(w.call('schedule_pause', { jobId: privateJob.id })))!.code).toBe('mousse_scope_denied') + expect(await w.call('schedule_create', { ...CREATE, threadId: 'hidden' })).toMatchObject({ isError: true, text: expect.stringContaining('was not found') }) + // From the private thread: it sees both, changes only the private one, and binds nothing to a shared thread. + const asHidden = await w.liveCaller('hidden') + expect(JSON.parse((await asHidden('schedule_list')).text).jobs.map((job: { id: string }) => job.id).sort()).toEqual([privateJob.id, sharedJob.id].sort()) + expect((await w.denied(asHidden('schedule_pause', { jobId: sharedJob.id })))!.message).toMatch(/private thread/) + expect((await asHidden('schedule_pause', { jobId: privateJob.id })).isError).toBeUndefined() + expect((await w.denied(asHidden('schedule_create', { ...CREATE, threadId: 'caller' })))!.message).toMatch(/private thread/) + }) + + it('a private thread\'s job runs in a private thread, never in new threads other devices see (issue #672)', async () => { + const w = await world() + w.threads.set('caller', thread('caller', { localOnly: true })) + const refused = await w.call('schedule_create', CREATE) + expect(refused.isError).toBe(true) + expect(refused.text).toMatch(/private thread/) + const bound = await w.create({ threadId: 'caller' }) + expect(w.stored(bound.id).threadId).toBe('caller') + const unbound = await w.call('schedule_update', { jobId: bound.id, threadId: null }) + expect(unbound.isError).toBe(true) + expect(unbound.text).toMatch(/private thread/) }) }) @@ -589,12 +562,10 @@ describe('the schedule tools (SPEC §15.1)', () => { }) it('records nothing for a call that was refused', async () => { - const { call, create, recordAgentAction, state } = await world() + const { call, create, recordAgentAction } = await world() const job = await create() recordAgentAction.mockClear() - state.person = false - await call('schedule_run', { jobId: job.id }).catch(() => undefined) - await call('schedule_update', { jobId: job.id, prompt: 'x' }).catch(() => undefined) + await call('schedule_update', { jobId: job.id, schedule: { kind: 'interval', minutes: 1 } }).catch(() => undefined) await call('schedule_update', { jobId: 'nope', name: 'x' }).catch(() => undefined) expect(recordAgentAction).not.toHaveBeenCalled() }) @@ -627,34 +598,23 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(stored(job.id).workspace).toBeUndefined() }) - it('rebinds a job to the caller\'s thread and takes that thread\'s project, and frees it with null', async () => { + it('rebinds a job to any thread and takes that thread\'s project, and frees it with null', async () => { const { call, create, stored } = await world() const job = await create() - await call('schedule_update', { jobId: job.id, threadId: 'caller' }) - expect(stored(job.id)).toMatchObject({ threadId: 'caller', projectId: 'p1' }) + await call('schedule_update', { jobId: job.id, threadId: 'elsewhere' }) + expect(stored(job.id)).toMatchObject({ threadId: 'elsewhere', projectId: 'p2' }) await call('schedule_update', { jobId: job.id, threadId: null }) - expect(stored(job.id)).toMatchObject({ projectId: 'p1' }) - expect(stored(job.id).threadId).toBeUndefined() - }) - - it('refuses another thread as the target', async () => { - const { call, create, denied, stored } = await world() - const job = await create() - expect((await denied(call('schedule_update', { jobId: job.id, threadId: 'elsewhere' })))!.code).toBe('mousse_scope_denied') + expect(stored(job.id)).toMatchObject({ projectId: 'p2' }) expect(stored(job.id).threadId).toBeUndefined() }) it.each([ - ['a slash prompt', { prompt: '/workflow run ship' }, /workflows/], ['a one-minute interval', { schedule: { kind: 'interval', minutes: 1 } }, /less than 15 minutes/], - ['a ten-minute interval', { schedule: { kind: 'interval', minutes: 10 } }, /less than 15 minutes/], ['every minute in cron', { schedule: { kind: 'cron', expr: '* * * * *' } }, /fixed list/], - ['a worktree', { workspace: { kind: 'worktree', path: '/work/wt' } }, /existing worktree/], - ['enabling the job', { enabled: true }, /schedule_pause/], ['an access cap', { accessCap: 'manage' }, /access/], - ['a permission ceiling', { permissionCeiling: 'full' }, /permission mode/], + ['a permission ceiling', { permissionCeiling: 'full' }, /set by Mousse/], ['a webhook trigger', { trigger: {} }, /webhook/], - ['another project', { projectId: 'p2' }, /project/], + ['a project that does not exist', { projectId: 'p9' }, /no project p9/], ['nothing', {}, /at least one field/] ])('refuses %s, and changes nothing', async (_name, patch, message) => { const { call, create, schedules, stored } = await world() @@ -666,15 +626,14 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(stored(job.id)).toEqual(before) }) - it('a job whose prompt is a workflow is not changed or started by an agent, however it got there', async () => { - const { call, create, jobs, stored } = await world() + it('changes a workflow prompt and a worktree as any other field', async () => { + const { call, create, stored, schedules } = await world() const job = await create({ schedule: { kind: 'manual' } }) - jobs.updateJob(job.id, { prompt: '/deploy production' }) - expect(await call('schedule_update', { jobId: job.id, schedule: { kind: 'interval', minutes: 15 } })).toMatchObject({ isError: true, text: expect.stringContaining('workflow') }) - expect(await call('schedule_run', { jobId: job.id })).toMatchObject({ isError: true, text: expect.stringContaining('workflow') }) - expect(stored(job.id).schedule).toEqual({ kind: 'manual' }) - // Pausing is always fine. - expect((await call('schedule_pause', { jobId: job.id })).isError).toBeUndefined() + expect((await call('schedule_update', { jobId: job.id, prompt: '/deploy production' })).isError).toBeUndefined() + expect((await call('schedule_update', { jobId: job.id, schedule: { kind: 'interval', minutes: 15 } })).isError).toBeUndefined() + schedules.validate.mockImplementation(() => ({ threadId: 'second' })) + expect((await call('schedule_update', { jobId: job.id, workspace: { kind: 'worktree', path: '/work/wt' } })).isError).toBeUndefined() + expect(stored(job.id)).toMatchObject({ prompt: '/deploy production', threadId: 'second', workspace: { kind: 'worktree', path: '/work/wt' } }) }) it('validates the job as it would be after the change', async () => { @@ -688,7 +647,7 @@ describe('the schedule tools (SPEC §15.1)', () => { }) }) - describe('an agent can never raise a job\'s limits', () => { + describe('an agent can never raise a job\'s ceiling', () => { it('keeps the narrower limits of a job when a wider caller changes what it does', async () => { const { call, create, state, stored } = await world() state.limits = { permissionCeiling: 'ask' } @@ -710,13 +669,15 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(stored(job.id)).toMatchObject({ permissionCeiling: 'accept_edits' }) }) - it('clearing a restrictive setting keeps the ceiling', async () => { + it('sets a permission mode up to the job\'s ceiling and the caller\'s, never above', async () => { const { call, create, state, stored } = await world() - state.limits = { permissionCeiling: 'ask' } - const job = await create({ workspace: { kind: 'newWorktree' } }) + state.limits = { permissionCeiling: 'accept_edits' } + const job = await create({ permissionMode: 'ask' }) + expect((await call('schedule_update', { jobId: job.id, permissionMode: 'accept_edits' })).isError).toBeUndefined() + expect(stored(job.id)).toMatchObject({ permissionMode: 'accept_edits', permissionCeiling: 'accept_edits' }) state.limits = { permissionCeiling: 'full' } - await call('schedule_update', { jobId: job.id, workspace: null }) - expect(stored(job.id)).toMatchObject({ permissionCeiling: 'ask' }) + expect(await call('schedule_update', { jobId: job.id, permissionMode: 'full' })).toMatchObject({ isError: true, text: expect.stringContaining('wider than') }) + expect(stored(job.id)).toMatchObject({ permissionMode: 'accept_edits', permissionCeiling: 'accept_edits' }) }) it('a change of the name alone leaves the limits as they were', async () => { @@ -728,15 +689,18 @@ describe('the schedule tools (SPEC §15.1)', () => { }) }) - describe('schedule_pause', () => { - it('pauses a job it made, says an agent did, and a person resumes it', async () => { - const { call, create, stored, schedules, jobs } = await world() + describe('schedule_pause and resuming', () => { + it('pauses a job, says an agent did, and resumes it with enabled: true', async () => { + const { call, create, stored, schedules } = await world() const job = await create() const outcome = await call('schedule_pause', { jobId: job.id, reason: 'The report is not needed this week' }) expect(JSON.parse(outcome.text).job).toMatchObject({ enabled: false, state: 'paused' }) expect(stored(job.id)).toMatchObject({ enabled: false, state: 'paused', pausedReason: 'Paused by an agent: The report is not needed this week' }) expect(schedules.pause).toHaveBeenCalledTimes(1) - expect(jobs.resumeJob(job.id)?.state).toBe('scheduled') + expect((await call('schedule_update', { jobId: job.id, enabled: true })).isError).toBeUndefined() + expect(stored(job.id)).toMatchObject({ enabled: true, state: 'scheduled' }) + expect((await call('schedule_update', { jobId: job.id, enabled: false })).isError).toBeUndefined() + expect(stored(job.id)).toMatchObject({ enabled: false, state: 'paused' }) }) it('pauses with a plain reason when none is given', async () => { @@ -746,18 +710,18 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(stored(job.id).pausedReason).toBe('Paused by an agent') }) - it('has no way to resume: update refuses enabled and run refuses a paused job', async () => { - const { call, create, stored } = await world() + it('schedule_run resumes a paused job and starts it', async () => { + const { call, create, stored, woke } = await world() const job = await create({ schedule: { kind: 'manual' } }) await call('schedule_pause', { jobId: job.id }) - expect((await call('schedule_update', { jobId: job.id, enabled: true })).isError).toBe(true) - expect(await call('schedule_run', { jobId: job.id })).toMatchObject({ isError: true, text: expect.stringContaining('paused') }) - expect(stored(job.id)).toMatchObject({ enabled: false, state: 'paused' }) + expect(JSON.parse((await call('schedule_run', { jobId: job.id })).text)).toMatchObject({ started: true }) + expect(stored(job.id).enabled).toBe(true) + expect(woke).toHaveBeenCalledTimes(1) }) }) describe('schedule_run', () => { - it('makes the job due now and wakes the scheduler', async () => { + it('makes the job due now and wakes the scheduler, from a run no person started too', async () => { const { call, create, stored, schedules, woke } = await world() const job = await create({ schedule: { kind: 'manual' } }) expect(stored(job.id).nextRunAt).toBeNull() @@ -808,22 +772,12 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(schedules.trigger).not.toHaveBeenCalled() expect(woke).not.toHaveBeenCalled() }) - }) describe('schedule_delete', () => { - /** A live run of `threadId` (a subagent's thread or another thread) whose calls go through the registry. */ - const liveCaller = async (w: Awaited>, threadId: string, runId?: string) => { - if (runId) { - w.fx.engine.markStarting(runId) - w.fx.engine.markRunning(runId) - } else runId = (await w.fx.runningRun(threadId)).runId - w.turns.register(appTurn({ threadId, runId })) - return (name: string, args: Record = {}) => w.registry.call(name, args, w.request({ threadId, runId: runId! })) - } const ids = async (w: Awaited>) => (await w.result(w.call('schedule_list'))).jobs.map((entry: { id: string }) => entry.id) - it('removes a job the thread made: it leaves the store and the list, and the thread records it with the job\'s name', async () => { + it('removes a job: it leaves the store and the list, and the thread records it with the job\'s name', async () => { const w = await world() const job = await w.create({ name: 'Watch the build' }) const kept = await w.create({ name: 'Keep me' }) @@ -838,24 +792,11 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(details).toMatchObject({ jobId: job.id, jobName: 'Watch the build', summary: expect.stringContaining('Watch the build') }) }) - it('needs no person\'s turn, so a job bound to its thread can remove itself when its work is done', async () => { - const w = await world() - const job = await w.create({ threadId: 'caller' }) - w.state.person = false - expect((await w.result(w.call('schedule_delete', { jobId: job.id }))).removed).toBe(true) - expect(w.jobs.getJob(job.id)).toBeUndefined() - }) - - it('a subagent\'s thread can hold a job (a person\'s turn there made it); its parent sees it in the list and removes it, and both threads record that', async () => { + it('a job a subagent made is removed by its parent, and both threads record that', async () => { const w = await world() const child = await w.fx.delegate(w.callerRun.runId, 'call-a') w.threads.set(child.childThreadId, thread(child.childThreadId)) - // Made through the tools by the subagent, after the person allowed it. const made = w.jobs.createJob({ ...CREATE, schedule: { kind: 'manual' }, createdBy: { threadId: child.childThreadId, runId: child.childRunId } }) - const listed = (await w.result(w.call('schedule_list'))).jobs - expect(listed).toEqual([expect.objectContaining({ id: made.id, createdByYou: false, createdBySubagent: child.childThreadId })]) - // Listed for removal, not handed over: the parent still cannot change it. - expect((await w.denied(w.call('schedule_pause', { jobId: made.id })))!.code).toBe('mousse_scope_denied') w.recordAgentAction.mockClear() expect((await w.result(w.call('schedule_delete', { jobId: made.id }))).removed).toBe(true) expect(w.jobs.getJob(made.id)).toBeUndefined() @@ -865,69 +806,6 @@ describe('the schedule tools (SPEC §15.1)', () => { ]) }) - it('a subagent of a person\'s turn creates and starts no job: `person` never passes down (§1.3)', async () => { - const w = await world() - const child = await w.fx.delegate(w.callerRun.runId, 'call-a') - w.threads.set(child.childThreadId, thread(child.childThreadId)) - const asChild = await liveCaller(w, child.childThreadId, child.childRunId) - expect(w.state.person).toBe(true) - expect(await w.denied(asChild('schedule_create', CREATE))).toMatchObject({ refused: { code: 'lacks_capability', lacks: 'person' } }) - expect(w.registry.listForThread(child.childThreadId).map((tool) => tool.name)).not.toContain('schedule_create') - expect(w.schedules.askFirst).not.toHaveBeenCalled() - expect(w.schedules.create).not.toHaveBeenCalled() - // Its parent, allowed, still adds one at once. - expect((await w.create()).id).toEqual(expect.any(String)) - }) - - it('a subagent removes the job it made, as its parent would, and never its parent\'s', async () => { - const w = await world() - const child = await w.fx.delegate(w.callerRun.runId, 'call-a') - w.threads.set(child.childThreadId, thread(child.childThreadId)) - const asChild = await liveCaller(w, child.childThreadId, child.childRunId) - const own = w.jobs.createJob({ ...CREATE, schedule: { kind: 'manual' }, createdBy: { threadId: child.childThreadId, runId: child.childRunId } }) - const parents = await w.create({ name: 'The parent\'s' }) - for (const id of [parents.id, 'missing']) { - const error = await w.denied(asChild('schedule_delete', { jobId: id })) - expect(error?.refused.code, id).toBe('scope_denied') - expect(error!.code).toBe('mousse_scope_denied') - } - expect(JSON.parse((await asChild('schedule_delete', { jobId: own.id })).text).removed).toBe(true) - expect(w.jobs.listJobs().map((job) => job.id)).toEqual([parents.id]) - }) - - // Who made the job, as seen from the caller: only its own thread and subagents below it are the caller's. - it.each([ - ['its own thread', 'caller', true], - ['its subagent', 'child', true], - ['a subagent of its subagent', 'grandchild', true], - ['a person (no creator)', undefined, false], - ['another thread', 'someone-else', false], - ['a fork of its thread (a fork is not a subagent)', 'fork-1', false], - ['its parent thread', 'parent', false] - ] as const)('a job made by %s (creator %s): removable %s', async (_label, creator, removable) => { - const w = await world() - const child = await w.fx.delegate(w.callerRun.runId, 'call-a') - w.fx.engine.markStarting(child.childRunId) - w.fx.engine.markRunning(child.childRunId) - const grandchild = await w.fx.delegate(child.childRunId, 'call-b') - w.fx.engine.delegations.createLineage({ threadId: 'fork-1', parentThreadId: 'caller', parentRunId: w.callerRun.runId, relationship: 'fork' }) - w.fx.engine.delegations.createLineage({ threadId: 'caller', parentThreadId: 'parent', parentRunId: w.callerRun.runId, relationship: 'fork' }) - const threadOf: Record = { caller: 'caller', child: child.childThreadId, grandchild: grandchild.childThreadId, 'someone-else': 'someone-else', 'fork-1': 'fork-1', parent: 'parent' } - const job = w.jobs.createJob({ name: 'A job', prompt: 'Do it', schedule: { kind: 'manual' }, ...(creator ? { createdBy: { threadId: threadOf[creator], runId: 'r' } } : {}) }) - if (removable) { - expect((await w.result(w.call('schedule_delete', { jobId: job.id }))).removed).toBe(true) - expect(w.jobs.getJob(job.id)).toBeUndefined() - return - } - const error = await w.denied(w.call('schedule_delete', { jobId: job.id })) - expect(error!.code).toBe('mousse_scope_denied') - expect(error!.message).toMatch(/removes only the jobs it made and the ones its subagents made/) - // Refused in the same words as a job that does not exist. - expect((await w.denied(w.call('schedule_delete', { jobId: 'missing' })))!.message).toBe(error!.message.replace(job.id, 'missing')) - expect(w.jobs.getJob(job.id)).toBeDefined() - expect(w.schedules.remove).not.toHaveBeenCalled() - }) - it('a repeat, a retry with the same clientRequestId and a job someone removed in between say it is gone, and change nothing else', async () => { const w = await world() const job = await w.create({ name: 'Once' }) @@ -936,9 +814,6 @@ describe('the schedule tools (SPEC §15.1)', () => { const records = w.recordAgentAction.mock.calls.length expect(await w.result(w.call('schedule_delete', { jobId: job.id, clientRequestId: 'del-1' }))).toMatchObject({ removed: true, alreadyRemoved: true, replayed: true, job: { id: job.id, name: 'Once' } }) expect(await w.result(w.call('schedule_delete', { jobId: job.id }))).toMatchObject({ removed: true, alreadyRemoved: true, job: { id: job.id, name: 'Once' } }) - // Another thread learns nothing about a job it never had. - const asSecond = await liveCaller(w, 'second') - expect((await w.denied(asSecond('schedule_delete', { jobId: job.id })))!.code).toBe('mousse_scope_denied') // The person deletes the other job while the agent's call is between its check and the removal. w.schedules.remove.mockImplementationOnce((id: string) => { w.jobs.deleteJob(id) @@ -992,16 +867,4 @@ describe('the schedule tools (SPEC §15.1)', () => { expect(schedules.create).not.toHaveBeenCalled() }) }) - it('a private thread\'s job runs in that thread or its lineage, never in new threads other devices see (issue #672)', async () => { - const w = await world() - w.threads.set('caller', thread('caller', { localOnly: true })) - const refused = await w.call('schedule_create', CREATE) - expect(refused.isError).toBe(true) - expect(refused.text).toMatch(/private thread/) - const bound = await w.create({ threadId: 'caller' }) - expect(w.stored(bound.id).threadId).toBe('caller') - const unbound = await w.call('schedule_update', { jobId: bound.id, threadId: null }) - expect(unbound.isError).toBe(true) - expect(unbound.text).toMatch(/private thread/) - }) }) diff --git a/tests/scheduledJobs.test.ts b/tests/scheduledJobs.test.ts index 04a6b41039..6e7768264e 100644 --- a/tests/scheduledJobs.test.ts +++ b/tests/scheduledJobs.test.ts @@ -137,21 +137,6 @@ describe('ScheduledJobStore', () => { }) }) - it('has "Agents may create jobs" off until a person turns it on, and keeps the choice', () => { - const config = MousseConfigStore.load(tempHome) - expect(config.agentJobsEnabled()).toBe(false) - config.updateScheduledSection({ agentJobs: true }) - expect(MousseConfigStore.load(tempHome).agentJobsEnabled()).toBe(true) - config.updateScheduledSection({ agentJobs: false }) - expect(MousseConfigStore.load(tempHome).agentJobsEnabled()).toBe(false) - // Other changes to the section leave the choice alone, and a value that is not a boolean never turns it on. - config.updateScheduledSection({ agentJobs: true }) - config.updateScheduledSection({ enabled: true }) - expect(MousseConfigStore.load(tempHome).agentJobsEnabled()).toBe(true) - config.set('scheduled.agentJobs', 'true') - expect(config.agentJobsEnabled()).toBe(false) - }) - it('has the limits on jobs agents create at their defaults, keeps a person\'s choice, and reads it without a restart', () => { const config = MousseConfigStore.load(tempHome) expect(config.agentJobLimits()).toEqual({ maxActive: 10, minIntervalMinutes: 15, lifetimeDays: 7 }) @@ -160,7 +145,7 @@ describe('ScheduledJobStore', () => { expect(MousseConfigStore.load(tempHome).agentJobLimits()).toEqual({ maxActive: 3, minIntervalMinutes: 60, lifetimeDays: 7 }) // The ends of each range are allowed; other changes to the section leave the values alone. config.updateScheduledSection({ agentJobMaxActive: 100, agentJobMinIntervalMinutes: 1440, agentJobLifetimeDays: 365 }) - config.updateScheduledSection({ agentJobs: true }) + config.updateScheduledSection({ enabled: true }) expect(MousseConfigStore.load(tempHome).agentJobLimits()).toEqual({ maxActive: 100, minIntervalMinutes: 1440, lifetimeDays: 365 }) config.updateScheduledSection({ agentJobMaxActive: 1, agentJobMinIntervalMinutes: 1, agentJobLifetimeDays: 1 }) expect(config.agentJobLimits()).toEqual({ maxActive: 1, minIntervalMinutes: 1, lifetimeDays: 1 }) @@ -1113,8 +1098,6 @@ describe('ScheduledJobService concurrency and occurrences', () => { tempHome = mkdtempSync(join(tmpdir(), 'mousse-scheduled-service-')) process.env.MOUSSE_HOME = tempHome config = MousseConfigStore.load(tempHome) - // Jobs agents created run only while agents may create jobs; the tests that say otherwise turn it off. - config.updateScheduledSection({ agentJobs: true }) store = new ScheduledJobStore(config) }) diff --git a/tests/scheduledTurn.test.ts b/tests/scheduledTurn.test.ts index a79d3272ac..b507a29b09 100644 --- a/tests/scheduledTurn.test.ts +++ b/tests/scheduledTurn.test.ts @@ -74,8 +74,6 @@ describe('scheduled jobs run as turns', () => { const boot = (adapters: ScriptedAdapter[], options: { pid?: number; start?: boolean; recover?: boolean; drivers?: HarnessDriver[] } = {}): World => { const daemon = phase6Daemon(fx.home, adapters, { pid: options.pid, ...(options.drivers ? { drivers: options.drivers } : {}) }) const config = MousseConfigStore.load(fx.home) - // Jobs agents created run only while agents may create jobs. - config.updateScheduledSection({ agentJobs: true }) const jobs = new ScheduledJobStore(config) jobs.setRunProbe(daemon.orch.scheduledRunProbe()) const service = new ScheduledJobService({ runIsolated: (prompt, ingress) => daemon.orch.runIsolatedScheduledJob(prompt, ingress) }, jobs, daemon.store, daemon.projects) @@ -1350,176 +1348,69 @@ describe('scheduled jobs run as turns', () => { expect(mode(w, (await finished(w, direct.id)).runId)).toBe('ask') }) - describe('which runs may create jobs, and what the owner records for them', () => { + describe('what the owner records for a job an agent makes', () => { const wireJobs = (w: World) => { w.orch.setScheduledJobs({ - enabled: () => true, list: () => w.jobs.listJobs(), get: (id) => w.jobs.getJob(id), validate: () => ({}), create: (input) => w.jobs.createJob(input), update: (id, patch) => w.jobs.updateJob(id, patch), pause: (id, reason) => w.jobs.pauseJob(id, reason), + resume: (id) => w.jobs.resumeJob(id), trigger: (id) => w.jobs.triggerJob(id), wake: () => undefined - }) - const host = () => w.orch.mcpToolHost().schedules! - return { - limits: (threadId: string, runId: string) => host().limits({ threadId, runId }), - person: (threadId: string, runId: string) => w.orch.mcpToolHost().personHeld!({ threadId, runId }) - } + } as never) + return (threadId: string, runId: string) => w.orch.mcpToolHost().schedules!.limits({ threadId, runId }) } - const NARROWEST = { permissionCeiling: 'ask' } - it("a turn a person started from the app is a person's, and a job it makes gets its bound mode", async () => { + it('a job records the mode its maker\'s run is bound to, whoever started that run: a person, a job, another agent or a parent', async () => { const seen: Record = {} - let wired!: ReturnType + let limits!: ReturnType const pi = piAdapter((input) => { - seen.person = wired.person(input.threadId, input.runId) - seen.limits = wired.limits(input.threadId, input.runId) - return 'pi' - }) - const world = boot([pi]) - wired = wireJobs(world) - const project = projectOf(world) - const thread = world.store.createThread('Mine', project.id, project.path, ON_PRIMARY) - world.orch.setThreadPermissionMode(thread.id, 'full') - const sent = await world.orch.send('hello', false, { threadId: thread.id, source: 'gui', clientRequestId: 'person-1', awaitMode: 'turn' }) - expect(mode(world, sent.runId)).toBe('full') - expect(seen.person).toBe(true) - expect(seen.limits).toEqual({ permissionCeiling: 'full' }) - }) - - it("the same turn from the CLI is a person's too", async () => { - const seen: Record = {} - let wired!: ReturnType - const w = boot([piAdapter((input) => { seen.person = wired.person(input.threadId, input.runId); return 'pi' })]) - wired = wireJobs(w) - const project = projectOf(w) - const thread = w.store.createThread('Mine', project.id, project.path, ON_PRIMARY) - await w.orch.send('hello', false, { threadId: thread.id, source: 'cli', clientRequestId: 'person-1', awaitMode: 'turn' }) - expect(seen.person).toBe(true) - }) - - it("no other run is a person's: a scheduled run, a remote turn, an agent's message, a bot's thread, a wake, a continuation, a run with no binding", async () => { - const seen: Record = {} - let wired!: ReturnType - const pi = piAdapter((input) => { - seen[input.threadId] = { person: wired.person(input.threadId, input.runId), limits: wired.limits(input.threadId, input.runId) } + seen[input.threadId] = limits(input.threadId, input.runId) return 'pi' }) const w = boot([pi]) - wired = wireJobs(w) + limits = wireJobs(w) const project = projectOf(w) - const make = (name: string) => { + const make = (name: string, permissionMode: 'full' | 'accept_edits') => { const thread = w.store.createThread(name, project.id, project.path, ON_PRIMARY) - w.orch.setThreadPermissionMode(thread.id, 'full') + w.orch.setThreadPermissionMode(thread.id, permissionMode) return thread } - + // A person's turn from the app. + const mine = make('Mine', 'full') + const sent = await w.orch.send('hello', false, { threadId: mine.id, source: 'gui', clientRequestId: 'person-1', awaitMode: 'turn' }) + expect(seen[mine.id]).toEqual({ permissionCeiling: mode(w, sent.runId) }) + expect(seen[mine.id]).toEqual({ permissionCeiling: 'full' }) // A scheduled run. - const scheduledThread = make('Scheduled') + const scheduledThread = make('Scheduled', 'accept_edits') const job = addJob(w, { name: 'Scheduled', prompt: 'scheduled run', threadId: scheduledThread.id, projectId: project.id }) await runNow(w, job) - await finished(w, job.id) - expect(seen[scheduledThread.id]).toEqual({ person: false, limits: NARROWEST }) - - // A remote send. - const remote = make('Remote') - await w.orch.runRemoteTurn(remote.id, 'remote message', w.store) - expect(seen[remote.id]).toEqual({ person: false, limits: NARROWEST }) - - // A message another agent sent with thread_send: an interactive origin, but source mcp. - const origin = make('Origin') - const target = make('Target') - const personRun = await w.orch.send('start', false, { threadId: origin.id, source: 'gui', clientRequestId: 'person-1', awaitMode: 'turn' }) - expect(seen[origin.id]?.person).toBe(true) - await w.orch.mcpToolHost().sendToThread!(target.id, { content: 'please do it', mode: 'agent' }, { - clientRequestId: 'agent-send-1', - actor: { kind: 'agent', threadId: origin.id, runId: personRun.runId!, toolCallId: 'call-1' } - }) - await waitFor(() => Boolean(seen[target.id]), 'the agent-sent turn') - expect(seen[target.id]).toEqual({ person: false, limits: NARROWEST }) - - // A bot's thread, even for a run a person started. - const botThread = make('Bot') - const botRun = await w.orch.send('hello bot', false, { threadId: botThread.id, source: 'gui', clientRequestId: 'person-2', awaitMode: 'turn' }) - expect(wired.person(botThread.id, botRun.runId!)).toBe(true) - w.orch.setBotThreads({ roleOf: (threadId: string) => (threadId === botThread.id ? 'activation' : undefined) } as never) - expect(wired.person(botThread.id, botRun.runId!)).toBe(false) - expect(wired.limits(botThread.id, botRun.runId!)).toEqual(NARROWEST) - w.orch.setBotThreads(null as never) - - // A wake, a continuation and any other source, none of which bound a turn. - for (const source of ['wake', 'provider-continuation', 'steer-followup', 'queue', 'integration', 'protocol', 'something-new']) { - const dispatched = await w.engine.dispatch({ kind: 'send', threadId: origin.id, clientRequestId: `unbound:${source}`, source }) - if (dispatched.status !== 'accepted') throw new Error('send rejected') - expect(wired.person(origin.id, dispatched.runId), source).toBe(false) - expect(wired.limits(origin.id, dispatched.runId), source).toEqual(NARROWEST) - } - }) - - it("no subagent holds person, not even one of a person's turn, and a subagent of any other run records the narrowest", async () => { - const w = boot([piAdapter(() => 'pi')]) - const wired = wireJobs(w) - const project = projectOf(w) - const thread = w.store.createThread('Mine', project.id, project.path, ON_PRIMARY) - w.orch.setThreadPermissionMode(thread.id, 'full') - const delegate = (parentThreadId: string, parentRunId: string, key: string) => - w.engine.requestDelegation({ parentThreadId, parentRunId, clientRequestId: `delegation:${parentRunId}:${key}`, prompt: 'look', workspace: 'shared', wake: 'always', title: key }) - const person = await w.orch.send('start', false, { threadId: thread.id, source: 'gui', clientRequestId: 'person-1', awaitMode: 'turn' }) - const child = await delegate(thread.id, person.runId!, 'child') - const grandchild = await delegate(child.childThreadId, child.childRunId, 'grandchild') - expect(wired.person(child.childThreadId, child.childRunId)).toBe(false) - expect(wired.person(grandchild.childThreadId, grandchild.childRunId)).toBe(false) - const woken = await w.engine.dispatch({ kind: 'send', threadId: thread.id, clientRequestId: 'unbound:wake', source: 'wake' }) - if (woken.status !== 'accepted') throw new Error('send rejected') - const ofWake = await delegate(thread.id, woken.runId, 'of-wake') - expect(wired.person(ofWake.childThreadId, ofWake.childRunId)).toBe(false) - expect(wired.limits(ofWake.childThreadId, ofWake.childRunId)).toEqual(NARROWEST) - - // Bound runs no person started: a job's, and another agent's message. - const jobThread = w.store.createThread('Job', project.id, project.path, ON_PRIMARY) - w.orch.setThreadPermissionMode(jobThread.id, 'full') - const job = addJob(w, { name: 'Job', prompt: 'scheduled run', threadId: jobThread.id, projectId: project.id }) - await runNow(w, job) const jobRun = (await finished(w, job.id)).runId! - const target = w.store.createThread('Target', project.id, project.path, ON_PRIMARY) - w.orch.setThreadPermissionMode(target.id, 'full') + expect(seen[scheduledThread.id]).toEqual({ permissionCeiling: mode(w, jobRun) }) + // A message another agent sent with thread_send. + const target = make('Target', 'full') await w.orch.mcpToolHost().sendToThread!(target.id, { content: 'please do it', mode: 'agent' }, { clientRequestId: 'agent-send-1', - actor: { kind: 'agent', threadId: thread.id, runId: person.runId!, toolCallId: 'call-1' } + actor: { kind: 'agent', threadId: mine.id, runId: sent.runId!, toolCallId: 'call-1' } }) - await waitFor(() => w.engine.listRuns(target.id).some((run) => run.status === 'completed'), 'the agent-sent turn') + await waitFor(() => Boolean(seen[target.id]), 'the agent-sent turn') const agentRun = w.engine.listRuns(target.id)[0]!.runId - for (const [name, threadId, runId] of [['job', jobThread.id, jobRun], ['agent message', target.id, agentRun]] as const) { - const ofIt = await delegate(threadId, runId, `of-${name}`) - const below = await delegate(ofIt.childThreadId, ofIt.childRunId, `below-${name}`) - expect(wired.person(ofIt.childThreadId, ofIt.childRunId), name).toBe(false) - expect(wired.person(below.childThreadId, below.childRunId), name).toBe(false) - expect(wired.limits(below.childThreadId, below.childRunId), name).toEqual(NARROWEST) - } - - // A person's turn on a bot's thread: its subagents record the narrowest too. - const botThread = w.store.createThread('Bot', project.id, project.path, ON_PRIMARY) - w.orch.setThreadPermissionMode(botThread.id, 'full') - const botRun = await w.orch.send('hello bot', false, { threadId: botThread.id, source: 'gui', clientRequestId: 'person-2', awaitMode: 'turn' }) - const ofBot = await delegate(botThread.id, botRun.runId!, 'of-bot') - expect(wired.person(ofBot.childThreadId, ofBot.childRunId)).toBe(false) - w.orch.setBotThreads({ roleOf: (threadId: string) => (threadId === botThread.id ? 'activation' : undefined) } as never) - expect(wired.limits(ofBot.childThreadId, ofBot.childRunId)).toEqual(NARROWEST) - w.orch.setBotThreads(null as never) + expect(seen[target.id]).toEqual({ permissionCeiling: mode(w, agentRun) }) + // A subagent of the person's turn. + const child = await w.engine.requestDelegation({ parentThreadId: mine.id, parentRunId: sent.runId!, clientRequestId: `delegation:${sent.runId}:child`, prompt: 'look', workspace: 'shared', wake: 'always', title: 'child' }) + expect(limits(child.childThreadId, child.childRunId)).toEqual({ permissionCeiling: mode(w, child.childRunId) ?? 'ask' }) }) - it("a run that cannot be read is not a person's, and records the narrowest", async () => { + it('a run that cannot be read records the narrowest', async () => { const w = boot([piAdapter(() => 'pi')]) - const wired = wireJobs(w) - expect(wired.person('no-thread', 'no-run')).toBe(false) - expect(wired.limits('no-thread', 'no-run')).toEqual(NARROWEST) + const limits = wireJobs(w) + expect(limits('no-thread', 'no-run')).toEqual({ permissionCeiling: 'ask' }) }) }) }) - describe('questions asked by a scheduled turn', () => { it('hold the occurrence until the question ends, and the occurrence ends with the turn', async () => { let world: World | undefined diff --git a/tests/scheduledWebhookTrigger.test.ts b/tests/scheduledWebhookTrigger.test.ts index 2feeb581a7..c346bd51e0 100644 --- a/tests/scheduledWebhookTrigger.test.ts +++ b/tests/scheduledWebhookTrigger.test.ts @@ -1159,30 +1159,17 @@ describe('scheduled job webhook trigger', () => { expect(calls[0]).toMatch(/^Triage issue 8<\/webhook-data-[0-9a-f]{16}>\n/) }) - it('"Agents may create jobs" is off by default, is chosen over the protocol, and refuses anything else', async () => { - const limits = { agentJobMaxActive: 10, agentJobMinIntervalMinutes: 15, agentJobLifetimeDays: 7 } - expect(await client.request('scheduled.settings.get')).toEqual({ settings: { agentJobs: false, ...limits } }) - expect(await client.request('scheduled.settings.set', { agentJobs: true })).toEqual({ settings: { agentJobs: true, ...limits } }) - expect(await client.request('scheduled.settings.get')).toEqual({ settings: { agentJobs: true, ...limits } }) - expect(mms.config.agentJobsEnabled()).toBe(true) - await expect(client.request('scheduled.settings.set', { agentJobs: 'yes' })).rejects.toThrow() - await expect(client.request('scheduled.settings.set', { agentJobs: false, other: 1 })).rejects.toThrow(/not allowed/) - expect(mms.config.agentJobsEnabled()).toBe(true) - expect(await client.request('scheduled.settings.set', { agentJobs: false })).toEqual({ settings: { agentJobs: false, ...limits } }) - }) - it('the limits on jobs agents create are chosen over the protocol, take effect at once, and refuse a value out of range', async () => { const schedules = mms.orchestrator.mcpToolHost().schedules! expect(schedules.jobLimits()).toEqual({ maxActive: 10, minIntervalMinutes: 15, lifetimeDays: 7 }) const changed = await client.request('scheduled.settings.set', { agentJobMaxActive: 3, agentJobMinIntervalMinutes: 60, agentJobLifetimeDays: 30 }) - expect(changed).toEqual({ settings: { agentJobs: false, agentJobMaxActive: 3, agentJobMinIntervalMinutes: 60, agentJobLifetimeDays: 30 } }) + expect(changed).toEqual({ settings: { agentJobMaxActive: 3, agentJobMinIntervalMinutes: 60, agentJobLifetimeDays: 30 } }) // The tools read them at the next call: no restart. expect(schedules.jobLimits()).toEqual({ maxActive: 3, minIntervalMinutes: 60, lifetimeDays: 30 }) expect(mms.config.agentJobLimits()).toEqual({ maxActive: 3, minIntervalMinutes: 60, lifetimeDays: 30 }) - // Naming one limit leaves the others and "Agents may create jobs" alone. - await client.request('scheduled.settings.set', { agentJobs: true }) + // Naming one limit leaves the others alone. await client.request('scheduled.settings.set', { agentJobMaxActive: 4 }) - expect(await client.request('scheduled.settings.get')).toEqual({ settings: { agentJobs: true, agentJobMaxActive: 4, agentJobMinIntervalMinutes: 60, agentJobLifetimeDays: 30 } }) + expect(await client.request('scheduled.settings.get')).toEqual({ settings: { agentJobMaxActive: 4, agentJobMinIntervalMinutes: 60, agentJobLifetimeDays: 30 } }) const refused: Array<[Record, RegExp]> = [ [{ agentJobMaxActive: 0 }, /between 1 and 100/], @@ -1196,11 +1183,13 @@ describe('scheduled job webhook trigger', () => { [{ agentJobLifetimeDays: null }, /integer/], [{}, /at least one setting/], [{ agentJobMaxActive: 5, other: 1 }, /not allowed/], + // The old "Agents may create jobs" switch is gone. + [{ agentJobs: true }, /not allowed/], // One bad value in a request saves none of it. [{ agentJobMaxActive: 5, agentJobLifetimeDays: 400 }, /between 1 and 365/] ] for (const [params, message] of refused) await expect(client.request('scheduled.settings.set', params), JSON.stringify(params)).rejects.toThrow(message) - expect(await client.request('scheduled.settings.get')).toEqual({ settings: { agentJobs: true, agentJobMaxActive: 4, agentJobMinIntervalMinutes: 60, agentJobLifetimeDays: 30 } }) + expect(await client.request('scheduled.settings.get')).toEqual({ settings: { agentJobMaxActive: 4, agentJobMinIntervalMinutes: 60, agentJobLifetimeDays: 30 } }) // A lower limit pauses nothing: the jobs agents made keep running. const agent = schedules.create({ name: 'By an agent', prompt: 'x', schedule: { kind: 'interval', minutes: 120 }, createdBy: { threadId: 'agent-thread' }, expiresAt: new Date(Date.now() + 3_600_000).toISOString() }) @@ -1227,19 +1216,9 @@ describe('scheduled job webhook trigger', () => { expect(kept?.expiresAt).toBeUndefined() }) - it('the agents\' schedule tools are wired to the profile: a thread asks first, the profile checks a job, and a run wakes the scheduler', async () => { + it('the agents\' schedule tools are wired to the profile: the profile checks a job, and a run wakes the scheduler', async () => { const schedules = mms.orchestrator.mcpToolHost().schedules! expect(schedules).toBeDefined() - expect(schedules.threadAllowed('agent-thread')).toBe(false) - // The owner says which run holds person: a run that does not exist does not. - expect(mms.orchestrator.mcpToolHost().personHeld!({ threadId: 'no-thread', runId: 'no-run' })).toBe(false) - // The first ask is durable and listed; Allow lets the thread add more. - const ask = schedules.askFirst({ threadId: 'agent-thread', requestKey: 'k1', job: { name: 'Asked', prompt: 'x', schedule: { kind: 'manual' }, createdBy: { threadId: 'agent-thread' } } }) - expect(mms.automationIndex().items.find((item) => item.kind === 'ask')).toMatchObject({ id: ask.id, attention: { kind: 'ask', answer: { kind: 'agent_ask', askId: ask.id } } }) - await client.request('scheduled.settings.set', { agentJobLifetimeDays: 7 }) - const answered = mms.answerAgentJobAsk(ask.id, 'allow') - expect(mms.scheduled.getJob(answered.jobId!)).toMatchObject({ name: 'Asked', createdBy: { threadId: 'agent-thread' }, expiresAt: expect.any(String) }) - expect(schedules.threadAllowed('agent-thread')).toBe(true) // The profile's own checks: a model it does not have, and a new worktree with no project. expect(() => schedules.validate({ workspace: { kind: 'newWorktree' } })).toThrow(/needs a project/) expect(() => schedules.validate({ selection: { instanceId: 'no-such-instance', llmProvider: '', model: 'x' } })).toThrow() @@ -1251,7 +1230,8 @@ describe('scheduled job webhook trigger', () => { schedules.wake() expect(wake).toHaveBeenCalledTimes(1) expect(schedules.pause(job.id, 'Paused by an agent')?.state).toBe('paused') - expect(schedules.list().map((entry) => entry.id).sort()).toEqual([answered.jobId!, job.id].sort()) + expect(schedules.resume(job.id)?.state).not.toBe('paused') + expect(schedules.list().map((entry) => entry.id)).toEqual([job.id]) }) it('refuses to enable a one-time job and reports a listener that cannot bind', async () => { diff --git a/tests/themeSelectors.test.ts b/tests/themeSelectors.test.ts index 7dd32f0021..1a2f5db4d8 100644 --- a/tests/themeSelectors.test.ts +++ b/tests/themeSelectors.test.ts @@ -65,7 +65,6 @@ const DECISIONS: Record = { 'an approval in the composer\'s dock': 'src/renderer/components/ComposerNotice.tsx', 'an approval in the composer (a plain question is not a decision)': 'src/renderer/components/ComposerQuestionModal.tsx', 'Needs you asks (bots, workflows, first-creation)': 'src/renderer/components/asks/AskCard.tsx', - 'an automation\'s ask in the inbox': 'src/renderer/components/automations/inbox/AutomationsInbox.tsx', 'a workflow run\'s approval': 'src/renderer/components/workflows/WorkflowRunPanel.tsx', 'a bot\'s ask in its chat': 'src/renderer/components/bots/BotAskReplies.tsx', 'a bot owner\'s permission decision': 'src/renderer/components/chats/BotPermissionDecision.tsx', From f4770aa125c504709d26a371dd1eb883c653ce91 Mon Sep 17 00:00:00 2001 From: TheAnimatrix Date: Mon, 30 Nov 2026 03:49:51 +0530 Subject: [PATCH 03/15] feat(automations): a thread's agent lists, changes, pauses and turns on automations The automation tools reach an ordinary chat's agent as well as the Automation manager and bots, and an agent changes or pauses any automation, not only one the person's message names. automation_enable turns a draft on for any agent, no wider than its own thread's mode; a bot still turns on only the drafts it wrote, under its grant. --- src/mms/automations/AutomationDrafts.ts | 59 +++++-------- src/mms/automations/automationManager.ts | 4 +- src/mms/run/mcp/appTools/agentMessage.ts | 16 +--- src/mms/run/mcp/appTools/automations.ts | 73 ++++++---------- src/mms/run/mcp/appTools/index.ts | 2 +- tests/automationDrafts.test.ts | 105 +++++++++-------------- 6 files changed, 92 insertions(+), 167 deletions(-) diff --git a/src/mms/automations/AutomationDrafts.ts b/src/mms/automations/AutomationDrafts.ts index 516ae178e3..1e58190be5 100644 --- a/src/mms/automations/AutomationDrafts.ts +++ b/src/mms/automations/AutomationDrafts.ts @@ -60,11 +60,8 @@ export interface DraftAuthor { originThreadId?: string } -/** - * Who calls `automation_update` or `automation_pause`: a bot, or the manager with the person's current request (their - * latest message on its thread), which names the automation it may change ("Change automation: ", or its name). - */ -export type AutomationEditor = { botId: string } | { managerThreadId: string; request?: string } +/** Who calls `automation_update` or `automation_pause`: a bot, or any other agent's thread (the manager's included). */ +export type AutomationEditor = { botId: string } | { threadId: string } /** What an agent's edit pauses an automation with: the person checks the change, then resumes it. */ export const AGENT_EDIT_PAUSE = 'Changed by an agent. Check it, then resume it.' @@ -114,19 +111,6 @@ export const REQUEST_URL_PROBLEM = 'Set up its request URL in Edit details › R export class AutomationDraftError extends Error {} -/** - * Whether the person's request names the automation: its id, or its whole name (three letters or more) as words of - * their own, in any case: "retest the build" names neither "Test" nor "Build check". - */ -function namedIn(request: string | undefined, job: ScheduledJob): boolean { - if (!request) return false - if (job.id && request.includes(job.id)) return true - const name = job.name.trim() - if (name.length < 3) return false - const words = name.split(/\s+/).map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('\\s+') - return new RegExp(`(?, botId: string): { id: string; enabled: boolean; problems: string[]; automation: AutomationContract } { + enable(args: Record, author: DraftAuthor): { id: string; enabled: boolean; problems: string[]; automation: AutomationContract } { const { draftId: _draftId, ...fields } = args let draftId: string if (Object.keys(fields).length) { - draftId = this.save(args, { botId }).draftId + draftId = this.save(args, author).draftId } else { - if (args.draftId === undefined) fail('Pass draftId to turn on a draft you wrote, or name, trigger and prompt to write one and turn it on.') + if (args.draftId === undefined) fail('Pass draftId to turn on a draft, or name, trigger and prompt to write one and turn it on.') draftId = text(args.draftId, 'draftId', 256) - // A bot turns on only the drafts it wrote, as it changes only those. - if (this.draftJob(draftId).draft!.botId !== botId) fail(`No draft ${draftId}.`) + // A bot turns on only the drafts it wrote, as it changes only those; a bot's draft is its own. + if (this.draftJob(draftId).draft!.botId !== author.botId) fail(`No draft ${draftId}.`) } const draft = this.draftJob(draftId) const { problems } = this.build({}, draft) @@ -664,7 +646,8 @@ export class AutomationDrafts { } return { id: draft.id, enabled: false, problems, automation: this.contract(this.deps.get(draft.id) ?? draft) } } - const on = this.turnOn(draftId) + const by = author.managerThreadId ?? author.originThreadId + const on = this.turnOn(draftId, by ? { threadId: by } : undefined) return { id: on.id, enabled: true, problems: [], automation: this.contract(on) } } diff --git a/src/mms/automations/automationManager.ts b/src/mms/automations/automationManager.ts index 123cdd2700..9f7c35de6e 100644 --- a/src/mms/automations/automationManager.ts +++ b/src/mms/automations/automationManager.ts @@ -30,7 +30,7 @@ export const AUTOMATION_MANAGER_INSTRUCTIONS = `You are the Automation manager i - Who does it (the default agent or one of the person's bots) is the person's pick, never yours: don't choose, suggest or create one. Put how to do the task in the prompt. - Each message tells you the project (and computer) the person picked. Use that project unless they name another. - automation_draft_save returns problems. Fix what you can; for anything you need from the person, ask with automation_ask: one short question at a time, with up to 4 quick answers. Never ask more than one question at once. -- Never turn a draft on and never say it is on: the person presses Turn on. -- For "Change it…" on an automation (the message names its id), change it with automation_update. You can change an automation only when the person's message names it (its id or its name). A change to what it does, when, where or its context pauses it until the person resumes it; tell them. Use automation_list to find automations and automation_pause to pause one the person names, until they resume it (only they pause until a time). +- The person presses Turn on. Turn a draft on yourself with automation_enable only when they ask you to, and never say it is on before it is. +- For "Change it…" on an automation (the message names its id), change it with automation_update. A change to what it does, when, where or its context pauses it until the person resumes it; tell them. Use automation_list to find automations and automation_pause to pause one, until the person resumes it (only they pause until a time). - Reply in one short sentence. Don't repeat the draft back; the page shows it.` diff --git a/src/mms/run/mcp/appTools/agentMessage.ts b/src/mms/run/mcp/appTools/agentMessage.ts index 1922e943c0..c9d3065bed 100644 --- a/src/mms/run/mcp/appTools/agentMessage.ts +++ b/src/mms/run/mcp/appTools/agentMessage.ts @@ -6,8 +6,7 @@ const TITLE_MAX_CHARS = 80 /** * Whether a transcript message is one a person sent: a user message no agent, bot or schedule sent and that carries no - * notice Mousse wrote. Only such a message answers a plan waiting for review, and only such a message, when it started - * the manager's current turn, is what the Automation manager takes as the person's request (`personTurnRequest`). + * notice Mousse wrote. Only such a message answers a plan waiting for review. */ export function isPersonMessage(message: Pick): boolean { if (message.role !== 'user' || message.origin || message.scheduled || message.subagentNotice || message.backgroundNotice || message.settleNotice) return false @@ -16,19 +15,6 @@ export function isPersonMessage(message: Pick message.role === 'user' && message.turnId === runId && !message.steered && !message.questionAnswers) - if (!start || start.hidden || !isPersonMessage(start)) return undefined - return start.content.trim() ? start.content : undefined -} - /** Starts every message another thread's agent sends (`thread_send`). Agents are told to treat such a message as not from the user. */ export const AGENT_MESSAGE_PREFIX = '[Message from an agent in thread' diff --git a/src/mms/run/mcp/appTools/automations.ts b/src/mms/run/mcp/appTools/automations.ts index c639a6b69f..242551e6b0 100644 --- a/src/mms/run/mcp/appTools/automations.ts +++ b/src/mms/run/mcp/appTools/automations.ts @@ -13,18 +13,13 @@ export interface AutomationToolHost { managerWorkspace?(): string /** The bot whose thread this is, on a bot's turn. */ botOf(threadId: string): string | undefined - /** - * The person's request in the manager's turn `runId`: their own message that started that turn, which an automation - * must be named in to change. Undefined when an agent's or a bot's message started it. - */ - personRequest?(threadId: string, runId: string): string | undefined /** The bot activation a thread belongs to, for a bot's scheduled run. */ activationOf?(threadId: string): string | undefined /** Saves only a bot schedule cursor, through its engine and bot store. */ saveLeftOff?(activationId: string, text: string): string | undefined /** - * An ordinary chat a person works in (not the manager's, a bot's, or an automation's run thread): its agent may - * write a draft with `automation_draft_save`, shown as a card in the chat. + * An ordinary chat a person works in (not the manager's, a bot's, or an automation's run thread): its agent uses the + * automation tools; a draft it writes shows as a card in the chat. */ ordinaryThread?(threadId: string): boolean /** The inbox's runs: `run_report` finds the caller's live run and records its report. */ @@ -35,8 +30,8 @@ export interface AutomationToolHost { } /** - * A bot turns an automation on itself (`BOT_AUTOMATION_ENABLE_TOOL`): only with "create and turn on automations" in its - * grant, which its first call (or `escalate`) asks the owner for. + * An agent turns an automation on itself. A bot does it only with "create and turn on automations" in its grant, which + * its first call (or `escalate`) asks the owner for. */ export const AUTOMATION_ENABLE_TOOL = 'automation_enable' @@ -70,47 +65,36 @@ const FIELDS = { } /** - * The Automation manager's tools (v4): it turns a person's words into a draft that never runs until the person presses - * Turn on, asks one question at a time under the draft, and lists, changes and pauses automations ("Change it…"). - * Only the profile's hidden manager thread and a bot that was granted them can use them; a bot asks its owner first. + * The automation tools (v4): an agent turns a person's words into a draft, lists, changes, pauses and turns on + * automations. The profile's hidden manager thread, an ordinary chat's agent and a bot that was granted them use them + * (a bot asks its owner first); questions under a draft (`automation_ask`) are the manager's and a bot's. */ export function automationTools(host: AppToolHost): MousseTool[] { + /** The manager's thread, a bot's, or an ordinary chat ("check this daily": its draft's card shows in the chat). */ const reach = (threadId: string): AutomationToolHost | undefined => { const tools = host.automations?.() if (!tools) return undefined - return tools.isManagerThread(threadId) || tools.botOf(threadId) ? tools : undefined + return tools.isManagerThread(threadId) || tools.botOf(threadId) || tools.ordinaryThread?.(threadId) ? tools : undefined } - /** The draft tool also reaches an ordinary chat ("check this daily"): its card shows in the chat. */ - const reachDraft = (threadId: string): AutomationToolHost | undefined => { + /** A question under a draft comes back to the manager or the bot that asked it. */ + const reachAsk = (threadId: string): AutomationToolHost | undefined => { const tools = host.automations?.() if (!tools) return undefined - return reach(threadId) ?? (tools.ordinaryThread?.(threadId) ? tools : undefined) - } - /** Turning an automation on reaches only a bot's thread (its grant decides whether it holds the tool). */ - const reachBot = (threadId: string): AutomationToolHost | undefined => { - const tools = host.automations?.() - return tools?.botOf(threadId) ? tools : undefined + return tools.isManagerThread(threadId) || tools.botOf(threadId) ? tools : undefined } const author = (tools: AutomationToolHost, ctx: ToolCallContext): DraftAuthor => { const botId = tools.botOf(ctx.caller.threadId) if (botId) return { botId } return tools.isManagerThread(ctx.caller.threadId) ? { managerThreadId: ctx.caller.threadId } : { originThreadId: ctx.caller.threadId } } - /** Who edits: a bot, or the manager with the person's request in its current turn (none when no person started it). */ + /** Who edits: a bot (its own drafts only), or any other agent's thread. */ const editor = (tools: AutomationToolHost, ctx: ToolCallContext): AutomationEditor => { const botId = tools.botOf(ctx.caller.threadId) - if (botId) return { botId } - let request: string | undefined - try { - request = tools.personRequest?.(ctx.caller.threadId, ctx.caller.runId) - } catch { - request = undefined - } - return { managerThreadId: ctx.caller.threadId, ...(request ? { request } : {}) } + return botId ? { botId } : { threadId: ctx.caller.threadId } } const run = (ctx: ToolCallContext, act: (tools: AutomationToolHost) => unknown, find: (threadId: string) => AutomationToolHost | undefined = reach): ToolOutcome => { const tools = find(ctx.caller.threadId) - if (!tools) throw new McpToolError('mousse_scope_denied', 'Only the Automation manager or a bot can use the automation tools.') + if (!tools) throw new McpToolError('mousse_scope_denied', 'The automation tools are not available in this thread.') try { return json(act(tools)) } catch (error) { @@ -123,8 +107,8 @@ export function automationTools(host: AppToolHost): MousseTool[] { access: 'actsAsCaller' as const, // The only thread a draft names is a thread event's pull request thread: the service reads it and binds nothing else. authorize: checkedInHandler('trigger.threadId of a thread event: AutomationDrafts checks the thread exists and has a pull request'), - available: (turn: { threadId: string }) => (reach(turn.threadId) ? true as const : 'Only the Automation manager or a bot can use this.'), - // Listed only to the manager's thread and to bots; every other agent never sees them. + available: (turn: { threadId: string }) => (reach(turn.threadId) ? true as const : 'The automation tools are not available in this thread.'), + // Listed to the manager's thread, an ordinary chat and bots; not to an automation's run or a hidden thread. listed: (listing: { threadId?: string }) => Boolean(listing.threadId && reach(listing.threadId)) } // The live automation run a caller's turn is: its engine run, else its thread's (or its bot activation's). @@ -145,24 +129,21 @@ export function automationTools(host: AppToolHost): MousseTool[] { ...common, name: 'automation_draft_save', description: - 'Write the person\'s request as an automation draft: When (trigger), what to do (prompt) and the project; who does it is the person\'s pick, never yours. In a conversation where the person says "check this daily", put what "this" means in context. A draft never runs: the person turns it on from the card it shows. Pass draftId to change a draft you wrote. Returns { draftId, problems[] }: each problem is something to fix or to ask the person about.', + 'Write the person\'s request as an automation draft: When (trigger), what to do (prompt) and the project; who does it is the person\'s pick, never yours. In a conversation where the person says "check this daily", put what "this" means in context. A draft never runs until it is turned on: the person does it from the card it shows, or you do with automation_enable. Pass draftId to change a draft you wrote. Returns { draftId, problems[] }: each problem is something to fix or to ask the person about.', inputSchema: { type: 'object', properties: { draftId: { type: 'string' }, ...FIELDS }, required: ['name', 'trigger', 'prompt'] }, class: 'mutation', - available: (turn: { threadId: string }) => (reachDraft(turn.threadId) ? true as const : 'Only a conversation, the Automation manager or a bot can write a draft.'), - listed: (listing: { threadId?: string }) => Boolean(listing.threadId && reachDraft(listing.threadId)), - handler: (args, ctx) => run(ctx, (tools) => tools.drafts.save(args, author(tools, ctx)), reachDraft) + handler: (args, ctx) => run(ctx, (tools) => tools.drafts.save(args, author(tools, ctx))) }, { ...common, name: AUTOMATION_ENABLE_TOOL, description: - 'Turn an automation on yourself, as if the person pressed Turn on: it runs on its trigger in their permission mode until they pause or delete it. Only for a bot its owner allowed to "create and turn on automations" (without it, write a draft and ask with escalate {tool:"automation_enable"}). Pass draftId alone to turn on a draft you wrote, or the fields of automation_draft_save (with draftId to change one you wrote) to write one and turn it on at once. Turn one on only when your owner asked for it to run. Returns { id, enabled, problems[], automation }: with problems it stays a draft; fix them or ask, then call again.', + 'Turn an automation on yourself, as if the person pressed Turn on: it runs on its trigger until the person pauses or deletes it, in no wider a permission mode than yours. Pass draftId alone to turn on a draft, or the fields of automation_draft_save (with draftId to change a draft you wrote) to write one and turn it on at once. Returns { id, enabled, problems[], automation }: with problems it stays a draft; fix them or ask, then call again.', + botDescription: + 'Turn an automation on yourself, as if your owner pressed Turn on: it runs on its trigger in their permission mode until they pause or delete it. Only for a bot its owner allowed to "create and turn on automations" (without it, write a draft and ask with escalate {tool:"automation_enable"}). Pass draftId alone to turn on a draft you wrote, or the fields of automation_draft_save (with draftId to change one you wrote) to write one and turn it on at once. Turn one on only when your owner asked for it to run. Returns { id, enabled, problems[], automation }: with problems it stays a draft; fix them or ask, then call again.', inputSchema: { type: 'object', properties: { draftId: { type: 'string' }, ...FIELDS } }, class: 'mutation', - // A bot's alone: the manager and a chat's agent write drafts the person turns on. - available: (turn: { threadId: string }) => (reachBot(turn.threadId) ? true as const : 'Only a bot its owner allowed to turn automations on can use this.'), - listed: (listing: { threadId?: string }) => Boolean(listing.threadId && reachBot(listing.threadId)), - handler: (args, ctx) => run(ctx, (tools) => tools.drafts.enable(args, tools.botOf(ctx.caller.threadId)!), reachBot) + handler: (args, ctx) => run(ctx, (tools) => tools.drafts.enable(args, author(tools, ctx))) }, { ...common, @@ -174,7 +155,9 @@ export function automationTools(host: AppToolHost): MousseTool[] { required: ['draftId', 'question'] }, class: 'mutation', - handler: (args, ctx) => run(ctx, (tools) => tools.drafts.ask(args, author(tools, ctx))) + available: (turn: { threadId: string }) => (reachAsk(turn.threadId) ? true as const : 'Only the Automation manager or a bot asks under a draft; in a chat, ask the person in your reply.'), + listed: (listing: { threadId?: string }) => Boolean(listing.threadId && reachAsk(listing.threadId)), + handler: (args, ctx) => run(ctx, (tools) => tools.drafts.ask(args, author(tools, ctx)), reachAsk) }, { ...common, @@ -188,7 +171,7 @@ export function automationTools(host: AppToolHost): MousseTool[] { ...common, name: 'automation_update', description: - 'Change an automation (or a draft) by id: pass only the fields to change (not who does it: the person picks that). You may change your own drafts, and an automation only when the person\'s message names it. A change to what it does, when, where or its context pauses it until the person resumes it, and must leave it with no problems. Its permission mode can only be lowered here.', + 'Change an automation (or a draft) by id: pass only the fields to change (not who does it: the person picks that). You may change any automation and any draft (a bot: only the drafts it wrote). A change to what it does, when, where or its context pauses it until the person resumes it, and must leave it with no problems. Its permission mode can only be lowered here.', inputSchema: { type: 'object', properties: { id: { type: 'string' }, ...FIELDS }, required: ['id'] }, class: 'mutation', handler: (args, ctx) => run(ctx, (tools) => ({ automation: tools.drafts.update(args, editor(tools, ctx)) })) @@ -196,7 +179,7 @@ export function automationTools(host: AppToolHost): MousseTool[] { { ...common, name: 'automation_pause', - description: 'Pause an automation the person\'s message names, by id, until the person resumes it. Only the person pauses until a time. A pause already there stays. A run in progress finishes.', + description: 'Pause an automation by id, until the person resumes it. Only the person pauses until a time. A pause already there stays. A run in progress finishes.', inputSchema: { type: 'object', properties: { id: { type: 'string' }, reason: { type: 'string' } }, required: ['id'] }, class: 'mutation', handler: (args, ctx) => run(ctx, (tools) => ({ automation: tools.drafts.pause(args, editor(tools, ctx)) })) diff --git a/src/mms/run/mcp/appTools/index.ts b/src/mms/run/mcp/appTools/index.ts index 312d93968d..6020e2446c 100644 --- a/src/mms/run/mcp/appTools/index.ts +++ b/src/mms/run/mcp/appTools/index.ts @@ -51,7 +51,7 @@ export * from './registry' export { compileTool, heldBeforeArguments, parentHolds, toolNeeds, unattendedRefusal, type CompiledTool, type ToolEffect, type ToolNeeds } from './authority' export * from './turns' export type { AgentAccessResult, AgentActionDetails, AgentApprovalResult, AgentArchiveResult, AgentArchiveOwnResult, AgentCreatedThread, AgentRemoteThreadRequest, AgentRemoteThreadResult, RemoteProjectCandidate, AgentQueueCommand, AgentQueueResult, AgentScheduleHost, AgentRunCommandResult, AgentSendResult, AgentThreadRequest, ApprovalRequestInfo, AppToolHost, QueueSnapshot, RemoteThreadsHost, ThreadSearchHit } from './host' -export { AGENT_MESSAGE_END, AGENT_MESSAGE_PREFIX, agentMessage, agentMessageText, cleanRemoteSenderTitle, BOT_MESSAGE_END, BOT_MESSAGE_PREFIX, botMessage, botMessageText, isPersonMessage, personTurnRequest } from './agentMessage' +export { AGENT_MESSAGE_END, AGENT_MESSAGE_PREFIX, agentMessage, agentMessageText, cleanRemoteSenderTitle, BOT_MESSAGE_END, BOT_MESSAGE_PREFIX, botMessage, botMessageText, isPersonMessage } from './agentMessage' export type { BotAppToolDeps } from './bots' export { AUTOMATION_TOOL_NAMES, type AutomationToolHost } from './automations' export { THEME_READ_TOOL, THEME_SET_TOOL, type AppearanceToolHost } from './appearance' diff --git a/tests/automationDrafts.test.ts b/tests/automationDrafts.test.ts index 52b6c4a947..daf1819e9e 100644 --- a/tests/automationDrafts.test.ts +++ b/tests/automationDrafts.test.ts @@ -260,7 +260,7 @@ describe('automation drafts', () => { const { drafts, service } = setup({ ceiling: 'auto' }) const { draftId } = drafts.save({ ...PR_CHECK, project: 'p1', permissionMode: 'accept_edits' }, {}) drafts.turnOn(draftId) - const manager = { managerThreadId: 'manager', request: `Move it to Monday at 8\n\n[Project: mousse (p1) · Change automation: ${draftId}]` } + const manager = { threadId: 'manager' } const changed = drafts.update({ id: draftId, trigger: { kind: 'time', schedule: { kind: 'cron', expr: '0 8 * * 1' } }, permissionMode: 'full' }, manager) expect(changed.trigger).toEqual({ kind: 'time', schedule: { kind: 'cron', expr: '0 8 * * 1' } }) expect(changed.permissionMode).toBe('accept_edits') @@ -277,7 +277,7 @@ describe('automation drafts', () => { ;(drafts as unknown as { deps: AutomationDraftsDeps }).deps.meta = { get: (id) => meta.get(id), set: (id, value) => { meta.set(id, value) }, move: () => {} } const { draftId } = drafts.save({ ...PR_CHECK, project: 'p1', context: 'PR #712' }, {}) drafts.turnOn(draftId) - const manager = { managerThreadId: 'manager', request: `Change it\n\n[Change automation: ${draftId}]` } + const manager = { threadId: 'manager' } // Paused by the person until tomorrow: an agent's change takes the end away, so it never restarts on its own. const tomorrow = new Date(Date.now() + 86_400_000).toISOString() service.pauseJob(draftId, 'Away', tomorrow) @@ -302,7 +302,7 @@ describe('automation drafts', () => { drafts.turnOn(draftId) const other = drafts.save({ ...PR_CHECK, name: 'Nightly build', project: 'p1' }, {}).draftId drafts.turnOn(other) - const manager = { managerThreadId: 'manager', request: `Pause it\n\n[Change automation: ${draftId}]` } + const manager = { threadId: 'manager' } const soon = new Date(Date.now() + 60_000).toISOString() // Held after an agent's change: a pause with an end would restart it in a minute. Refused, and the hold stays. drafts.update({ id: draftId, prompt: 'Review open PRs, merge the green ones.' }, manager) @@ -317,26 +317,11 @@ describe('automation drafts', () => { drafts.pause({ id: draftId }, manager) expect(service.getJob(draftId)).toMatchObject({ enabled: false, pausedReason: 'Away' }) expect(service.getJob(draftId)!.resumeAt).toBeUndefined() - // An automation the person did not name is not the manager's to pause. - expect(() => drafts.pause({ id: other }, manager)).toThrow(/Ask the person to name it/) - expect(service.getJob(other)).toMatchObject({ enabled: true, state: 'scheduled' }) - // Named, it pauses until the person resumes it. - expect(drafts.pause({ id: other, reason: 'Quiet week' }, { managerThreadId: 'manager', request: 'pause the nightly build' })).toMatchObject({ paused: true }) + // Any other automation pauses too, until the person resumes it. + expect(drafts.pause({ id: other, reason: 'Quiet week' }, { threadId: 'manager' })).toMatchObject({ paused: true }) expect(service.getJob(other)).toMatchObject({ enabled: false, pausedReason: 'Quiet week' }) }) - it('takes a name only as words of its own, never inside other words', () => { - const { drafts, service } = setup() - const test = drafts.save({ ...PR_CHECK, name: 'Test', project: 'p1' }, {}).draftId - drafts.turnOn(test) - const refuse = (request: string) => expect(() => drafts.update({ id: test, name: 'Test 2' }, { managerThreadId: 'manager', request })).toThrow(/Ask the person to name it/) - refuse('retest the build') - refuse('run the tests') - refuse('attest it') - expect(service.getJob(test)!.name).toBe('Test') - expect(drafts.update({ id: test, name: 'Test 2' }, { managerThreadId: 'manager', request: 'Rename "test" to Test 2' }).name).toBe('Test 2') - }) - it('never leaves both the draft and the bot\'s schedule when Turn on cannot remove the draft', () => { const { drafts, service } = setup() drafts.nextWho({}, { kind: 'bot', botId: 'bot_1' }) @@ -359,39 +344,32 @@ describe('automation drafts', () => { const { drafts, service } = setup() const { draftId } = drafts.save({ ...PR_CHECK, project: 'p1' }, {}) drafts.turnOn(draftId) - const manager = { managerThreadId: 'manager', request: 'Rename the PR check to "PR sweep" and make it skip drafts' } + const manager = { threadId: 'manager' } // A new name changes nothing a run does: it keeps running. - drafts.update({ id: draftId, name: 'PR sweep' }, { managerThreadId: 'manager', request: 'rename pr check' }) + drafts.update({ id: draftId, name: 'PR sweep' }, { threadId: 'manager' }) expect(service.getJob(draftId)).toMatchObject({ name: 'PR sweep', enabled: true, state: 'scheduled' }) - const changed = drafts.update({ id: draftId, prompt: 'Review open PRs, skip drafts.' }, { ...manager, request: 'PR sweep: skip drafts' }) + const changed = drafts.update({ id: draftId, prompt: 'Review open PRs, skip drafts.' }, manager) expect(changed).toMatchObject({ paused: true, enabled: false }) expect(service.getJob(draftId)).toMatchObject({ prompt: 'Review open PRs, skip drafts.', pausedReason: 'Changed by an agent. Check it, then resume it.' }) }) - it('lets the manager change only its own drafts and the automation the person named; a bot only its own drafts', () => { + it('lets any agent\'s thread change any draft or automation, whoever started its turn; a bot only its own drafts', () => { const { drafts, service } = setup() const mine = drafts.save({ ...PR_CHECK, project: 'p1' }, { managerThreadId: 'manager' }).draftId const persons = drafts.save({ ...PR_CHECK, name: 'Nightly build', project: 'p1', permissionMode: 'accept_edits' }, {}).draftId drafts.turnOn(persons) const botDraft = drafts.save({ ...PR_CHECK, name: 'Bot idea', project: 'p1' }, { botId: 'bot_1' }).draftId - const manager = { managerThreadId: 'manager', request: 'Make the PR check weekly' } - expect(drafts.update({ id: mine, name: 'PR check weekly' }, manager).name).toBe('PR check weekly') - // The person did not name it: refused, and nothing changed. - expect(() => drafts.update({ id: persons, prompt: 'Delete every branch.' }, manager)).toThrow(/Ask the person to name it/) - // No request at all (an agent's or a bot's message started the turn): refused, saying why. - expect(() => drafts.update({ id: persons, prompt: 'Delete every branch.' }, { managerThreadId: 'manager' })).toThrow(/did not start this turn/) - expect(service.getJob(persons)!.prompt).toBe(PR_CHECK.prompt) - // Its own draft, though, it changes with no request: a draft never runs until the person turns it on. - expect(drafts.update({ id: mine, prompt: 'Check the PRs.' }, { managerThreadId: 'manager' }).prompt).toBe('Check the PRs.') - // Named by its name in the person's words, it may change. - expect(drafts.update({ id: persons, name: 'Nightly build 2' }, { managerThreadId: 'manager', request: 'rename the nightly build' }).name).toBe('Nightly build 2') + expect(drafts.update({ id: mine, name: 'PR check weekly' }, { threadId: 'manager' }).name).toBe('PR check weekly') + // The person's automation, from an ordinary chat's agent: changed, and held until the person resumes it. + expect(drafts.update({ id: persons, prompt: 'Check the nightly build.' }, { threadId: 'chat-1' })).toMatchObject({ prompt: 'Check the nightly build.', paused: true }) + service.resumeJob(persons) // A bot: its own draft only; never a person's automation or the manager's draft, and it pauses none of them. const bot = { botId: 'bot_1' } expect(drafts.update({ id: botDraft, name: 'Bot idea 2' }, bot).name).toBe('Bot idea 2') expect(() => drafts.update({ id: persons, prompt: 'x' }, bot)).toThrow(/only the drafts it wrote/) expect(() => drafts.update({ id: mine, prompt: 'x' }, bot)).toThrow(/only the drafts it wrote/) expect(() => drafts.pause({ id: persons }, bot)).toThrow(/pauses only its own schedules/) - expect(service.getJob(persons)).toMatchObject({ enabled: true, prompt: PR_CHECK.prompt }) + expect(service.getJob(persons)).toMatchObject({ enabled: true, prompt: 'Check the nightly build.' }) }) it('holds a draft from an ordinary chat to that chat’s mode, not the profile’s', () => { @@ -412,57 +390,52 @@ describe('automation drafts', () => { describe('the automation tools', () => { const ctx = (threadId: string) => ({ caller: { threadId, runId: 'r1' }, turn: { threadId }, toolCallId: 'c1' }) as unknown as ToolCallContext - it('work for the manager\'s thread and a bot, and nowhere else', async () => { + it('work for the manager's thread, an ordinary chat and a bot, and nowhere else', async () => { const { drafts } = setup() - const tools: AutomationToolHost = { drafts, isManagerThread: (id) => id === 'manager', botOf: (id) => (id === 'bot-thread' ? 'bot_1' : undefined) } + const tools: AutomationToolHost = { drafts, isManagerThread: (id) => id === 'manager', botOf: (id) => (id === 'bot-thread' ? 'bot_1' : undefined), ordinaryThread: (id) => id === 'chat-1' } const list = automationTools({ automations: () => tools } as unknown as AppToolHost) expect(list.map((tool) => tool.name)).toEqual(['automation_draft_save', 'automation_enable', 'automation_ask', 'automation_list', 'automation_update', 'automation_pause', 'run_report']) const save = list[0]! - expect(save.available!({ threadId: 'other' } as never)).toMatch(/Only a conversation, the Automation manager or a bot/) - expect(save.available!({ threadId: 'manager' } as never)).toBe(true) + expect(save.available!({ threadId: 'other' } as never)).toMatch(/not available in this thread/) + for (const threadId of ['manager', 'chat-1', 'bot-thread']) expect(save.available!({ threadId } as never)).toBe(true) + // A question under a draft is the manager's and a bot's: a chat's agent asks in its reply. + const ask = list.find((tool) => tool.name === 'automation_ask')! + expect(ask.available!({ threadId: 'chat-1' } as never)).toMatch(/ask the person in your reply/) const result = JSON.parse((await save.handler({ ...PR_CHECK, project: 'mousse' }, ctx('manager'))).text) as { draftId: string; problems: string[] } expect(result.problems).toEqual([]) // A bot writes its own drafts; it cannot change the manager's. expect((await save.handler({ ...PR_CHECK, draftId: result.draftId }, ctx('bot-thread'))).isError).toBe(true) const botDraft = JSON.parse((await save.handler(PR_CHECK, ctx('bot-thread'))).text) as { draftId: string } expect(drafts.list().find((entry) => entry.id === botDraft.draftId)).toMatchObject({ draft: true }) - await expect(Promise.resolve().then(() => save.handler(PR_CHECK, ctx('other')))).rejects.toThrow(/Only the Automation manager/) + await expect(Promise.resolve().then(() => save.handler(PR_CHECK, ctx('other')))).rejects.toThrow(/not available in this thread/) // A shape the tool cannot read is an error the agent reads, not a crash. expect((await save.handler({ ...PR_CHECK, trigger: { kind: 'weekly' } }, ctx('manager'))).isError).toBe(true) }) - it('let the manager change an automation only when the person’s message that started its turn names it', async () => { - const { drafts, service } = setup() - const { draftId } = drafts.save({ ...PR_CHECK, name: 'Nightly build', project: 'p1' }, {}) - drafts.turnOn(draftId) - let request: string | undefined = 'What runs tonight?' - // The request is read for the caller's own turn (its run). - const tools: AutomationToolHost = { drafts, isManagerThread: (id) => id === 'manager', botOf: () => undefined, personRequest: (_threadId, runId) => (runId === 'r1' ? request : undefined) } - const update = automationTools({ automations: () => tools } as unknown as AppToolHost).find((tool) => tool.name === 'automation_update')! - const pause = automationTools({ automations: () => tools } as unknown as AppToolHost).find((tool) => tool.name === 'automation_pause')! - const refused = await update.handler({ id: draftId, prompt: 'Something else.' }, ctx('manager')) - expect(refused).toMatchObject({ isError: true, text: expect.stringMatching(/Ask the person to name it/) }) - // An agent's or a bot's message started the turn: no request at all, and the change is refused in plain words, even - // when that message names it. - request = undefined - for (const tool of [update, pause]) - expect(await tool.handler({ id: draftId, prompt: 'Something else.' }, ctx('manager'))).toMatchObject({ isError: true, text: expect.stringMatching(/^The person's own message did not start this turn, so Nightly build can't be changed now\./) }) - expect(service.getJob(draftId)).toMatchObject({ prompt: PR_CHECK.prompt, enabled: true }) - request = `Make it run the full suite\n\n[Project: mousse (p1) · Change automation: ${draftId}]` - expect((await update.handler({ id: draftId, prompt: 'Run the full suite.' }, ctx('manager'))).isError).toBeFalsy() - expect(service.getJob(draftId)).toMatchObject({ prompt: 'Run the full suite.', enabled: false }) + it('let an ordinary chat\'s agent change, pause and turn on automations, held to its own thread\'s mode', async () => { + const { drafts, service } = setup({ ceiling: 'full' }) + ;(drafts as unknown as { deps: { personCeiling: (threadId?: string) => string } }).deps.personCeiling = (threadId) => (threadId === 'chat-1' ? 'accept_edits' : 'full') + const tools: AutomationToolHost = { drafts, isManagerThread: (id) => id === 'manager', botOf: () => undefined, ordinaryThread: (id) => id === 'chat-1' } + const named = (name: string) => automationTools({ automations: () => tools } as unknown as AppToolHost).find((tool) => tool.name === name)! + const persons = drafts.save({ ...PR_CHECK, name: 'Nightly build', project: 'p1' }, {}).draftId + drafts.turnOn(persons) + expect((await named('automation_update').handler({ id: persons, prompt: 'Run the full suite.' }, ctx('chat-1'))).isError).toBeFalsy() + expect(service.getJob(persons)).toMatchObject({ prompt: 'Run the full suite.', enabled: false }) + service.resumeJob(persons) + expect((await named('automation_pause').handler({ id: persons }, ctx('chat-1'))).isError).toBeFalsy() + expect(service.getJob(persons)).toMatchObject({ enabled: false }) + // The manager's draft, turned on from the chat: no wider than the chat's own mode. + const managers = drafts.save({ ...PR_CHECK, name: 'Manager', project: 'p1', permissionMode: 'full' }, { managerThreadId: 'manager' }).draftId + const on = JSON.parse((await named('automation_enable').handler({ draftId: managers }, ctx('chat-1'))).text) as { enabled: boolean } + expect(on.enabled).toBe(true) + expect(service.getJob(managers)).toMatchObject({ enabled: true, permissionCeiling: 'accept_edits', permissionMode: 'accept_edits' }) }) it('let a bot turn on only the drafts it wrote, or write one and turn it on at once, and keep a draft with problems a draft', async () => { const { drafts, service } = setup() const tools: AutomationToolHost = { drafts, isManagerThread: (id) => id === 'manager', botOf: (id) => (id === 'bot-thread' ? 'bot_1' : id === 'bot2-thread' ? 'bot_2' : undefined) } const enable = automationTools({ automations: () => tools } as unknown as AppToolHost).find((tool) => tool.name === 'automation_enable')! - // A bot's alone: the manager and an ordinary chat write drafts the person turns on. - expect(enable.available!({ threadId: 'manager' } as never)).toMatch(/Only a bot/) - expect(enable.listed!({ threadId: 'manager' })).toBe(false) expect(enable.available!({ threadId: 'bot-thread' } as never)).toBe(true) - await expect(Promise.resolve().then(() => enable.handler({ draftId: 'x' }, ctx('manager')))).rejects.toThrow(/Only the Automation manager or a bot/) - // A draft the bot wrote, turned on by id: the person's own automation, as their Turn on makes it. const { draftId } = drafts.save({ ...PR_CHECK, project: 'mousse', permissionMode: 'full' }, { botId: 'bot_1' }) // Another bot can't turn it on, nor can it turn on the manager's. From adfc6d9d48368eb28f7ae1d3c8a2840efa6a1710 Mon Sep 17 00:00:00 2001 From: TheAnimatrix Date: Mon, 30 Nov 2026 03:50:13 +0530 Subject: [PATCH 04/15] feat(approvals): any agent answers another thread's approvals and questions within its own mode The Answer approvals on other threads switch is gone, with the rules that only a subagent's direct parent answers it and that a turn a person started is theirs to answer. An agent, or a personal bot with Use your threads, answers any other thread's approval within its own permission mode, and its plain questions, labelled as its answer. A request the provider keeps for a person, and Always for this thread, stay the person's. --- docs/CONFIGURATION.md | 16 +- docs/GLOSSARY.md | 4 +- src/mms/orchestrator/UserQuestionService.ts | 18 +- src/mms/protocol/validators.ts | 4 +- src/mms/run/ThreadApprovals.ts | 8 +- src/mms/run/approvalRights.ts | 78 +----- src/mms/run/mcp/appTools/requestAnswer.ts | 6 +- .../settings/AgentAccessSettings.tsx | 31 +-- src/renderer/lib/settingsSearch.ts | 2 - src/shared/bots/personal/askText.ts | 2 +- src/shared/bots/personal/catalogue.ts | 2 +- src/shared/bots/personal/manifest.ts | 2 +- src/shared/settings.ts | 7 +- tests/run/approvalRights.test.ts | 243 +++++------------- 14 files changed, 97 insertions(+), 326 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 2f8a4df3d9..641c761946 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -42,9 +42,9 @@ Each agent enforces the mode with its own controls: - **Pi (both the Pi agent and the older Mousse loop):** commands (`bash`) ask under Ask and Auto-accept edits, edits (`edit`, `write`) ask under Ask; integrating a subagent's work asks unless the mode allows edits. - **Antigravity and other ACP agents:** the agent's own once-only permission options are asked or answered by the mode; its "always" and "session" options are not offered. An agent that approves tools itself (a generic ACP agent) runs only in Full access; a turn in another mode is refused with the fix named. -An approval request is saved. It waits as long as you take while you are in the chat, and survives closing the window and restarting Mousse: after a restart, answering it continues the thread, and an approval you give then covers that same action once. Any client can answer: the app, `mousse-cli approvals` (or `/approve` and `/deny` in the CLI chat), or a linked device that may chat; if another client answered first you are told who. Sending a message while an approval waits denies it, with your message as the reason. Runs nobody watches (workflows, bots, scheduled jobs, agent definitions) keep the ten-minute limit: an approval nobody answers then counts as a refusal. +An approval request is saved. It waits as long as you take while you are in the chat, and survives closing the window and restarting Mousse: after a restart, answering it continues the thread, and an approval you give then covers that same action once. Any client can answer: the app, `mousse-cli approvals` (or `/approve` and `/deny` in the CLI chat), or a linked device that may chat; if another client answered first you are told who. Another thread's agent may answer it too (`request_answer`), once and only within its own permission mode; the thread shows that an agent answered. A request the provider keeps for a person (such as Claude Code's own safety check) is yours alone. Sending a message while an approval waits denies it, with your message as the reason. Runs nobody watches (workflows, bots, scheduled jobs, agent definitions) keep the ten-minute limit: an approval nobody answers then counts as a refusal. -**Always for this thread.** An approval card can offer "Always for this thread" (in the CLI: `/approve always`, or `mousse-cli approvals answer allow_always`). It allows the request and lets the same request through later in this thread without asking. "Same" is exact: the same command in the same folder, or the same edit of the same file. Another command, argument, folder or tool still asks. A rule approves the text of the request, not what it does: `npm test` or `./build.sh` run whatever the project holds that time, and Claude's shell keeps its folder between calls, so the same command can run from a subfolder. It is not offered when the agent gives no stable description of the call (an ACP agent with no details, a Codex command with no text), when Codex gives a reason for asking (such as a retry outside the sandbox), for an integration of a subagent's work, or for Claude Code's own safety checks and anything it says must not be remembered, in any mode. A rule belongs to its thread: a fork or a subagent starts with none. It answers only turns you started from the app or the CLI: scheduled and webhook jobs, subagents, bots, workflows and messages another agent sends to the thread still ask. It remembers the permission mode you were asked under and is ignored while the thread asks about more than that, which applies again when you loosen the mode. That is not a kill switch: a rule made under Ask holds in every mode (this covers every Codex, pi and ACP command rule), so only revoking it stops it. Rules are listed and revoked with the CLI (`mousse-cli approvals rules `, `approvals reset [ruleId]`), and the thread shows a line each time one answers. Only you can make one, in the app or the CLI: a linked device or an agent answering for its subagent can allow a request once, never "always". +**Always for this thread.** An approval card can offer "Always for this thread" (in the CLI: `/approve always`, or `mousse-cli approvals answer allow_always`). It allows the request and lets the same request through later in this thread without asking. "Same" is exact: the same command in the same folder, or the same edit of the same file. Another command, argument, folder or tool still asks. A rule approves the text of the request, not what it does: `npm test` or `./build.sh` run whatever the project holds that time, and Claude's shell keeps its folder between calls, so the same command can run from a subfolder. It is not offered when the agent gives no stable description of the call (an ACP agent with no details, a Codex command with no text), when Codex gives a reason for asking (such as a retry outside the sandbox), for an integration of a subagent's work, or for Claude Code's own safety checks and anything it says must not be remembered, in any mode. A rule belongs to its thread: a fork or a subagent starts with none. It answers only turns you started from the app or the CLI: scheduled and webhook jobs, subagents, bots, workflows and messages another agent sends to the thread still ask. It remembers the permission mode you were asked under and is ignored while the thread asks about more than that, which applies again when you loosen the mode. That is not a kill switch: a rule made under Ask holds in every mode (this covers every Codex, pi and ACP command rule), so only revoking it stops it. Rules are listed and revoked with the CLI (`mousse-cli approvals rules `, `approvals reset [ruleId]`), and the thread shows a line each time one answers. Only you can make one, in the app or the CLI: a linked device or an agent can allow a request once, never "always". ## File format @@ -214,7 +214,6 @@ Automation **definitions** only (the code calls an automation a job). Runtime fi |-----|------|---------|-------------| | `scheduled.enabled` | `boolean` | `true` | When false, MMS/GUI does not start the scheduled ticker | | `scheduled.jobs` | `ScheduledJobDefinition[]` | `[]` | Job definitions (see below) | -| `scheduled.agentJobs` | `boolean` | `false` | Legacy. The switch is gone: the first time a thread's agent adds an automation through the `schedule_*` Mousse tools, the person is asked at the top of the Automations inbox, under Needs you (" wants to … · Allow / Not now"); Allow adds it and lets that thread add more within the limits. A profile that turned this on earlier lets every thread add them without asking | | `scheduled.agentJobMaxActive` | `integer` (1 to 100) | `10` | "At most … active" (Settings → Agents → Agent access, Automations agents add): active automations agents may have in the profile at once. Only a person sets it (that setting or `scheduled.settings.set`); no tool an agent holds can. Read at every use, so a change needs no restart. Lowering it never pauses or deletes an existing job: it refuses the next `schedule_create` until there is room | | `scheduled.agentJobMinIntervalMinutes` | `integer` (1 to 1440) | `15` | "At least … minutes apart": the fewest minutes between runs of a job an agent creates or changes. Same rules as above. It is checked when an agent creates a job or changes its schedule; jobs that already exist keep their schedule | | `scheduled.agentJobLifetimeDays` | `integer` (1 to 365) | `7` | "End after … days": how long a job an agent creates lasts unless a person extends it; also what `automation extend` gives when no number of days is named. It applies to jobs created or extended afterwards; the stored `expiresAt` of an existing job is not rewritten. A saved value that is not a whole number in range reads as the default | @@ -272,13 +271,10 @@ A plain-prompt run is a turn on a thread, admitted by the Run Engine like any me - **Questions and approvals.** A scheduled turn asks for tool approval and questions like any turn. Nobody is likely watching a per-run thread, so a question or approval waits for its timeout (10 minutes; up to an hour for `question_ask`) and is then denied; a person's message on a bound thread dismisses it and stops the run. The job's occurrence and the thread stay held for that time. A scheduled turn has no time limit of its own yet. > **Warning: `workspace: project` lets an unattended agent edit your own checkout.** The run works in the same folder you work in, with no worktree, no checkpoints and no undo, and two jobs on one project can edit it at the same time. For a job in a Git project, use `newWorktree` (`--workspace new-worktree`). -- **Jobs agents create.** Agents get six tools (`schedule_list`, `schedule_create`, `schedule_update`, `schedule_pause`, `schedule_run`, `schedule_delete`; see `docs/run-engine/SPEC.md` §15.1). A thread's first add asks the person (see `scheduled.agentJobs`). - - **Only a person's turn creates or starts jobs.** `schedule_create`, `schedule_run` and a `schedule_update` of anything but the name are refused unless a person started the run from the app or the CLI. A scheduled or webhook run, a message another agent sent, a subagent, a wake, a continuation, a bot, a remote send, a run with no recorded binding and one that cannot be read are all refused, so a job can never create or start jobs and no chain of jobs can form. - - **Creator scope.** An agent lists, changes, pauses and runs only the jobs its own thread created through these tools. A person's job, and a job another thread made, are refused like jobs that do not exist. Every change an agent makes is an `agent.action` event on its thread with a row in its transcript, and the job and its run records are labelled "Created by an agent". - - **Bounds.** A person sets them (`scheduled.agentJobMaxActive`, `agentJobMinIntervalMinutes`, `agentJobLifetimeDays`; defaults 10, 15 and 7), and the tools read them at every call. At most that many active agent-made jobs in the profile at once (counted from the saved jobs, so a restart does not reset it; paused and ended jobs do not count). A job runs no more often than every that many minutes (a cron expression has exactly five fields and a fixed list of minutes that far apart; above 60 minutes the hours it names must keep its runs that far apart too). A job ends that many days after it is made unless a person extends it. An agent can only shorten a job's number of runs. A lower limit does not delete or pause jobs that exist: it only refuses new creates or changes. A changed lifetime applies to jobs created or extended afterwards, and the `expiresAt` already stored is not rewritten. No `schedule_*` tool and no tool argument can change these settings. - - **No more than the creator.** The job records the permission mode of the turn that made it, and its runs get at most that; a change by an agent can only narrow it. A job cannot have a webhook until a person keeps it, run a workflow (a prompt starting with `/`; agents do not create, change or start those), use an existing worktree, or be enabled again by an agent: a person resumes a paused job. `schedule_run` is refused in the same cases as Run now (running, claimed, a run in progress or waiting in a queue), for a paused job and for one that has ended. - - **No switch stops them.** `scheduled.agentJobs` only decides whether a thread's first add asks the person; turning it off stops nothing that exists. A person pauses or deletes an agent's automation in the Automations inbox. - - **Threads that are gone.** A job bound to a deleted or archived thread, or made from a thread that was deleted, pauses with a reason instead of failing on every tick. +- **Jobs agents create.** Agents get six tools (`schedule_list`, `schedule_create`, `schedule_update`, `schedule_pause`, `schedule_run`, `schedule_delete`; see `docs/run-engine/SPEC.md` §15.1). A job an agent creates is made at once; nothing asks first. A `scheduled.agentJobs` value an older version saved is ignored and dropped. + - **Every job of the profile.** Any agent, a subagent's included and whoever started its run, lists, changes, pauses, resumes, runs and deletes every job of the profile: the person's own, its own and other agents'. A private thread's jobs stay on its side of the private line: a shared thread's agent does not see them, and a private thread's agent changes only private threads' jobs and binds a job only to a private thread. A personal bot sees and changes only the jobs it made. Every change an agent makes is an `agent.action` event on its thread with a row in its transcript (and on the thread that made the job, when another agent did), and the jobs agents make and their run records are labelled "Created by an agent". + - **Bounds.** A person sets them (`scheduled.agentJobMaxActive`, `agentJobMinIntervalMinutes`, `agentJobLifetimeDays`; defaults 10, 15 and 7), and the tools read them at every call. At most that many active agent-made jobs in the profile at once (counted from the saved jobs, so a restart does not reset it; paused and ended jobs do not count, and resuming one needs room). A job an agent creates or changes runs no more often than every that many minutes (a cron expression has exactly five fields and a fixed list of minutes that far apart; above 60 minutes the hours it names must keep its runs that far apart too). A job an agent creates ends that many days after it is made unless a person extends it; an agent may give a job an earlier end (`expiresAt`), never a later one than it has. A lower limit does not delete or pause jobs that exist: it only refuses new creates or changes. A changed lifetime applies to jobs created or extended afterwards, and the `expiresAt` already stored is not rewritten. No `schedule_*` tool and no tool argument can change these settings. + - **No more than the agent.** A job records the permission mode of the run that made it (or last changed what it does) as its ceiling, and its runs get at most that; an agent may choose the job's own mode up to that, never above, and a change by an agent never raises the ceiling. An agent may pick the model, a saved agent, the project, a new thread per run, a workflow prompt (starting with `/`), an existing worktree and the number of runs, and resume a paused job (`schedule_update` with `enabled: true`, or `schedule_run`). It cannot give a job a webhook or a pull request trigger, or the saved keys its runs read. `schedule_run` is refused in the same cases as Run now (running, claimed, a run in progress or waiting in a queue) and for a job that has ended. - **Threads that are gone.** A job bound to a deleted or archived thread, or made from a thread that was deleted, pauses with a reason instead of failing on every tick. - **`manual` jobs.** They have no next run and never complete; "Run now" starts them. - **Webhook trigger.** A job with a `trigger` is started by `POST /hooks/` on the webhook listener (see `docs/CLI.md`). A request carries `X-Mousse-Timestamp` (within 5 minutes of the daemon's clock) and `X-Mousse-Signature: sha256=`, the HMAC-SHA256 of `.` under the job's secret, checked in constant time. A signature-valid request leaves a receipt in `scheduled/triggers//receipts.json` (synced to disk before the request is answered, and kept until the request's timestamp can no longer pass the 5-minute check, so a captured request cannot be replayed, restarts included; a receipts file that cannot be read makes the job answer `503` until the secret is rotated, and a file full of still-valid receipts makes it answer `429` for a few minutes) and, when accepted, its body in `scheduled/triggers//.json` (owner-only: mode `0600`, and on Windows the `triggers` folder is limited to your account and SYSTEM; deleted when the run ends or after a day if nothing references it). A delivery waits for the next scheduler tick, which is woken at once; a job runs one delivery at a time (`409` while one is running, waiting in a queue or pending). A delivery does not move an interval or cron job's own timer. `scheduled/triggers//deliveries.json` logs the last 50 accepted deliveries (`accepted`, `queued`, `completed`, `failed`, `dispatch_failed`, `uncertain`) the last 20 refusals of signed requests (`running`, `pending`, `paused`, `replay`, `rate_limited`) and the last 20 requests that failed verification (`rejected_signature`, `too_large`), kept apart so unsigned traffic never pushes the others out. Every write to `scheduled/jobs-runtime.json` is synced to disk. A run started by a delivery fills the prompt's `{{body.path}}` placeholders from the stored body: single values only, each framed in a random `` tag, flattened to one line, with look-alike characters swapped in where a harness could read a `/skill`, `@file` or `$skill` mention, and capped (4 KiB each, 64 KiB in all), and kept in the run's thread history and records, not deleted with the stored body, with a note at the end that the tagged text is untrusted data; placeholders with no usable value are listed in the run record's `missingPlaceholders`. Headers and the secret are never available to a prompt (see `docs/CLI.md`). diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index 2f98db687c..987405757d 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -43,7 +43,7 @@ Use these terms in issues, PRs, comments, and docs. If you need a term that is n - **Continuation run:** a run of a thread that records a turn the provider started on its own, because background work finished and the provider wants to read the report. It opens with a short note and ends at the provider's result. - **Workflow:** a published sequence of steps that can run from chat (its slash command), the CLI, or an automation. - **Automation:** work that runs on its own. A trigger (a time, a request, a pull request's checks, reviews or comments, a `mousse-cli automation run` call, or Run now) starts a run: its Who (an agent, or one of the person's bots) does what it says in its project, usually on a thread of its own. A bot's schedules are automations with the bot as Who. **Tell me** sets the lowest report level that notifies, on an automation or on a bot for its unattended work reports and wake replies: Needs you, Worth a look (the default), FYI too or Every run; a failed run always does. The code calls an automation a scheduled job (`ScheduledJob`); the CLI is `mousse-cli automation`, with `schedule` as an alias. -- **Draft (automation):** an automation that is saved but never on and never runs, shown as a card with what each run is asked to do, When, Who, Project and May. A draft an agent wrote in a chat may do no more than that chat's mode. The Automation manager, a bot with the automation tools, or an agent in any chat (`automation_draft_save`) makes one. Turn on makes it the person's own automation, within their permissions; a bot allowed to "create and turn on automations" may turn on the drafts it wrote (`automation_enable`). Discard deletes it. The Inbox lists drafts under Drafts. +- **Draft (automation):** an automation that is saved but never on and never runs, shown as a card with what each run is asked to do, When, Who, Project and May. A draft an agent wrote in a chat may do no more than that chat's mode. The Automation manager, a bot with the automation tools, or an agent in any chat (`automation_draft_save`) makes one. Turn on makes it the person's own automation, within their permissions; an agent in a chat or the Automation manager may turn on a draft itself, no wider than its own mode, and a bot allowed to "create and turn on automations" may turn on the drafts it wrote (`automation_enable`). Discard deletes it. The Inbox lists drafts under Drafts. - **Automation manager:** the agent that turns what a person types in the Automations composer into a draft, asking a question first when it needs to. It is the default agent on one hidden thread per profile, reused for every request, and works in the project picked in the composer (or in a folder of its own). - **Inbox:** the Automations page: every run of every automation, in the Chats sidebar's place. Runs still going sit on top, then Needs you, Worth a look, FYI, and Quiet runs folded. A run opens beside the list as its own thread, under a strip with its level, its pull request, its usage, Too noisy, Should have told me and Resolve. Manage lists the automations themselves, to turn on or off, edit or delete. - **Needs you:** the Inbox's queue of what an automation is waiting on: a run that reported Needs you, a run that failed, and an approval or question on a run's thread. An item stays until it is resolved (Resolve, or answering the approval or question where it was asked); opening the run never resolves it. Items for an automation whose Who is a bot are assigned to that bot and folded under Assigned to bots. @@ -52,7 +52,7 @@ Use these terms in issues, PRs, comments, and docs. If you need a term that is n - **Bound secret:** a secret the owner gave a bot for one HTTPS service. Mousse keeps the value and adds it only to that service's fixed authentication header through a GET or HEAD read. Known services also fix the allowed path segments and version headers. Commands outside a sandbox can still read the owner's secret-store files. - **Space bot:** a bot a member adds to a Space, which answers in the Space's chat. Its code lives in `bots/space/`, apart from personal bots. - **Grant:** what a bot's owner approved: the tools the bot may use beyond what every bot has, and its limits. The bot works inside its grant without asking. Every bot also has, without a grant, the profiler, Mousse's look, scheduled jobs, secrets the owner gives and quick actions, and, unless switched off in About, every MCP server set up in Mousse, every skill and the automation tools. -- **Use your threads:** the bot permission, off by default, to read, search and act on its owner's reachable threads. Work and scheduled runs, their subagents, and chat turns started by creation, an owner message or tap, a wake, a question or a job may act under the grant. A turn from another bot's message is read-only. A thread it starts uses the target computer's default permission mode, capped by device limits. A message uses the target thread's mode. Answering an approval also requires the computer's “Agents may answer approvals on other threads” setting, except in a thread the bot started: there it answers that thread's own questions and approvals, whoever started the turn, and they don't ping the owner. Private threads and other bots' threads stay out of reach. The owner can switch the permission off in About. See `docs/bots.md`. +- **Use your threads:** the bot permission, off by default, to read, search and act on its owner's reachable threads. Work and scheduled runs, their subagents, and chat turns started by creation, an owner message or tap, a wake, a question or a job may act under the grant. A turn from another bot's message is read-only. A thread it starts uses the target computer's default permission mode, capped by device limits. A message uses the target thread's mode. It answers the questions and approvals of the threads it reaches, labelled as its own answers; in a thread it started, those requests don't ping the owner. Private threads and other bots' threads stay out of reach. The owner can switch the permission off in About. See `docs/bots.md`. - **Create and turn on automations:** the bot permission, off by default, to turn on automation drafts the bot wrote, or write one and turn it on at once (`automation_enable`), as if the owner pressed Turn on. Without it a bot only writes drafts. It is asked for like any tool, refused on a turn another bot's message started, and goes with the automation tools' switch in About. See `docs/bots.md`. - **Wall:** the point where a bot needs something its grant does not cover, such as another tool or more time, while its owner is chatting with it. Its dispatch ends, the bot's reply carries an ask, and the answer continues the turn. In a run, a missing permission is no wall: the call is refused and the run carries on. Work the owner asked for that runs out of time or turns posts what it has and waits for an ask for more, and Allow carries it on; a scheduled run that runs out ends, with an ask for more. - **Escalation:** a bot asking its owner for something outside its grant on its own initiative (the `escalate` tool). The owner answers it like any other ask. The code calls every ask an escalation (`bot_escalations`). diff --git a/src/mms/orchestrator/UserQuestionService.ts b/src/mms/orchestrator/UserQuestionService.ts index 66e91d7038..a82fb40843 100644 --- a/src/mms/orchestrator/UserQuestionService.ts +++ b/src/mms/orchestrator/UserQuestionService.ts @@ -28,8 +28,7 @@ import type { PendingApprovalInfo, PendingUserQuestions, UserQuestionAnswers, Us import { canAnswerApproval, type Answerer, - type ApprovalRefusal, - type LineageLookup + type ApprovalRefusal } from '../run/approvalRights' import { approvalFingerprint } from '../run/approvalFingerprint' import type { OpenQuestionCloseReason, OpenQuestionRecord, OpenQuestions } from '../run/OpenQuestions' @@ -187,20 +186,11 @@ export class UserQuestionService extends EventEmitter { private pending = new Map() private settledWaiters = new Map() private stopped = false - private lineage: LineageLookup = () => null private binding: ApprovalBinding | null = null private openStore: OpenQuestions | null = null /** True after this process started; plain questions never survive process death. */ readonly survivesDaemonRestart = false - /** - * Where `canAnswerApproval` finds a thread's parent. Without a source no agent may answer an - * approval: only the user can. - */ - setLineageSource(lookup: LineageLookup): void { - this.lineage = lookup - } - /** * Saves approval requests in `binding.store` from now on. `null` returns to plain in-memory * approvals. The service of a profile is bound once its Run Engine exists. @@ -455,8 +445,7 @@ export class UserQuestionService extends EventEmitter { const rights = canAnswerApproval( { threadId: pending.threadId, action: pending.approval.action, permissionKey: pending.approval.permissionKey, reason: pending.approval.reason }, answeredBy, - meaning, - this.lineage + meaning ) if (!rights.ok) return { ok: false, reason: rights.code } } @@ -611,8 +600,7 @@ export class UserQuestionService extends EventEmitter { const rights = canAnswerApproval( { threadId: pending.threadId, action: pending.approval.action, permissionKey: pending.approval.permissionKey, reason: pending.approval.reason }, answeredBy, - { decision: 'reject' }, - this.lineage + { decision: 'reject' } ) if (!rights.ok) return false } diff --git a/src/mms/protocol/validators.ts b/src/mms/protocol/validators.ts index 05424b58c7..57d5f5db05 100644 --- a/src/mms/protocol/validators.ts +++ b/src/mms/protocol/validators.ts @@ -1105,10 +1105,10 @@ function assertRunsPatch(value: unknown): void { function assertAgentAccessPatch(value: unknown): void { const patch = asPlainObject(value, 'partial.agentAccess') for (const key of Object.keys(patch)) { - // `level`, `projectIds` and `projectsUnreadable` are the removed access level's: an older client may still send them, and they are dropped. + // `level`, `projectIds`, `projectsUnreadable` (the removed access level's) and `answerApprovals` (the removed approvals switch): + // an older client may still send them, and they are dropped. if (key !== 'level' && key !== 'projectIds' && key !== 'projectsUnreadable' && key !== 'answerApprovals' && key !== 'remoteSubagents' && key !== 'computers' && key !== 'fromOtherDevices' && key !== 'computerUse' && key !== 'computerDriver') throw new Error(`partial.agentAccess.${key} is not allowed`) } - if (patch.answerApprovals !== undefined && typeof patch.answerApprovals !== 'boolean') throw new Error('partial.agentAccess.answerApprovals must be a boolean') if (patch.remoteSubagents !== undefined && typeof patch.remoteSubagents !== 'boolean') throw new Error('partial.agentAccess.remoteSubagents must be a boolean') if (patch.fromOtherDevices !== undefined && typeof patch.fromOtherDevices !== 'boolean') throw new Error('partial.agentAccess.fromOtherDevices must be a boolean') if (patch.computerUse !== undefined && typeof patch.computerUse !== 'boolean') throw new Error('partial.agentAccess.computerUse must be a boolean') diff --git a/src/mms/run/ThreadApprovals.ts b/src/mms/run/ThreadApprovals.ts index 7f5551bad6..1c9981810e 100644 --- a/src/mms/run/ThreadApprovals.ts +++ b/src/mms/run/ThreadApprovals.ts @@ -1,7 +1,7 @@ import { redactSecrets } from '../../shared/errors' import { isPermissionMode, isStricter, narrowPermissionMode, type PermissionAction, type PermissionMode } from '../../shared/permissionMode' import type { UserQuestionAnswers } from '../../shared/types' -import { canAnswerApproval, type Answerer, type ApprovalRefusal, type LineageLookup } from './approvalRights' +import { canAnswerApproval, type Answerer, type ApprovalRefusal } from './approvalRights' import { int, json, str, type Row } from './db/rows' import type { EffectOutbox } from './EffectOutbox' import { stableStringify } from './json' @@ -283,7 +283,7 @@ export function cancelApprovalRows(store: RunStore, where: string, params: Array export class ThreadApprovals { constructor( private readonly store: RunStore, - private readonly deps: { outbox: EffectOutbox; lineage: LineageLookup } + private readonly deps: { outbox: EffectOutbox } ) {} /** Saves a new request (`pending`) and records `approval.pending`. */ @@ -395,7 +395,7 @@ export class ThreadApprovals { return { ok: false, reason: 'already_answered', ...(row.answeredBy ? { answeredBy: row.answeredBy } : {}), ...(row.decision ? { decision: row.decision } : {}) } if (row.status === 'cancelled') return { ok: false, reason: 'cancelled', ...(row.cancelReason ? { cancelReason: row.cancelReason } : {}) } const meaning = meaningOf(row.questions, answers) - const rights = canAnswerApproval({ threadId: row.threadId, action: row.action, permissionKey: row.permissionKey, reason: row.reason }, answeredBy, meaning, this.deps.lineage) + const rights = canAnswerApproval({ threadId: row.threadId, action: row.action, permissionKey: row.permissionKey, reason: row.reason }, answeredBy, meaning) if (!rights.ok) return { ok: false, reason: rights.code } const always = meaning.decision === 'allow' && meaning.scope === 'always' const once = always ? onceAllowOption(row.questions) : undefined @@ -589,7 +589,7 @@ export class ThreadApprovals { return this.db.transaction(() => { const pending = this.listPending(threadId) for (const row of pending) { - const rights = canAnswerApproval({ threadId: row.threadId, action: row.action, permissionKey: row.permissionKey, reason: row.reason }, send.answeredBy, { decision: 'reject' }, this.deps.lineage) + const rights = canAnswerApproval({ threadId: row.threadId, action: row.action, permissionKey: row.permissionKey, reason: row.reason }, send.answeredBy, { decision: 'reject' }) if (!rights.ok) return { refused: true } } const denied: string[] = [] diff --git a/src/mms/run/approvalRights.ts b/src/mms/run/approvalRights.ts index b0e3bc9ecd..32a2890c9b 100644 --- a/src/mms/run/approvalRights.ts +++ b/src/mms/run/approvalRights.ts @@ -1,5 +1,4 @@ import { permissionModeAllows, type PermissionAction, type PermissionMode } from '../../shared/permissionMode' -import type { LineageRecord } from './types' /** * Who may answer an approval request. One rule for every way in: the GUI, the CLI, Bridge clients, @@ -7,20 +6,6 @@ import type { LineageRecord } from './types' * approval is settled (`UserQuestionService.submitAnswers`), never in a client. */ -/** - * What the profile lets an agent do beyond its own subagents, as it is at the moment the agent answers - * (`approval_respond`). Absent for every other way an agent answers: those reach the agent's own subagents only. - */ -export interface AgentApprovalAccess { - /** The profile's switch "Agents may answer approvals on other threads" (off by default). */ - answerApprovals: boolean - /** - * The answerer is the personal bot that started the request's thread, answering that thread's own request, whoever - * started the turn (`OrchestratorService.supervisorOf`): it needs no switch. Every other part of the rule still holds. - */ - startedThread?: boolean -} - export type Answerer = /** * The user, through one of their clients. `via: 'bridge'` with a `node` is the user at another of @@ -29,11 +14,10 @@ export type Answerer = */ | { kind: 'user'; via?: 'gui' | 'cli' | 'bridge' | 'internal'; node?: string; maxPermissionMode?: PermissionMode } /** - * An agent, acting within its own run's permission mode. It answers for its own subagent, and for a thread - * outside its lineage only when `access` says the profile allows it. `toolCallId` is the call that answers, - * kept with the answer so a retry of that call is told from another caller's. + * An agent, acting within its own run's permission mode, for any thread but its own. `toolCallId` is the call that + * answers, kept with the answer so a retry of that call is told from another caller's. */ - | { kind: 'agent'; threadId: string; runId: string; permissionMode: PermissionMode; toolCallId?: string; access?: AgentApprovalAccess } + | { kind: 'agent'; threadId: string; runId: string; permissionMode: PermissionMode; toolCallId?: string } /** What an approval is about: the thread that asked and the kind of action it asks to take. */ export interface ApprovalSubject { @@ -57,9 +41,6 @@ export interface ApprovalAnswer { export type ApprovalRefusal = | 'own_request' | 'person_only' - | 'person_turn' - | 'not_parent' - | 'approvals_disabled' | 'mode_forbids' | 'agent_no_standing_grant' | 'bridge_no_standing_grant' @@ -84,41 +65,15 @@ export function startedByPerson(run: { origin: string; source: string | null | u export type ApprovalRights = { ok: true } | { ok: false; code: ApprovalRefusal } -/** Looks up the lineage of a thread (a subagent's parent), or null for a thread without one. */ -export type LineageLookup = (threadId: string) => Pick | null - -/** Lineage walks stop here; a deeper chain is treated as no relation, which only ever refuses more. */ -const LINEAGE_MAX_DEPTH = 64 - -/** The threads above `threadId` in the lineage, nearest first. */ -function ancestorsOf(threadId: string, lineage: LineageLookup): string[] { - const out: string[] = [] - let current = threadId - for (let depth = 0; depth < LINEAGE_MAX_DEPTH; depth += 1) { - const link = lineage(current) - if (!link || out.includes(link.parentThreadId)) break - out.push(link.parentThreadId) - current = link.parentThreadId - } - return out -} - /** - * The user may always answer. An agent may answer only for an action its own permission mode allows - * without asking, never for its own request, and never with a standing rule ("always"): only a user - * creates one. Whose requests it may answer: - * - its own direct subagent's; - * - any other thread's, only when its access (`approval_respond`) is `manage`, the profile's switch for - * answering approvals is on (or the answerer is the bot that started that thread, `startedThread`) and the - * thread's project is one agents may reach. A thread of its own - * lineage (a subagent of a subagent, its parent or an ancestor) is never one of those: a subagent - * answers nothing above it, and only the direct parent answers for a child. + * The user may always answer. An agent may answer any thread's request but its own, only for an action its own + * permission mode allows without asking, never one the provider keeps for a person (`reason`), and never with a + * standing rule ("always"): only a user creates one, since it outlives the turn. */ export function canAnswerApproval( request: ApprovalSubject, answerer: Answerer, - answer: ApprovalAnswer, - lineage: LineageLookup + answer: ApprovalAnswer ): ApprovalRights { if (answerer.kind === 'user') { if (answerer.via === 'bridge' && answer.decision === 'allow' && answer.scope === 'always') { @@ -135,20 +90,6 @@ export function canAnswerApproval( // A request Claude Code (or the provider) will not let anything but a person answer, in any mode: no agent answers it, // not even the parent of the subagent that asked. This is the set a standing rule never answers either. if (request.reason) return { ok: false, code: 'person_only' } - const link = lineage(request.threadId) - const ownSubagent = link !== null && link.parentThreadId === answerer.threadId && link.relationship === 'subagent' - if (!ownSubagent) { - const access = answerer.access - if (!access) return { ok: false, code: 'not_parent' } - // A subagent is answered by its parent alone. Nothing in the answerer's own lineage is answered through the access - // branch: not below it, not above it, and not beside it (a sibling or cousin shares an ancestor with it). - if (link !== null && link.relationship === 'subagent') return { ok: false, code: 'not_parent' } - const above = ancestorsOf(request.threadId, lineage) - const mine = ancestorsOf(answerer.threadId, lineage) - if (above.includes(answerer.threadId) || mine.includes(request.threadId) || above.some((id) => mine.includes(id))) - return { ok: false, code: 'not_parent' } - if (!access.answerApprovals && !access.startedThread) return { ok: false, code: 'approvals_disabled' } - } if (!permissionModeAllows(answerer.permissionMode, request.action)) return { ok: false, code: 'mode_forbids' } if (answer.decision === 'allow' && answer.scope === 'always') return { ok: false, code: 'agent_no_standing_grant' } return { ok: true } @@ -159,10 +100,7 @@ export function describeApprovalRefusal(code: ApprovalRefusal): string { switch (code) { case 'own_request': return 'An agent cannot answer its own approval request; the user does.' case 'person_only': return 'The provider asks for this itself (its own safety check, a path outside the allowed folders, or a rule the user made), so only the user can answer it.' - case 'person_turn': return 'The user started the turn that asks, so the user answers it. Agents answer for turns that agents, jobs or subagents started.' - case 'not_parent': return 'Only the parent of a subagent can answer its approval requests.' - case 'approvals_disabled': return 'The user has not allowed agents to answer approvals on other threads (Settings > Agents). Ask the user to answer it.' - case 'mode_forbids': return 'Your permission mode would ask the user before this kind of action, so you cannot approve it for your subagent. Ask the user to answer it.' + case 'mode_forbids': return 'Your permission mode would ask the user before this kind of action, so you cannot approve it. Ask the user to answer it.' case 'agent_no_standing_grant': return 'Only the user can approve an action for the whole thread. Approve it once, or ask the user.' case 'bridge_no_standing_grant': return 'A linked device can allow a request once. "Always for this thread" is made in the app or the CLI, where the rule can be seen and revoked.' case 'device_mode_forbids': return 'The computer that runs this thread lets this device allow this request once, but not for the whole thread: its permission limit would ask about this kind of action. Raise the limit for this device on that computer, in Settings, Devices, or answer in the app there.' diff --git a/src/mms/run/mcp/appTools/requestAnswer.ts b/src/mms/run/mcp/appTools/requestAnswer.ts index e3ca0ad957..d7df763df0 100644 --- a/src/mms/run/mcp/appTools/requestAnswer.ts +++ b/src/mms/run/mcp/appTools/requestAnswer.ts @@ -23,8 +23,8 @@ export const REQUEST_ANSWER_KINDS: Readonly Agents > Access and Subagents: whether agents may answer approvals on other threads, then whether they - * may work on the user's other devices ("Let agents work on your other devices", stored as `remoteSubagents`), on which of + * Settings > Agents > Subagents: whether agents may work on the user's other devices ("Let agents work on your other devices", stored as `remoteSubagents`), on which of * them, and whether threads another device started here may too ("Threads started from other devices", * `fromOtherDevices`). All read and write the one stored `agentAccess` setting. Agents read and * manage every thread; there is no level to choose (SPEC §15.1). @@ -31,7 +30,7 @@ export function AgentAccessSettings({ const toggleComputer = (node: string) => save({ computers: access.computers.includes(node) ? access.computers.filter((entry) => entry !== node) : [...access.computers, node] }) - // Always the whole setting: a partial write must not drop the approvals switch or the computer list. + // Always the whole setting: a partial write must not drop the computer list. const save = (next: Partial) => void updateSettings({ agentAccess: { ...access, ...next } }) // A computer removed from the user's devices leaves the allowed list on its own. @@ -60,30 +59,6 @@ export function AgentAccessSettings({ return ( <> - - - Use with care. Agents approve what other threads ask for, within their own permission mode. - - An agent can approve a command, a file change or a tool that another thread asked to run, without you seeing the request - first. It can approve only what its own permission mode would allow without asking, never “Always for this - thread”, and never its own thread. Each answer shows in that thread as approved by an agent. Requests the provider - asks for itself (such as Claude Code’s own safety check) and turns you started yourself stay yours. Off by default. - - } - control={ - save({ answerApprovals })} - /> - } - /> -