diff --git a/apps/server/src/builder/controller-kit/mount.ts b/apps/server/src/builder/controller-kit/mount.ts index d697176c8..327618ffa 100644 --- a/apps/server/src/builder/controller-kit/mount.ts +++ b/apps/server/src/builder/controller-kit/mount.ts @@ -1,6 +1,7 @@ import type { AgentConfig, AgentInstructions, ToolsInput } from '@mastra/core/agent' import { Agent } from '@mastra/core/agent' import type { AgentController } from '@mastra/core/agent-controller' +import { createCodingAgent } from '@mastra/core/coding-agent' import type { RequestContext } from '@mastra/core/request-context' import type { MastraCompositeStore } from '@mastra/core/storage' import type { QueueDeps } from '../model-accounts/public.ts' @@ -51,6 +52,7 @@ function instructionsOf(prompt: Prompt): AgentConfig['instructions'] { switch (prompt.kind) { case 'MESSAGES': return ({ requestContext }) => messagesOf(prompt.parts, requestContext) + case 'ONE_STRING': case 'DELEGATED': return ({ requestContext }) => prompt.of(requestContext) default: @@ -119,7 +121,7 @@ async function toolsOfSpec(spec: AgentSpec, requestContext: RequestContext): Pro } /** The session's starting state of a regime: `NOTHING_ASKS` is `{ yolo: true }`, `THE_WRITE_ASKS` `{ yolo: false }`; one owner of the `yolo` (C26). */ -function initialStateOf(approval: Approval): Readonly<{ yolo: boolean }> { +export function initialStateOf(approval: Approval): Readonly<{ yolo: boolean }> { switch (approval.kind) { case 'NOTHING_ASKS': return { yolo: true } @@ -130,17 +132,30 @@ function initialStateOf(approval: Approval): Readonly<{ yolo: boolean }> { } } +/** `createCodingAgent` reads a missing `workspace` key as a local machine (`NM/coding-agent/index.js:221`); the ficha never gives one, so the key is always there, `undefined`. */ +function agentOfBase(base: AgentSpec['base'], config: AgentConfig): Agent { + switch (base) { + case 'AGENT': + return new Agent(config) + case 'CODING_AGENT': + return createCodingAgent({ ...config, workspace: undefined }) + default: + return base satisfies never + } +} + /** * The one place that calls Mastra's agent constructor for the agents on a ficha, with the turn's - * processor made from `spec.turn`, the tools under the ficha's regime, and only the optional fields - * the ficha fills. `watch` comes with a `SESSION` turn (`sessionTurns`): `mountAgent` calls it with - * the controller; a `RUN` turn has none, the agent runs alone. + * processor made from `spec.turn`, the tools under the ficha's regime, the judge as the default + * `isTaskComplete`, and only the optional fields the ficha fills. `watch` comes with a `SESSION` + * turn (`sessionTurns`): `mountAgent` calls it with the controller; a `RUN` turn has none. */ export function agentOfSpec( spec: AgentSpec, deps: { queue: QueueDeps }, ): Readonly<{ agent: Agent; watch?: (controller: AgentController) => void }> { const turns = turnsOf(spec.turn) + const defaults = agentDefaults(deps.queue, turns, spec.processors) const config: AgentConfig = { id: spec.id, name: spec.name, @@ -148,18 +163,19 @@ export function agentOfSpec( instructions: instructionsOf(spec.prompt), model: modelOf(spec.model), tools: ({ requestContext }) => toolsOfSpec(spec, requestContext), - ...agentDefaults(deps.queue, turns, spec.processors), + ...defaults, + ...(spec.judge === undefined + ? {} + : { defaultOptions: { ...defaults.defaultOptions, isTaskComplete: spec.judge } }), memory: spec.memory, ...(spec.skills === undefined ? {} : { skills: spec.skills }), ...(spec.signals === undefined ? {} : { signals: spec.signals }), ...(spec.scopes === undefined ? {} : { scopes: spec.scopes }), ...(spec.knowledge === undefined ? {} : { knowledge: spec.knowledge }), } - switch (spec.base) { - case 'AGENT': - return { agent: new Agent(config), ...('watch' in turns ? { watch: turns.watch } : {}) } - default: - return spec.base satisfies never + return { + agent: agentOfBase(spec.base, config), + ...('watch' in turns ? { watch: turns.watch } : {}), } } diff --git a/apps/server/src/builder/controller-kit/public.ts b/apps/server/src/builder/controller-kit/public.ts index 5c15a8fb0..a71ff398c 100644 --- a/apps/server/src/builder/controller-kit/public.ts +++ b/apps/server/src/builder/controller-kit/public.ts @@ -1,12 +1,12 @@ export { admitAsker, agentManagerAdmission } from './admission.ts' export { ASK_USER_TOOL, createAskUserTool } from './ask-user.ts' -export { agentDefaults, CONVERSATION_MODE, controllerOf, MODEL_TIMEOUT } from './factories.ts' +export { CONVERSATION_MODE, MODEL_TIMEOUT } from './factories.ts' export { CONEXUS_PROMPT, TITLE } from './instructions.ts' export type { ControllerKind, Owner } from './kinds.ts' export { CONTROLLER_KINDS, ownerOfResource, resourceOf } from './kinds.ts' export { conversationMemory, ownerIn, turnOfOwner } from './memory.ts' export { BR_LOCATION, routedModel, sessionModel, toolsOf } from './model.ts' -export { agentOfSpec, mountAgent, NEVER_ASKS } from './mount.ts' +export { agentOfSpec, initialStateOf, mountAgent, NEVER_ASKS } from './mount.ts' export { oncePerRun } from './once.ts' export type { Kept } from './open.ts' export { attemptIdOf, changeModel, openSession } from './open.ts' @@ -17,7 +17,7 @@ export { dataContextOf, markIn, marksOf, principalOf, RUN_MARKS, runResolver } f export { skillOf } from './skills.ts' export type { Mays, Speakers } from './speakers.ts' export { blockOf, turnDate } from './speakers.ts' -export type { AgentSpec, ConversationSpec } from './spec.ts' +export type { AgentSpec, ConversationSpec, TurnSource } from './spec.ts' export { listOwned, ownThread } from './thread.ts' export type { Taken } from './turns.ts' -export { takeOfScope, turnKeyOn, turnProcessor } from './turns.ts' +export { takeOfScope, turnKeyOn } from './turns.ts' diff --git a/apps/server/src/builder/controller-kit/spec.test.ts b/apps/server/src/builder/controller-kit/spec.test.ts index 56c8e9b86..c04492fa0 100644 --- a/apps/server/src/builder/controller-kit/spec.test.ts +++ b/apps/server/src/builder/controller-kit/spec.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict' import type { TestContext } from 'node:test' import { test } from 'node:test' import { ModelId } from '@conexus/hub-api' +import type { Agent, StreamIsTaskCompleteConfig } from '@mastra/core/agent' import { Knowledge } from '@mastra/core/knowledge' import type { InputProcessor } from '@mastra/core/processors' import { RequestContext } from '@mastra/core/request-context' @@ -257,3 +258,61 @@ test('o turno RUN da ficha leva o id dela e só retoma no primeiro passo se a fi assert.equal('processInputStep' in (await processorOf(false)), false) assert.equal('processInputStep' in (await processorOf(true)), true) }) + +test('a ficha de código dá um agente sem máquina própria: sem a chave, o Mastra poria a local no servidor do Hub', async (t) => { + const { mount } = await mounting(t) + assert.equal(await mount().agent.getWorkspace(), undefined) + const coding = mount({ base: 'CODING_AGENT' }).agent + assert.equal(await coding.getWorkspace(), undefined) + // Only `createCodingAgent` adds the task list's signal, and only with memory. + assert.deepEqual(mount().agent.listSignalProviders(), []) + assert.equal(coding.listSignalProviders().length, 1) +}) + +test('as instruções de uma string só chegam ao agente como a ficha as dá, e a ficha vê o run', async (t) => { + const { mount } = await mounting(t) + const requestContext = new RequestContext() + requestContext.set('lido', 'do run') + const { agent } = mount({ + prompt: { + kind: 'ONE_STRING', + of: async (context) => `Uma só, ${String(context.get('lido'))}.`, + }, + }) + assert.equal(await agent.getInstructions({ requestContext }), 'Uma só, do run.') +}) + +test('a ficha sem juiz dá um agente sem isTaskComplete; com um, ele é o padrão do agente e os outros padrões ficam', async (t) => { + const { mount } = await mounting(t) + const requestContext = new RequestContext() + const without = await mount().agent.getDefaultOptions({ requestContext }) + assert.equal('isTaskComplete' in without, false) + const judge: StreamIsTaskCompleteConfig = { scorers: [], strategy: 'all' } + const judged = await mount({ judge }).agent.getDefaultOptions({ requestContext }) + assert.equal(judged.isTaskComplete, judge) + assert.deepEqual(judged.toolCallConcurrency, without.toolCallConcurrency) + assert.deepEqual(judged.modelSettings, without.modelSettings) +}) + +test('uma conversa com o turno RUN leva o processador do turno e nenhum que depende da sessão', async (t) => { + const { mount } = await mounting(t) + const turn = { + kind: 'RUN', + id: 'conexus-spec-run', + none: 'SEM_VEZ', + resumes: true, + take: async () => ({ kind: 'NONE' }) satisfies Taken, + } as const + const { agent } = mount({ turn }) + const listed = await agent.listConfiguredInputProcessors(new RequestContext()) + assert.deepEqual( + listed.map((each) => ('id' in each ? each.id : undefined)), + ['conexus-spec-run', 'conexus-account-pick'], + ) + async function deletedRunsOf(agent: Agent) { + const output = await agent.listConfiguredOutputProcessors(new RequestContext()) + return output.flatMap((each) => ('id' in each && each.id.endsWith('-deleted') ? [each.id] : [])) + } + assert.deepEqual(await deletedRunsOf(agent), []) + assert.deepEqual(await deletedRunsOf(mount().agent), ['conexus-spec-turn-deleted']) +}) diff --git a/apps/server/src/builder/controller-kit/spec.ts b/apps/server/src/builder/controller-kit/spec.ts index 8de5a83f2..b29553138 100644 --- a/apps/server/src/builder/controller-kit/spec.ts +++ b/apps/server/src/builder/controller-kit/spec.ts @@ -1,4 +1,9 @@ -import type { AgentConfig, AgentInstructions, ToolsInput } from '@mastra/core/agent' +import type { + AgentConfig, + AgentInstructions, + StreamIsTaskCompleteConfig, + ToolsInput, +} from '@mastra/core/agent' import type { MastraMemory } from '@mastra/core/memory' import type { InputProcessor } from '@mastra/core/processors' import type { RequestContext } from '@mastra/core/request-context' @@ -20,11 +25,13 @@ export type PromptPart = }> /** - * An agent's instructions (row 5): system messages in order, or, for the agent of a conversation - * that delegates (row 21), the instructions of the agent the run names. + * An agent's instructions (row 5): system messages in order; one string, as the Builder's are; or, + * for the agent of a conversation that delegates (row 21), the instructions of the agent the run + * names. */ export type Prompt = | Readonly<{ kind: 'MESSAGES'; parts: readonly PromptPart[] }> + | Readonly<{ kind: 'ONE_STRING'; of: (requestContext: RequestContext) => Promise }> | Readonly<{ kind: 'DELEGATED' of: (requestContext: RequestContext) => Promise @@ -52,8 +59,9 @@ type SessionTurn = Readonly<{ }> /** - * ...or by the run alone, with no session to hold it: an agent that runs on its own (the version - * the Construtor tests) takes its turn at the input and ends it with the call. + * ...or by the run alone, with no session to hold it: the agent that runs on its own (the version + * the Construtor tests) and the Builder, whose run frees the Projeto itself (`onEnd`), take their + * turn at the input and do not end it by session. */ type RunTurn = Readonly<{ kind: 'RUN' @@ -76,7 +84,8 @@ export type AgentSpec = Readonly<{ id: string name: string description?: string - base: 'AGENT' + /** `CODING_AGENT` is Mastra's `createCodingAgent`, made with no workspace of its own. */ + base: 'AGENT' | 'CODING_AGENT' prompt: Prompt model: ModelSource tools: (requestContext: RequestContext) => Promise @@ -88,15 +97,16 @@ export type AgentSpec = Readonly<{ signals?: AgentConfig['signals'] scopes?: AgentConfig['scopes'] knowledge?: AgentConfig['knowledge'] + /** How a turn ends (row 11): Mastra's `isTaskComplete` scores it, and a score of 0 sends the reason back to the model. */ + judge?: StreamIsTaskCompleteConfig }> type ControllerInput = Parameters[0] /** A conversation's agent and its controller: the id is `CONTROLLER_KINDS[kind].id`, never the ficha's. */ -export type ConversationSpec = Omit & +export type ConversationSpec = Omit & Readonly<{ kind: ControllerKind - turn: SessionTurn /** The controller's memory, where its threads live, and the agent's unless `memory` says another. */ threads: MastraMemory /** The agent's own memory, when it is not the threads': the one a run's version keeps. */ diff --git a/apps/server/src/builder/conversation/builder.ts b/apps/server/src/builder/conversation/builder.ts index f8f8f2d0f..871bf577e 100644 --- a/apps/server/src/builder/conversation/builder.ts +++ b/apps/server/src/builder/conversation/builder.ts @@ -1,6 +1,5 @@ import type { CompanyData, CompanyId, PersonId, ProjectId } from '@conexus/hub-api' -import { BUILDER_CONTROLLER, BUILDER_TOOL } from '@conexus/hub-api' -import { createCodingAgent } from '@mastra/core/coding-agent' +import { BUILDER_TOOL } from '@conexus/hub-api' import type { RequestContext } from '@mastra/core/request-context' import type { MastraCompositeStore } from '@mastra/core/storage' import { webFetchTool } from '@mastra/core/tools' @@ -17,12 +16,11 @@ import { builderAccess } from '../connectors/public.ts' import type { DataBinding, RunScope } from '../controller-kit/public.ts' import { ASK_USER_TOOL, - agentDefaults, CONVERSATION_MODE, - controllerOf, conversationMemory, createAskUserTool, dataContextOf, + mountAgent, oncePerRun, principalOf, sessionModel, @@ -127,9 +125,9 @@ const BUILDER_MEMORY = { ...TITLE.app, recall: 'thread' } as const /** * The Builder (decision 0050): one agent shared by every conversation, its keyless model taken * from the session and given its account by the queue's processors, its memory, its title and its - * observation through the same account, in Mastra's own database. It is Mastra Code's agent - * (`sdk/src/index.ts:1216-1223`): no workspace of its own, since the controller lends the turn's - * machine, and the task list's signal with `memory`. + * observation through the same account, in Mastra's own database. It is made from its ficha: Mastra + * Code's agent (`sdk/src/index.ts:1216-1223`) with no workspace of its own, since the controller + * lends the turn's machine, and the task list's signal with `memory`. */ export function createBuilder(deps: { storage: MastraCompositeStore @@ -162,59 +160,56 @@ export function createBuilder(deps: { const scope = await scopeOf(requestContext) return scope === undefined ? [] : companyConnections(scope) } - const defaults = agentDefaults(queue, { processor: turnOf(deps) }) - const agent = createCodingAgent({ - id: BUILDER_CONTROLLER, - name: 'Builder', - instructions: builderInstructions({ - runs: deps.runs, - projectOf, - projectName: deps.projectName, - granted, - data: dataFor(deps.copies, projectOf), - }), - skills: async ({ requestContext }) => [ - ...APP_SKILLS, - ...(await granted(requestContext)).map((each) => - skillOf({ directory: each.skill.name, ...each.skill }), - ), - ], - model: ({ requestContext }) => sessionModel(requestContext), - tools: async ({ requestContext }) => { - const scope = await scopeOf(requestContext) - // The order of step 20 (criterion 13a): the model's request stays byte for byte the same. - return { - web_fetch: webFetchTool, - [BUILDER_TOOL.check]: check, - ...toolsOf(sessionModel(requestContext)), - ...(scope === undefined ? {} : await companyTools(scope, 'builder', tools)), - } - }, - ...defaults, - workspace: undefined, - defaultOptions: { - ...defaults.defaultOptions, - isTaskComplete: { + const instructions = builderInstructions({ + runs: deps.runs, + projectOf, + projectName: deps.projectName, + granted, + data: dataFor(deps.copies, projectOf), + }) + const { agent, controller } = mountAgent( + { + kind: 'builder', + name: 'Builder', + base: 'CODING_AGENT', + prompt: { kind: 'ONE_STRING', of: (requestContext) => instructions({ requestContext }) }, + skills: async ({ requestContext }) => [ + ...APP_SKILLS, + ...(await granted(requestContext)).map((each) => + skillOf({ directory: each.skill.name, ...each.skill }), + ), + ], + model: { kind: 'SESSION' }, + tools: async (requestContext) => { + const scope = await scopeOf(requestContext) + // The order of step 20 (criterion 13a): the model's request stays byte for byte the same. + return { + web_fetch: webFetchTool, + [BUILDER_TOOL.check]: check, + ...toolsOf(sessionModel(requestContext)), + ...(scope === undefined ? {} : await companyTools(scope, 'builder', tools)), + } + }, + approval: { kind: 'NOTHING_ASKS' }, + judge: { scorers: [conexusCheck({ runs: deps.runs, storage })], strategy: 'all', }, + turn: turnOf(deps), + threads: memory, + mode: { id: CONVERSATION_MODE, availableTools: TOOL_CLOSURE.availableTools }, + // `ask_user` and `submit_plan` are ours, under the native ids (`plan-tools.ts`). + own: { + fixed: { [ASK_USER_TOOL]: createAskUserTool(), [SUBMIT_PLAN_TOOL]: createSubmitPlanTool() }, + }, + // The conversation's machine (Factory `session-sandbox.ts:29-36`); none outside a conversation. + workspace: async ({ requestContext, mastra }) => { + const ids = await projectOf(requestContext) + return ids === undefined ? undefined : deps.runs.workspaceOf(ids, mastra) + }, }, - memory, - }) - const controller = controllerOf({ - ...{ kind: 'builder', storage, memory, agent }, - mode: { id: CONVERSATION_MODE, availableTools: TOOL_CLOSURE.availableTools }, - // The conversation's machine (Factory `session-sandbox.ts:29-36`); none outside a conversation. - workspace: async ({ requestContext, mastra }) => { - const ids = await projectOf(requestContext) - return ids === undefined ? undefined : deps.runs.workspaceOf(ids, mastra) - }, - // `ask_user` and `submit_plan` are ours, under the native ids (`plan-tools.ts`). - tools: { - fixed: { [ASK_USER_TOOL]: createAskUserTool(), [SUBMIT_PLAN_TOOL]: createSubmitPlanTool() }, - }, - initialState: TOOL_CLOSURE.initialState, - }) + { queue, storage }, + ) return { controller, memory, agent, queue: deps.queue } } diff --git a/apps/server/src/builder/conversation/permissions.test.ts b/apps/server/src/builder/conversation/permissions.test.ts index 0b1504701..3652fecae 100644 --- a/apps/server/src/builder/conversation/permissions.test.ts +++ b/apps/server/src/builder/conversation/permissions.test.ts @@ -9,6 +9,7 @@ import { createTool } from '@mastra/core/tools' import { MockLanguageModelV3 } from 'ai/test' import { z } from 'zod' import type { Reply, Sent } from '../../platform/test-anthropic.ts' +import { initialStateOf } from '../controller-kit/public.ts' import { accountPick, callModel, Turn, turnContext } from '../model-accounts/public.ts' import { TOOL_CLOSURE } from './public.ts' import { asked, conversing, endOf, MODEL, title } from './test-conversation.ts' @@ -159,7 +160,7 @@ async function closedSession(ran: string[]) { tools: { github_create_issue: outside }, }), modes: [{ id: 'conversa', availableTools: TOOL_CLOSURE.availableTools }], - initialState: TOOL_CLOSURE.initialState, + initialState: initialStateOf({ kind: 'NOTHING_ASKS' }), }) await controller.init() return controller.createSession() diff --git a/apps/server/src/builder/conversation/permissions.ts b/apps/server/src/builder/conversation/permissions.ts index 2b031553f..c8a4657c8 100644 --- a/apps/server/src/builder/conversation/permissions.ts +++ b/apps/server/src/builder/conversation/permissions.ts @@ -57,11 +57,10 @@ const EXECUTE = new Set([ * How the Builder's controller closes its tools, the one owner of the closed set, as Mastra Code * closes its own (`mastracode/sdk/src/index.ts:858,1331`): the mode offers the four groups and no * other tool (`availableTools`, which the controller enforces when a tool is called), a session - * starts in `yolo` so nothing waits to be approved (decision 0053), and the controller's own - * tools are off (`disableBuiltinTools`). The account queue narrows the set the mode offers and - * never rebuilds it. + * starts in `yolo` so nothing waits to be approved (decision 0053; the ficha's regime + * `NOTHING_ASKS` writes it), and the controller's own tools are off (`disableBuiltinTools`). The + * account queue narrows the set the mode offers and never rebuilds it. */ export const TOOL_CLOSURE = { availableTools: [...READ, ...EDIT, ...EXECUTE, ...TALK], - initialState: { yolo: true }, } diff --git a/apps/server/src/builder/conversation/turn-of.ts b/apps/server/src/builder/conversation/turn-of.ts index a8b76bed7..6c17fd7a1 100644 --- a/apps/server/src/builder/conversation/turn-of.ts +++ b/apps/server/src/builder/conversation/turn-of.ts @@ -1,9 +1,8 @@ import type { ConversationId, ProjectId } from '@conexus/hub-api' -import type { InputProcessor } from '@mastra/core/processors' import type { RequestContext } from '@mastra/core/request-context' import type { Memory } from '@mastra/memory' -import type { Owner, RunScope, Taken } from '../controller-kit/public.ts' -import { ownerIn, runResolver, turnOfOwner, turnProcessor } from '../controller-kit/public.ts' +import type { Owner, RunScope, Taken, TurnSource } from '../controller-kit/public.ts' +import { ownerIn, runResolver, turnOfOwner } from '../controller-kit/public.ts' import type { QueueDeps } from '../model-accounts/public.ts' import type { Runs } from '../runs/public.ts' import { conversationIn } from '../runs/public.ts' @@ -50,22 +49,24 @@ function projectTurn(deps: { } /** - * The run's turn, made as Mastra's run reads its input, from the conversation the run is (Factory - * `credential-policy.ts:31-90`), never from the request that woke it: the run takes the Projeto, - * or ends refused with whose run holds it, before any model call and with nothing saved. A run - * Mastra resumes (an answered card) reads no input: its first step takes the turn instead. + * The Builder's turn as its ficha holds it (`turn`): the run's, made as Mastra's run reads its + * input, from the conversation the run is (Factory `credential-policy.ts:31-90`), never from the + * request that woke it. `projectTurn` is the step: the run takes the Projeto, or ends refused with + * whose run holds it, before any model call and with nothing saved. A run Mastra resumes (an + * answered card) reads no input: its first step takes the turn instead. */ export function turnOf(deps: { queue: QueueDeps runs: Pick index: ConversationIndex -}): InputProcessor { - return turnProcessor({ +}): TurnSource { + return { + kind: 'RUN', id: TURN_PROCESSOR, none: 'CONVERSATION_NOT_FOUND', resumes: true, take: projectTurn(deps), - }) + } } /** The Builder's run: its Projeto from the Hub's index, every connection the Projeto received. */