From 3814ce7a513fa843bca9cc0a7f05235c4800d004 Mon Sep 17 00:00:00 2001 From: reviewer Date: Mon, 23 Nov 2026 12:17:49 +0000 Subject: [PATCH 1/2] refactor(harness): U5 o Assistente na ficha --- .../server/src/builder/assistant/assistant.ts | 270 +++++++++--------- .../src/builder/assistant/available-tools.ts | 39 +++ .../src/builder/assistant/instructions.ts | 51 +--- apps/server/src/builder/assistant/turn.ts | 19 +- .../src/builder/controller-kit/factories.ts | 16 +- .../src/builder/controller-kit/mount.ts | 19 +- .../src/builder/controller-kit/public.ts | 4 +- .../src/builder/controller-kit/spec.test.ts | 46 +++ .../server/src/builder/controller-kit/spec.ts | 12 + 9 files changed, 276 insertions(+), 200 deletions(-) create mode 100644 apps/server/src/builder/assistant/available-tools.ts diff --git a/apps/server/src/builder/assistant/assistant.ts b/apps/server/src/builder/assistant/assistant.ts index f833f47e5..0fb0b688b 100644 --- a/apps/server/src/builder/assistant/assistant.ts +++ b/apps/server/src/builder/assistant/assistant.ts @@ -1,7 +1,6 @@ import { readFileSync } from 'node:fs' import type { CompanyData, CompanyId, ConversationId, Person } from '@conexus/hub-api' import { - ASSISTANT_CONTROLLER, ASSISTANT_TOOL, BUILDER_TOOL, DATA_TOOL, @@ -10,7 +9,6 @@ import { TASK_TOOLS, WORKSPACE_TOOL, } from '@conexus/hub-api' -import { Agent } from '@mastra/core/agent' import type { RequestContext } from '@mastra/core/request-context' import { TaskSignalProvider } from '@mastra/core/signals' import type { MastraCompositeStore } from '@mastra/core/storage' @@ -20,6 +18,7 @@ import type { Connectors } from '../../hub/connectors/public.ts' import type { IdentityPorts } from '../../hub/identity/public.ts' import type { Database } from '../../platform/database.ts' import type { FailureLog } from '../../platform/failure.ts' +import { Failure } from '../../platform/failure.ts' import type { CompanyCopies, CompanyProjects, @@ -34,26 +33,34 @@ import { projectsOf, } from '../company-tools/public.ts' import { TYPED_READ_NAMES } from '../connectors/public.ts' -import type { DataBinding, Owner, ReleaseScope, Speakers } from '../controller-kit/public.ts' +import type { + ConversationSpec, + DataBinding, + Owner, + ReleaseScope, + Speakers, +} from '../controller-kit/public.ts' import { ASK_USER_TOOL, admitAsker, - agentDefaults, + blockOf, CONVERSATION_MODE, - controllerOf, createAskUserTool, dataContextOf, MODEL_TIMEOUT, + mountAgent, principalOf, sessionModel, skillOf, toolsOf, } from '../controller-kit/public.ts' +import { dataOrder } from '../data-tools/public.ts' import type { ConversationMachine, ConversationMachines, MachineTuning } from '../machine/public.ts' import { createConversationMachines, PACKAGE_HOSTS, showFileTool } from '../machine/public.ts' import type { QueueDeps } from '../model-accounts/public.ts' import { subagentModel } from '../model-accounts/public.ts' import { profileReadOnlyInRuns } from './automation-memory.ts' +import { AVAILABLE_TOOLS } from './available-tools.ts' import { chosenConnections } from './chosen.ts' import { COMPANY_MEMORY_TOOLS, companyMemory, companyScopes } from './company-memory.ts' import { readsFiles } from './connector-access.ts' @@ -62,7 +69,7 @@ import { assistantRuns, machineMarks } from './context.ts' import { machineUploads, READ_MEDIA } from './files.ts' import type { HandOffDoors } from './handoff.ts' import { registerHandOff } from './handoff.ts' -import { assistantInstructions } from './instructions.ts' +import { FIXED, MODEL_BLOCKS } from './instructions.ts' import type { maysOf } from './mays.ts' import { assistantMemory } from './memory.ts' import type { OpenDeps } from './open.ts' @@ -75,42 +82,11 @@ import { RESEARCH, researchOnly } from './research.ts' import { registerAssistantRoutes } from './routes.ts' import type { ScopeOf } from './run-reads.ts' import { runReads } from './run-reads.ts' -import { assistantTurns, turnEnd, turnKey } from './turn.ts' +import { assistantTurn, turnEnd, turnKey } from './turn.ts' type AssistantConnectors = Connectors['assistant'] type AssistantConnection = Awaited>[number] -/** The `ToolSearchProcessor`'s own tool, by the id Mastra gives it. */ -const SEARCH_TOOLS = 'search_tools' -/** The memory's own tools, by the ids `@mastra/memory` gives them (`listTools`). */ -const MEMORY_TOOLS = ['recall', 'updateWorkingMemory'] as const -/** - * The closed set the mode offers the model (criterion 12): the layer that enforces it, as the - * controller filters the agent's tools by it; the save is built only for who may manage connections. - * The typed reads come only once a search loads them. Of the controller's own tools it holds - * `ask_user` (a card, only what it cannot decide) and the task list; the plan card stays the - * Builder's, as the Assistant approves no plan, and one subagent type, `pesquisar` - * (`research.ts`), which only reads. The memory's hold the person's other conversations and what - * the model keeps about them (`memory.ts`); the company's, what it keeps (`company-memory.ts`). - */ -const AVAILABLE_TOOLS: readonly string[] = [ - ...Object.values(WORKSPACE_TOOL), - ...MEMORY_TOOLS, - ...COMPANY_MEMORY_TOOLS, - SEARCH_TOOLS, - ...TYPED_READ_NAMES, - BUILDER_TOOL.connectorNotes, - BUILDER_TOOL.connectorNoteSave, - ...Object.values(DATA_TOOL), - ...Object.values(ASSISTANT_TOOL), - BUILDER_TOOL.webFetch, - BUILDER_TOOL.webSearch, - ...SKILL_TOOLS, - ASK_USER_TOOL, - SUBAGENT_TOOL, - ...TASK_TOOLS, -] - /** What Conexus does, read by the Assistant when the task asks (the `conexus` skill). */ const CONEXUS_SKILL = skillOf({ directory: 'conexus', @@ -170,81 +146,110 @@ async function inRequestOrder( } } -/** - * The agent (`template-agent-harness`, `agents/agent.ts:33-76`): its instructions, tools and skills - * from the run's scope, the Builder's model of the session and the Builder's processors by name. - */ -function assistantAgent( - deps: Deps, - parts: { - memory: ReturnType - company: ReturnType - turns: ReturnType - machines: ConversationMachines - scopeOf: RunOf - toolScopeOf: ScopeOf - tools: CompanyToolDeps - maysFor: ReturnType - speakersFor: (requestContext: RequestContext) => Promise - }, -) { - const { queue } = deps - const { scopeOf, toolScopeOf, maysFor } = parts - const showFile = showFileTool(parts.machines) - const proposeMemory = proposeCompanyMemoryTool({ memory: parts.company, scopeOf }) - const proposals = proposeTools(parts.machines) - async function automationRun(requestContext: RequestContext) { - return (await scopeOf(requestContext))?.attended === false - } - async function chosenOf(requestContext: RequestContext) { +type Parts = { + memory: ReturnType + company: ReturnType + machines: ConversationMachines + scopeOf: RunOf + toolScopeOf: ScopeOf + tools: CompanyToolDeps + maysFor: ReturnType + speakersFor: (requestContext: RequestContext) => Promise +} + +/** The connections the run's view chose and the company's tools reach; none outside a conversation. */ +function chosenIn({ toolScopeOf }: Parts) { + return async (requestContext: RequestContext) => { const scope = await toolScopeOf(requestContext) return scope === undefined ? [] : companyConnections(scope) } - const defaults = agentDefaults(queue, parts.turns) - const assistantDefaults = { - ...defaults, - // The turn's processor first, then the search that loads the reads (before the account's pick, - // which flattens them for CLIProxy's Google path); the person's files go to the machine last, - // once the pick has chosen the model. - inputProcessors: [ - parts.turns.processor, - companyReadSearch(toolScopeOf, parts.tools), - // Before the account's pick, which flattens the step's tools, so it flattens the closed one. - researchOnly, - profileReadOnlyInRuns(automationRun), - ...defaults.inputProcessors.filter((each) => each !== parts.turns.processor), - machineUploads({ log: deps.log }), - ], +} + +/** The tools of a run, in the order the request lists them: the model's provider's, the company's first, the Assistant's own, the hand-offs, the rest. */ +function assistantTools(parts: Parts) { + const { scopeOf, toolScopeOf, maysFor, machines } = parts + const showFile = showFileTool(machines) + const proposeMemory = proposeCompanyMemoryTool({ memory: parts.company, scopeOf }) + const proposals = proposeTools(machines) + const chosenOf = chosenIn(parts) + return async (requestContext: RequestContext) => { + const scope = await scopeOf(requestContext) + const { byAutomation, automate } = await maysFor(requestContext) + const { first, rest } = await inRequestOrder(await toolScopeOf(requestContext), parts.tools) + return { + ...toolsOf(sessionModel(requestContext)), + ...first, + [ASSISTANT_TOOL.showFile]: showFile, + [ASSISTANT_TOOL.proposeCompanyMemory]: proposeMemory, + ...(automate + ? { + [ASSISTANT_TOOL.proposeAutomation]: proposeAutomationTool( + await chosenOf(requestContext), + ), + } + : {}), + ...handOffOf(scope, proposals, byAutomation), + ...rest, + } + } +} + +/** The conversation's block of the instructions; a run with no conversation is the Hub's defect. */ +function blockOfRun(parts: Parts) { + const chosenOf = chosenIn(parts) + return async (requestContext: RequestContext) => { + const speakers = await parts.speakersFor(requestContext) + if (speakers === undefined) { + throw new Failure('INTERNAL_UNEXPECTED', { + details: { reason: 'PROMPT_WITHOUT_CONVERSATION' }, + }) + } + const [chosen, may] = await Promise.all([ + chosenOf(requestContext), + parts.maysFor(requestContext), + ]) + return blockOf(speakers, chosen, may) } - return new Agent({ - id: ASSISTANT_CONTROLLER, +} + +/** + * The Assistant's ficha: its instructions, tools and skills from the run's scope, the session's + * model, and the Builder's processors by name around the account's pick (the reads' search, the + * helper's closing and the automations' profile before it; the person's files to the machine after). + */ +function assistantSpec(deps: Deps, parts: Parts): ConversationSpec { + const { queue, log } = deps + const { scopeOf, toolScopeOf, machines } = parts + const chosenOf = chosenIn(parts) + return { + kind: 'assistant', name: 'Assistant', - instructions: assistantInstructions({ - chosenOf, - speakersOf: parts.speakersFor, - maysOf: maysFor, - }), - model: ({ requestContext }) => sessionModel(requestContext), - tools: async ({ requestContext }) => { - const scope = await scopeOf(requestContext) - const toolScope = await toolScopeOf(requestContext) - const { byAutomation, automate } = await maysFor(requestContext) - const { first, rest } = await inRequestOrder(toolScope, parts.tools) - return { - ...toolsOf(sessionModel(requestContext)), - ...first, - [ASSISTANT_TOOL.showFile]: showFile, - [ASSISTANT_TOOL.proposeCompanyMemory]: proposeMemory, - ...(automate - ? { - [ASSISTANT_TOOL.proposeAutomation]: proposeAutomationTool( - await chosenOf(requestContext), - ), - } - : {}), - ...handOffOf(scope, proposals, byAutomation), - ...rest, - } + base: 'AGENT', + prompt: { + kind: 'MESSAGES', + parts: [ + { kind: 'FIXED', text: FIXED }, + { kind: 'TEXT', text: dataOrder() }, + { kind: 'BY_MODEL', blocks: MODEL_BLOCKS }, + { kind: 'OF_RUN', of: blockOfRun(parts) }, + ], + }, + model: { kind: 'SESSION' }, + tools: assistantTools(parts), + // Decision 0053: nothing waits to be approved; the systems get no write. + approval: { kind: 'NOTHING_ASKS' }, + turn: assistantTurn({ queue, scopeOf }), + // Before the account's pick, which flattens the tools for CLIProxy's Google path: the search + // that loads the reads and the helper's closing. The person's files go last, once it has picked. + processors: { + beforePick: [ + companyReadSearch(toolScopeOf, parts.tools), + researchOnly, + profileReadOnlyInRuns(async (requestContext) => { + return (await scopeOf(requestContext))?.attended === false + }), + ], + afterPick: [machineUploads({ log })], }, skills: async ({ requestContext }) => [ CONEXUS_SKILL, @@ -252,11 +257,23 @@ function assistantAgent( skillOf({ directory: each.skill.name, ...each.skill }), ), ], - ...assistantDefaults, signals: [new TaskSignalProvider()], - memory: parts.memory, + threads: parts.memory, ...companyScopes({ memory: parts.company, scopeOf }), - }) + mode: { id: CONVERSATION_MODE, availableTools: AVAILABLE_TOOLS }, + // The helper's `connector_read` is made for each run, closed on the conversation's scope: the + // helper's own context cannot find the conversation (`research.ts`). + own: { + fixed: { [ASK_USER_TOOL]: createAskUserTool() }, + perRun: async ({ requestContext }) => { + const scope = await toolScopeOf(requestContext) + return scope === undefined ? {} : companyTools(scope, 'research', parts.tools) + }, + }, + subagents: { types: [RESEARCH], model: subagentModel(queue, MODEL_TIMEOUT.stepMs) }, + // The conversation's machine (Factory `session-sandbox.ts:29-36`); none outside a conversation. + workspace: ({ requestContext }) => machines.workspace(requestContext), + } } /** @@ -283,32 +300,15 @@ export function createAssistant(deps: Deps) { }, deps.machineTuning, ) - const turns = assistantTurns({ queue, scopeOf }) const tools = companyDeps(deps) const { speakersFor, maysFor, toolScopeOf } = runReads(deps, scopeOf) - const agent = assistantAgent(deps, { - ...{ memory, company, turns, scopeOf, machines }, - ...{ toolScopeOf, tools, maysFor, speakersFor }, - }) - const controller = controllerOf({ - ...{ kind: 'assistant', storage, memory, agent }, - mode: { id: CONVERSATION_MODE, availableTools: AVAILABLE_TOOLS }, - // The helper's `connector_read` is made for each run, closed on the conversation's scope: the - // helper's own context cannot find the conversation (`research.ts`). - tools: { - fixed: { [ASK_USER_TOOL]: createAskUserTool() }, - perRun: async ({ requestContext }) => { - const scope = await toolScopeOf(requestContext) - return scope === undefined ? {} : companyTools(scope, 'research', tools) - }, - }, - subagents: { types: [RESEARCH], model: subagentModel(queue, MODEL_TIMEOUT.stepMs) }, - // The conversation's machine (Factory `session-sandbox.ts:29-36`); none outside a conversation. - workspace: ({ requestContext }) => machines.workspace(requestContext), - // Decision 0053: nothing waits to be approved; the systems get no write. - initialState: { yolo: true }, - }) - turns.watch(controller) + const { controller } = mountAgent( + assistantSpec(deps, { + ...{ memory, company, scopeOf, machines }, + ...{ toolScopeOf, tools, maysFor, speakersFor }, + }), + { queue, storage }, + ) const opening: OpenDeps = { ...deps, controller, memory, chosen } return Object.freeze({ diff --git a/apps/server/src/builder/assistant/available-tools.ts b/apps/server/src/builder/assistant/available-tools.ts new file mode 100644 index 000000000..8a4fc6365 --- /dev/null +++ b/apps/server/src/builder/assistant/available-tools.ts @@ -0,0 +1,39 @@ +import { + ASSISTANT_TOOL, + BUILDER_TOOL, + DATA_TOOL, + SKILL_TOOLS, + SUBAGENT_TOOL, + TASK_TOOLS, + WORKSPACE_TOOL, +} from '@conexus/hub-api' +import { TYPED_READ_NAMES } from '../connectors/public.ts' +import { ASK_USER_TOOL } from '../controller-kit/public.ts' +import { COMPANY_MEMORY_TOOLS } from './company-memory.ts' + +/** The `ToolSearchProcessor`'s own tool, by the id Mastra gives it. */ +const SEARCH_TOOLS = 'search_tools' +/** The memory's own tools, by the ids `@mastra/memory` gives them (`listTools`). */ +const MEMORY_TOOLS = ['recall', 'updateWorkingMemory'] as const +/** + * The closed set the mode offers the model (criterion 12), which the controller enforces; the + * typed reads come only once a search loads them, and the controller's own tools it holds are + * `ask_user`, the task list and one subagent type, `pesquisar` (`research.ts`). + */ +export const AVAILABLE_TOOLS: readonly string[] = [ + ...Object.values(WORKSPACE_TOOL), + ...MEMORY_TOOLS, + ...COMPANY_MEMORY_TOOLS, + SEARCH_TOOLS, + ...TYPED_READ_NAMES, + BUILDER_TOOL.connectorNotes, + BUILDER_TOOL.connectorNoteSave, + ...Object.values(DATA_TOOL), + ...Object.values(ASSISTANT_TOOL), + BUILDER_TOOL.webFetch, + BUILDER_TOOL.webSearch, + ...SKILL_TOOLS, + ASK_USER_TOOL, + SUBAGENT_TOOL, + ...TASK_TOOLS, +] diff --git a/apps/server/src/builder/assistant/instructions.ts b/apps/server/src/builder/assistant/instructions.ts index 3389cee3f..0c11ff0cc 100644 --- a/apps/server/src/builder/assistant/instructions.ts +++ b/apps/server/src/builder/assistant/instructions.ts @@ -1,16 +1,5 @@ import { readFileSync } from 'node:fs' -import type { AgentInstructions } from '@mastra/core/agent' -import type { RequestContext } from '@mastra/core/request-context' -import { Failure } from '../../platform/failure.ts' -import type { Mays, Speakers } from '../controller-kit/public.ts' -import { - blockOf, - CONEXUS_PROMPT, - fixedSystem, - sessionModel, - TITLE, -} from '../controller-kit/public.ts' -import { dataOrder } from '../data-tools/public.ts' +import { CONEXUS_PROMPT, TITLE } from '../controller-kit/public.ts' /** * The Assistant's observer: the conversation's title and what a business conversation keeps, never @@ -22,7 +11,7 @@ export const ASSISTANT_OBSERVER = `${TITLE.ask.observer} Observe as a business a * The fixed message, the same bytes in every conversation of every company (criterion 13a): what * Conexus is, shared with the units after this one (`conexus.md`), then the Assistant (`assistant.md`). */ -const FIXED = [ +export const FIXED = [ CONEXUS_PROMPT, readFileSync(new URL('./prompt/assistant.md', import.meta.url), 'utf8').trim(), ].join('\n\n') @@ -36,41 +25,7 @@ const FIXED = [ * same block unmeasured. A model without a block gets the fixed message alone. */ const LUNA = readFileSync(new URL('./prompt/openai-luna.md', import.meta.url), 'utf8').trim() -const MODEL_BLOCKS: Readonly> = { +export const MODEL_BLOCKS: Readonly> = { 'openai/gpt-6-luna': LUNA, 'openai/gpt-5.6-luna': LUNA, } - -/** - * The system messages (`P1`, `L1`): the fixed one with its own cache mark, the turn's model's block - * when it has one, then the conversation's block, which the Hub marks as the last one; resolved again - * on each call of the agent. - */ -export function assistantInstructions(deps: { - /** The connections of the run's view: the chosen ones it reaches (issue 1147). */ - chosenOf: ( - requestContext: RequestContext, - ) => Promise - speakersOf: (requestContext: RequestContext) => Promise - maysOf: (requestContext: RequestContext) => Promise -}) { - return async ({ requestContext }: { requestContext: RequestContext }) => { - const [speakers, chosen, may] = await Promise.all([ - deps.speakersOf(requestContext), - deps.chosenOf(requestContext), - deps.maysOf(requestContext), - ]) - if (speakers === undefined) { - throw new Failure('INTERNAL_UNEXPECTED', { - details: { reason: 'PROMPT_WITHOUT_CONVERSATION' }, - }) - } - const model = MODEL_BLOCKS[sessionModel(requestContext)] - return [ - fixedSystem(FIXED), - { role: 'system', content: dataOrder() }, - ...(model === undefined ? [] : [{ role: 'system' as const, content: model }]), - { role: 'system', content: blockOf(speakers, chosen, may) }, - ] satisfies AgentInstructions - } -} diff --git a/apps/server/src/builder/assistant/turn.ts b/apps/server/src/builder/assistant/turn.ts index 92a89527b..3c80a24c4 100644 --- a/apps/server/src/builder/assistant/turn.ts +++ b/apps/server/src/builder/assistant/turn.ts @@ -1,6 +1,6 @@ import type { FailureCode } from '@conexus/hub-api' import type { AgentController, Session as ControllerSession } from '@mastra/core/agent-controller' -import { sessionTurns, takeOfScope, turnKeyOn } from '../controller-kit/public.ts' +import { takeOfScope, turnKeyOn } from '../controller-kit/public.ts' import { failureOf, modelFailure, TurnTally } from '../conversation/public.ts' import type { QueueDeps } from '../model-accounts/public.ts' import type { RunOf } from './context.ts' @@ -11,20 +11,21 @@ const TURN_PROCESSOR = 'conexus-assistant-turn' export const turnKey = turnKeyOn('conexus-assistant-turn-key') /** - * The Assistant's turns (step 24.1, U2) on the kit's owner of their end: a run of a conversation - * takes its owner's turn with a new `TurnKey`, and no Projeto (`Runs`): the controller already - * sends one message at a time to a conversation. A card (`ask_user`) suspends the run, and an - * automation's run ends then (`endOf`). The turn's end leaves the conversation's machine running: - * E2B pauses it on its own timeout, and a later question before then reuses it. + * The Assistant's turn on the ficha (step 24.1, U2): a run of a conversation takes its owner's turn + * with a new `TurnKey`, and no Projeto (`Runs`): the controller already sends one message at a time + * to a conversation. A card (`ask_user`) suspends the run, and an automation's run ends then + * (`endOf`). The turn's end leaves the conversation's machine running: E2B pauses it on its own + * timeout, and a later question before then reuses it. */ -export function assistantTurns(deps: { queue: QueueDeps; scopeOf: RunOf }) { - return sessionTurns({ +export function assistantTurn(deps: { queue: QueueDeps; scopeOf: RunOf }) { + return { + kind: 'SESSION', id: TURN_PROCESSOR, take: takeOfScope({ ...{ queue: deps.queue, turnKey }, scopeOf: async (requestContext) => (await deps.scopeOf(requestContext))?.owner, }), - }) + } as const } export type TurnEnd = { kind: 'DONE' } | { kind: 'FAILED'; code: FailureCode } diff --git a/apps/server/src/builder/controller-kit/factories.ts b/apps/server/src/builder/controller-kit/factories.ts index ebd40a13a..23c0c67d6 100644 --- a/apps/server/src/builder/controller-kit/factories.ts +++ b/apps/server/src/builder/controller-kit/factories.ts @@ -49,15 +49,25 @@ const BUILTIN: Record = { } /** - * What every conversation agent shares: the turn, then the account's pick; the account's errors; - * Mastra retries nothing itself, the account processors retry; and the model call's budget. + * What every conversation agent shares: the turn, then the account's pick, with the processors an + * agent puts `beforePick` and `afterPick` between them; the account's errors; Mastra retries + * nothing itself, the account processors retry; and the model call's budget. */ export function agentDefaults( queue: QueueDeps, turns: { processor: InputProcessor; deletedRun?: OutputProcessor }, + around: { + beforePick: readonly InputProcessor[] + afterPick: readonly InputProcessor[] + } = { beforePick: [], afterPick: [] }, ) { return { - inputProcessors: [turns.processor, accountPick(queue)], + inputProcessors: [ + turns.processor, + ...around.beforePick, + accountPick(queue), + ...around.afterPick, + ], outputProcessors: [ new CyberRefusalHandler(), workspaceMetadataLive, diff --git a/apps/server/src/builder/controller-kit/mount.ts b/apps/server/src/builder/controller-kit/mount.ts index 9fd275dd9..d697176c8 100644 --- a/apps/server/src/builder/controller-kit/mount.ts +++ b/apps/server/src/builder/controller-kit/mount.ts @@ -33,6 +33,10 @@ async function messagesOf( return [fixedSystem(part.text)] case 'TEXT': return [{ role: 'system', content: part.text } as const] + case 'BY_MODEL': { + const content = part.blocks[sessionModel(requestContext)] + return content === undefined ? [] : [{ role: 'system', content } as const] + } case 'OF_RUN': { const content = ofRun[at] return content === undefined ? [] : [{ role: 'system', content } as const] @@ -144,7 +148,7 @@ export function agentOfSpec( instructions: instructionsOf(spec.prompt), model: modelOf(spec.model), tools: ({ requestContext }) => toolsOfSpec(spec, requestContext), - ...agentDefaults(deps.queue, turns), + ...agentDefaults(deps.queue, turns, spec.processors), memory: spec.memory, ...(spec.skills === undefined ? {} : { skills: spec.skills }), ...(spec.signals === undefined ? {} : { signals: spec.signals }), @@ -164,13 +168,22 @@ export function mountAgent( spec: ConversationSpec, deps: { queue: QueueDeps; storage: MastraCompositeStore }, ): Readonly<{ agent: Agent; controller: AgentController }> { - const { kind, threads, memory, mode, own, workspace, ...fields } = spec + const { kind, threads, memory, mode, own, workspace, subagents, ...fields } = spec const { agent, watch } = agentOfSpec( { ...fields, id: CONTROLLER_KINDS[kind].id, memory: memory ?? threads }, deps, ) const controller = controllerOf({ - ...{ kind, storage: deps.storage, memory: threads, agent, mode, workspace, tools: own }, + ...{ + kind, + storage: deps.storage, + memory: threads, + agent, + mode, + workspace, + tools: own, + subagents, + }, initialState: initialStateOf(spec.approval), }) watch?.(controller) diff --git a/apps/server/src/builder/controller-kit/public.ts b/apps/server/src/builder/controller-kit/public.ts index 511563ff5..5c15a8fb0 100644 --- a/apps/server/src/builder/controller-kit/public.ts +++ b/apps/server/src/builder/controller-kit/public.ts @@ -1,7 +1,7 @@ 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 { CONEXUS_PROMPT, fixedSystem, TITLE } from './instructions.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' @@ -20,4 +20,4 @@ export { blockOf, turnDate } from './speakers.ts' export type { AgentSpec, ConversationSpec } from './spec.ts' export { listOwned, ownThread } from './thread.ts' export type { Taken } from './turns.ts' -export { sessionTurns, takeOfScope, turnKeyOn, turnProcessor } from './turns.ts' +export { takeOfScope, turnKeyOn, turnProcessor } 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 4029bbc4b..56c8e9b86 100644 --- a/apps/server/src/builder/controller-kit/spec.test.ts +++ b/apps/server/src/builder/controller-kit/spec.test.ts @@ -3,6 +3,7 @@ import type { TestContext } from 'node:test' import { test } from 'node:test' import { ModelId } from '@conexus/hub-api' import { Knowledge } from '@mastra/core/knowledge' +import type { InputProcessor } from '@mastra/core/processors' import { RequestContext } from '@mastra/core/request-context' import { TaskSignalProvider } from '@mastra/core/signals' import { createSkill } from '@mastra/core/skills' @@ -136,6 +137,51 @@ test('as instruções seguem a ordem da ficha, e uma parte do run que não dá n ]) }) +test('a ficha com um bloco por modelo o põe depois do texto fixo só quando o modelo da sessão tem um', async (t) => { + const { mount } = await mounting(t) + const { agent } = mount({ + prompt: { + kind: 'MESSAGES', + parts: [ + { kind: 'TEXT', text: 'Primeiro.' }, + { kind: 'BY_MODEL', blocks: { 'openai/gpt-6-luna': 'Do Luna.' } }, + { kind: 'TEXT', text: 'Último.' }, + ], + }, + }) + function on(modelId: string) { + const requestContext = new RequestContext() + requestContext.set('controller', { session: { modelId } }) + return agent.getInstructions({ requestContext }) + } + assert.deepEqual(await on('openai/gpt-6-luna'), [ + { role: 'system', content: 'Primeiro.' }, + { role: 'system', content: 'Do Luna.' }, + { role: 'system', content: 'Último.' }, + ]) + assert.deepEqual(await on('anthropic/claude-test'), [ + { role: 'system', content: 'Primeiro.' }, + { role: 'system', content: 'Último.' }, + ]) +}) + +test('a ficha sem processors dá o turno e a escolha da conta; com eles, uns antes e outros depois da escolha', async (t) => { + const { mount } = await mounting(t) + async function idsOf(fields: Partial) { + const listed = await mount(fields).agent.listConfiguredInputProcessors(new RequestContext()) + return listed.map((each) => ('id' in each ? each.id : undefined)) + } + assert.deepEqual(await idsOf({}), ['conexus-spec-turn', 'conexus-account-pick']) + const before: InputProcessor = { id: 'antes', processInputStep: () => ({}) } + const after: InputProcessor = { id: 'depois', processInputStep: () => ({}) } + assert.deepEqual(await idsOf({ processors: { beforePick: [before], afterPick: [after] } }), [ + 'conexus-spec-turn', + 'antes', + 'conexus-account-pick', + 'depois', + ]) +}) + test('o regime "a escrita pergunta" dá NEVER_ASKS, numa cópia, a toda ferramenta sem regra em função', async (t) => { const { mount } = await mounting(t) const unruled = createTool({ diff --git a/apps/server/src/builder/controller-kit/spec.ts b/apps/server/src/builder/controller-kit/spec.ts index fd2d6bedf..8de5a83f2 100644 --- a/apps/server/src/builder/controller-kit/spec.ts +++ b/apps/server/src/builder/controller-kit/spec.ts @@ -1,5 +1,6 @@ import type { AgentConfig, AgentInstructions, 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' import type { Turn } from '../model-accounts/public.ts' import type { controllerOf } from './factories.ts' @@ -11,6 +12,8 @@ import type { Taken } from './turns.ts' export type PromptPart = | Readonly<{ kind: 'FIXED'; text: string }> | Readonly<{ kind: 'TEXT'; text: string }> + /** The block of the turn's model, by its id with its provider; a model without one adds no message. */ + | Readonly<{ kind: 'BY_MODEL'; blocks: Readonly> }> | Readonly<{ kind: 'OF_RUN' of: (requestContext: RequestContext) => Promise @@ -62,6 +65,12 @@ type RunTurn = Readonly<{ export type TurnSource = SessionTurn | RunTurn +/** The input processors an agent adds around the account's pick (C26): the turn's comes first, always. */ +type Processors = Readonly<{ + beforePick: readonly InputProcessor[] + afterPick: readonly InputProcessor[] +}> + /** What an agent is made of: Mastra's `Agent` fields, filled by its ficha. */ export type AgentSpec = Readonly<{ id: string @@ -74,6 +83,7 @@ export type AgentSpec = Readonly<{ approval: Approval memory: AgentConfig['memory'] turn: TurnSource + processors?: Processors skills?: AgentConfig['skills'] signals?: AgentConfig['signals'] scopes?: AgentConfig['scopes'] @@ -94,5 +104,7 @@ export type ConversationSpec = Omit & mode: ControllerInput['mode'] /** The controller's own tools under native ids (`ask_user`, `submit_plan`). */ own?: NonNullable + /** The helpers the `subagent` tool may start (row 22), and the model of each one's calls. */ + subagents?: ControllerInput['subagents'] workspace?: ControllerInput['workspace'] }> From 4e68f5e40c0ae588ab30c9b5d6587644c2632083 Mon Sep 17 00:00:00 2001 From: reviewer Date: Mon, 23 Nov 2026 13:17:06 +0000 Subject: [PATCH 2/2] refactor(harness): U5 tira os imports sem uso do assistant.ts --- apps/server/src/builder/assistant/assistant.ts | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/apps/server/src/builder/assistant/assistant.ts b/apps/server/src/builder/assistant/assistant.ts index 0fb0b688b..2c3cf2276 100644 --- a/apps/server/src/builder/assistant/assistant.ts +++ b/apps/server/src/builder/assistant/assistant.ts @@ -1,14 +1,6 @@ import { readFileSync } from 'node:fs' import type { CompanyData, CompanyId, ConversationId, Person } from '@conexus/hub-api' -import { - ASSISTANT_TOOL, - BUILDER_TOOL, - DATA_TOOL, - SKILL_TOOLS, - SUBAGENT_TOOL, - TASK_TOOLS, - WORKSPACE_TOOL, -} from '@conexus/hub-api' +import { ASSISTANT_TOOL } from '@conexus/hub-api' import type { RequestContext } from '@mastra/core/request-context' import { TaskSignalProvider } from '@mastra/core/signals' import type { MastraCompositeStore } from '@mastra/core/storage' @@ -32,7 +24,6 @@ import { companyTools, projectsOf, } from '../company-tools/public.ts' -import { TYPED_READ_NAMES } from '../connectors/public.ts' import type { ConversationSpec, DataBinding, @@ -62,7 +53,7 @@ import { subagentModel } from '../model-accounts/public.ts' import { profileReadOnlyInRuns } from './automation-memory.ts' import { AVAILABLE_TOOLS } from './available-tools.ts' import { chosenConnections } from './chosen.ts' -import { COMPANY_MEMORY_TOOLS, companyMemory, companyScopes } from './company-memory.ts' +import { companyMemory, companyScopes } from './company-memory.ts' import { readsFiles } from './connector-access.ts' import type { RunOf } from './context.ts' import { assistantRuns, machineMarks } from './context.ts'