Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions apps/server/src/builder/controller-kit/mount.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 }
Expand All @@ -130,36 +132,50 @@ 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,
...(spec.description === undefined ? {} : { description: spec.description }),
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 } : {}),
}
}

Expand Down
8 changes: 4 additions & 4 deletions apps/server/src/builder/controller-kit/public.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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'
59 changes: 59 additions & 0 deletions apps/server/src/builder/controller-kit/spec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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'])
})
26 changes: 18 additions & 8 deletions apps/server/src/builder/controller-kit/spec.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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<string> }>
| Readonly<{
kind: 'DELEGATED'
of: (requestContext: RequestContext) => Promise<AgentInstructions>
Expand Down Expand Up @@ -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'
Expand All @@ -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<ToolsInput>
Expand All @@ -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<typeof controllerOf>[0]

/** A conversation's agent and its controller: the id is `CONTROLLER_KINDS[kind].id`, never the ficha's. */
export type ConversationSpec = Omit<AgentSpec, 'id' | 'memory' | 'turn'> &
export type ConversationSpec = Omit<AgentSpec, 'id' | 'memory'> &
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. */
Expand Down
107 changes: 51 additions & 56 deletions apps/server/src/builder/conversation/builder.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 }
}

Expand Down
Loading
Loading