From f9d1c51b4ce2045d5913fd0a38105e454683a3fa Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 1 Oct 2026 07:17:07 +0200 Subject: [PATCH 01/14] feat(platform): give projects without agents the organization's standard agent Members cannot create agents, so a project without one left them no way to hand it work. A `standard_agent` governance policy, on by default, now provides one: the first task given to it in a project without agents of its own sets up a managed project agent (0145: `managed`, one per project), with the project's document skills and no connectors, tools or secrets. Nobody edits it; every start reads the policy again, resolves its runtime and model for the person the run acts for (chat Auto's standard band, or the admin's pin, which never falls back), writes the result back to the row and refuses with the policy's reason when it cannot run (STANDARD_AGENT_OFF, STANDARD_AGENT_UNAVAILABLE). The retry job retires such a refusal. The chat hand-over note tells each person when a project's tasks go to it. --- .../custom/governance/standard-agent.yml | 6 + .../shared/src/schemas/governance.test.ts | 44 ++ packages/shared/src/schemas/governance.ts | 39 ++ .../components/project-agent-dialog.tsx | 2 +- .../features/projects/lib/document-skills.ts | 5 - .../backend/core/chat/task_handover.test.ts | 3 + .../backend/core/chat/task_handover.ts | 2 + .../0146_project_agents_managed.sql | 29 ++ .../platform/backend/domains/chat/handover.ts | 22 +- .../backend/domains/governance/routes.test.ts | 35 ++ .../backend/domains/governance/routes.ts | 18 +- .../backend/domains/governance/shim.ts | 3 +- .../backend/domains/projects/routes.test.ts | 65 +++ .../backend/domains/projects/routes.ts | 31 ++ .../domains/projects/service.agents.test.ts | 129 +++++ .../backend/domains/projects/service.ts | 129 ++++- .../projects/standard-agent.integration.ts | 294 +++++++++++ .../domains/projects/standard-agent.test.ts | 472 +++++++++++++++++ .../domains/projects/standard-agent.ts | 482 ++++++++++++++++++ .../tasks/agent-runs.standard-agent.test.ts | 120 +++++ .../backend/domains/tasks/agent-runs.ts | 46 +- .../backend/domains/tasks/errors.test.ts | 15 +- .../platform/backend/integration-check.ts | 2 + .../jobs/task-list.agent-retry.test.ts | 32 ++ services/platform/backend/jobs/task-list.ts | 63 ++- services/platform/backend/rest/error-codes.ts | 3 + services/platform/lib/chat/context.test.ts | 2 + services/platform/lib/chat/handover.test.ts | 24 + services/platform/lib/chat/handover.ts | 16 +- services/platform/lib/chat/index.ts | 1 + services/platform/lib/chat/model-choice.ts | 37 +- .../config/document-skills-catalog.test.ts | 2 +- .../platform/lib/shared/document-skills.ts | 7 + services/platform/messages/de.yml | 52 ++ services/platform/messages/en.yml | 52 ++ services/platform/messages/fr.yml | 52 ++ services/platform/scripts/openapi/spec.ts | 17 +- 37 files changed, 2300 insertions(+), 53 deletions(-) create mode 100644 configs/platform/custom/governance/standard-agent.yml delete mode 100644 services/platform/app/features/projects/lib/document-skills.ts create mode 100644 services/platform/backend/db/migrations/0146_project_agents_managed.sql create mode 100644 services/platform/backend/domains/projects/standard-agent.integration.ts create mode 100644 services/platform/backend/domains/projects/standard-agent.test.ts create mode 100644 services/platform/backend/domains/projects/standard-agent.ts create mode 100644 services/platform/backend/domains/tasks/agent-runs.standard-agent.test.ts create mode 100644 services/platform/lib/shared/document-skills.ts diff --git a/configs/platform/custom/governance/standard-agent.yml b/configs/platform/custom/governance/standard-agent.yml new file mode 100644 index 0000000000..7031e68639 --- /dev/null +++ b/configs/platform/custom/governance/standard-agent.yml @@ -0,0 +1,6 @@ +# The organization's standard agent: the project agent Tale provides in every +# project that has none of its own, so work can go to an agent before anyone +# sets one up. Leave harness, providerSlug and modelId out to let the platform +# choose (set providerSlug and modelId together to pin a model), and add +# instructions to replace its built-in standing instructions. +enabled: true diff --git a/packages/shared/src/schemas/governance.test.ts b/packages/shared/src/schemas/governance.test.ts index 4e53337e04..fc63d6bcef 100644 --- a/packages/shared/src/schemas/governance.test.ts +++ b/packages/shared/src/schemas/governance.test.ts @@ -20,6 +20,7 @@ import { reviewPolicyConfigSchema, skillOrgWideModeOf, skillSharingConfigSchema, + standardAgentConfigSchema, transcriptionModelConfigSchema, visionModelConfigSchema, } from './governance'; @@ -490,6 +491,49 @@ describe('imageGenerationConfigSchema', () => { }); }); +describe('standardAgentConfigSchema', () => { + it('is registered as the standard_agent policy schema', () => { + expect(POLICY_SCHEMAS.standard_agent).toBe(standardAgentConfigSchema); + }); + + it('reads on with everything automatic, and every pin', () => { + expect(standardAgentConfigSchema.parse({ enabled: true })).toEqual({ + enabled: true, + }); + const pinned = { + enabled: true, + harness: 'codex', + providerSlug: 'openai', + modelId: 'gpt-5.5', + instructions: 'Answer in the language of the task.', + }; + expect(standardAgentConfigSchema.parse(pinned)).toEqual(pinned); + }); + + it('keeps its pins while switched off, so switching it on restores them', () => { + const parked = { + enabled: false, + harness: 'claude-code', + providerSlug: 'anthropic', + modelId: 'claude-sonnet-5', + }; + expect(standardAgentConfigSchema.parse(parked)).toEqual(parked); + }); + + it.each([ + {}, + { enabled: 'yes' }, + { enabled: true, providerSlug: 'openai' }, + { enabled: true, modelId: 'gpt-5.5' }, + { enabled: true, harness: '' }, + { enabled: true, instructions: '' }, + { enabled: true, instructions: 'x'.repeat(20_001) }, + { enabled: true, model: 'misspelled-pin' }, + ])('refuses a config that cannot be routed or read: %j', (config) => { + expect(standardAgentConfigSchema.safeParse(config).success).toBe(false); + }); +}); + describe('reviewPolicyConfigSchema', () => { it('accepts the empty config — a missing file and no requirement mean the same thing', () => { const parsed = reviewPolicyConfigSchema.safeParse({}); diff --git a/packages/shared/src/schemas/governance.ts b/packages/shared/src/schemas/governance.ts index 135df61cd9..e76027d60c 100644 --- a/packages/shared/src/schemas/governance.ts +++ b/packages/shared/src/schemas/governance.ts @@ -81,6 +81,10 @@ export const POLICY_TYPES = [ // may generate images, and with which model. Missing file ⇒ off — the // capability is opt-in. See `imageGenerationConfigSchema`. 'image_generation', + // The organization's standard agent: the project agent Tale provides in + // every project that has none of its own. Missing file ⇒ on, runtime and + // model automatic. See `standardAgentConfigSchema`. + 'standard_agent', // Independent-review requirements for the task-review gate. Missing row / // empty config ⇒ no extra requirement — anyone with project edit access // may approve, exactly as today. See `reviewPolicyConfigSchema`; enforced @@ -407,6 +411,40 @@ export const imageGenerationConfigSchema = z ); export type ImageGenerationConfig = z.infer; +/** + * The organization's standard agent — the project agent Tale provides in + * every project that has none of its own, so work can go to an agent before + * anyone sets one up (`backend/domains/projects/standard-agent.ts`). + * + * On by default: a missing file and `enabled: true` both mean ON. Off, no + * project offers it and a task already given to it cannot start. The + * runtime (`harness`) and the model are each automatic when absent: the + * platform picks a model the person starting the run may use, run by Claude + * Code (or by the runtime a subscription-served model is bound to). Pin both + * `providerSlug` and `modelId`, or neither; the write door checks `harness` + * against the runtimes a project agent may use. Pins may stay while the + * policy is off, so switching it back on restores them. `instructions` + * replaces the built-in standing instructions. + */ +export const standardAgentConfigSchema = z + .object({ + enabled: z.boolean(), + harness: z.string().min(1).max(64).optional(), + providerSlug: z.string().min(1).max(64).optional(), + modelId: z.string().min(1).max(200).optional(), + instructions: z.string().min(1).max(20_000).optional(), + }) + .strict() + .refine( + (config) => + (config.providerSlug === undefined) === (config.modelId === undefined), + { + message: + 'pin both providerSlug and modelId, or neither (neither = automatic selection)', + }, + ); +export type StandardAgentConfig = z.infer; + export const uploadPolicyConfigSchema = z.object({ enabled: z.boolean(), allowedExtensions: z.array(z.string()).optional(), @@ -1222,6 +1260,7 @@ export const POLICY_SCHEMAS = { vision_model: visionModelConfigSchema, transcription_model: transcriptionModelConfigSchema, image_generation: imageGenerationConfigSchema, + standard_agent: standardAgentConfigSchema, review_policy: reviewPolicyConfigSchema, embedding: embeddingConfigSchema, skill_sharing: skillSharingConfigSchema, diff --git a/services/platform/app/features/projects/components/project-agent-dialog.tsx b/services/platform/app/features/projects/components/project-agent-dialog.tsx index eb2e5aaafc..89c78aaeeb 100644 --- a/services/platform/app/features/projects/components/project-agent-dialog.tsx +++ b/services/platform/app/features/projects/components/project-agent-dialog.tsx @@ -24,6 +24,7 @@ import { import { failureDetail } from '@/app/lib/backend/adapters'; import { AGENT_TOOL_CATALOG } from '@/backend/core/sandbox/tool_names'; import { useT } from '@/lib/i18n/client'; +import { DOCUMENT_SKILL_SLUGS } from '@/lib/shared/document-skills'; import { AppError } from '@/lib/shared/errors/app-error'; import { @@ -33,7 +34,6 @@ import { import { useAgentSecrets, type AgentSecretSummary } from '../hooks/queries'; import type { ProjectAgentRow } from '../hooks/queries'; import { useUnpinnedServingPreview } from '../hooks/use-unpinned-serving-preview'; -import { DOCUMENT_SKILL_SLUGS } from '../lib/document-skills'; import { findSelectedModel, type ModelOption } from '../lib/model-options'; import { AgentSecretsField } from './agent-secrets-field'; diff --git a/services/platform/app/features/projects/lib/document-skills.ts b/services/platform/app/features/projects/lib/document-skills.ts deleted file mode 100644 index 89a31c6d34..0000000000 --- a/services/platform/app/features/projects/lib/document-skills.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Standard document bundles seeded from `configs/platform/custom/skills/`. - * A new project agent preselects only the ones its project can access. - */ -export const DOCUMENT_SKILL_SLUGS = ['docx', 'pptx', 'xlsx', 'pdf'] as const; diff --git a/services/platform/backend/core/chat/task_handover.test.ts b/services/platform/backend/core/chat/task_handover.test.ts index 4863545d75..b18278bd44 100644 --- a/services/platform/backend/core/chat/task_handover.test.ts +++ b/services/platform/backend/core/chat/task_handover.test.ts @@ -21,6 +21,7 @@ describe('readTaskHandover', () => { { name: 'Getting started', agentCount: 0, canEdit: false }, ], automationEnabled: true, + standardAgent: true, })), ARGS, ); @@ -30,11 +31,13 @@ describe('readTaskHandover', () => { projectsWithoutAgents: 1, canAddAgents: false, automationOff: false, + standardAgent: true, labels: { createTask: 'Aufgabe erstellen', createAndStart: 'Erstellen und Agent starten', assignee: 'Zuständig', createAgent: 'Agent erstellen …', + standardAgent: 'Standard-Agent', }, }); }); diff --git a/services/platform/backend/core/chat/task_handover.ts b/services/platform/backend/core/chat/task_handover.ts index 51da743f37..46c7984c5b 100644 --- a/services/platform/backend/core/chat/task_handover.ts +++ b/services/platform/backend/core/chat/task_handover.ts @@ -56,11 +56,13 @@ export async function readTaskHandover( (project) => project.agentCount === 0 && project.canEdit, ), automationOff: facts.automationEnabled !== true, + standardAgent: facts.standardAgent === true, labels: { createTask: label('chat.createTask.headerButton'), createAndStart: label('tasks.actions.createAndStart'), assignee: label('tasks.fields.assignee'), createAgent: label('tasks.assignee.createAgent'), + standardAgent: label('tasks.assignee.standardAgent'), }, }; } catch (error) { diff --git a/services/platform/backend/db/migrations/0146_project_agents_managed.sql b/services/platform/backend/db/migrations/0146_project_agents_managed.sql new file mode 100644 index 0000000000..d9ae1e93e6 --- /dev/null +++ b/services/platform/backend/db/migrations/0146_project_agents_managed.sql @@ -0,0 +1,29 @@ +-- The organization's standard agent, one per project that needs it. +-- +-- A project without agents of its own was a dead end for everyone who cannot +-- set one up (a Member): its tasks could go to a person, never to an agent. +-- The `standard_agent` governance policy (on by default) now gives such a +-- project an agent Tale manages. It is created the first time someone hands +-- work there, configured by the policy rather than by hand, and brought back +-- in line with the policy whenever a run starts +-- (`backend/domains/projects/standard-agent.ts`). +-- +-- managed true for the standard agent Tale created and keeps in line with +-- the policy: its runtime, model and instructions are the policy's, +-- so the Agents tab shows them and nobody edits them there. false +-- for every agent a person set up. +-- +-- At most one managed agent per project: the partial unique index makes two +-- people handing work to the same project at the same moment create one +-- agent, not two (the second insert finds the first). +-- +-- Rolling-deploy safe: a NOT NULL column with a constant default, and an +-- index over rows only the new image writes. The previous image neither reads +-- nor writes the column, and the agents it creates read as not managed. + +ALTER TABLE app.project_agents + ADD COLUMN IF NOT EXISTS managed boolean NOT NULL DEFAULT false; + +CREATE UNIQUE INDEX IF NOT EXISTS project_agents_one_managed + ON app.project_agents (project_id) + WHERE managed; diff --git a/services/platform/backend/domains/chat/handover.ts b/services/platform/backend/domains/chat/handover.ts index bf356d80d6..ce409dc44a 100644 --- a/services/platform/backend/domains/chat/handover.ts +++ b/services/platform/backend/domains/chat/handover.ts @@ -2,17 +2,21 @@ import type { Sql } from 'postgres'; import { findOrganizationMember } from '../../auth/membership.ts'; import { getProjectAuthContext, listProjects } from '../projects/service.ts'; +import { readStandardAgentAvailability } from '../projects/standard-agent.ts'; import { mentionAutomationEnabled } from '../tasks/run-start.ts'; /** * What the chat's hand-over note (`lib/chat/handover.ts`) is built from, for * one person: the active projects they can open, each with its agent count - * and whether they may add agents to it, and whether the organization lets - * agents start at all (a broken policy reads as off, as for a mention). + * and whether they may add agents to it, whether the organization lets + * agents start at all (a broken policy reads as off, as for a mention), and + * whether its standard agent would take work in a project without agents + * for this person. */ export interface TaskHandoverFacts { projects: { name: string; agentCount: number; canEdit: boolean }[]; automationEnabled: boolean; + standardAgent: boolean; } export async function readTaskHandoverFacts( @@ -25,7 +29,7 @@ export async function readTaskHandoverFacts( args.userId, ); if (member === null || member.role === 'disabled') { - return { projects: [], automationEnabled: false }; + return { projects: [], automationEnabled: false, standardAgent: false }; } const auth = await getProjectAuthContext(sql, { organizationId: args.organizationId, @@ -40,5 +44,17 @@ export async function readTaskHandoverFacts( canEdit: project.canEdit, })), automationEnabled: await mentionAutomationEnabled(sql, args.organizationId), + // One fact of several: a failed read says no standard agent rather + // than costing the person the whole note. + standardAgent: await readStandardAgentAvailability(sql, args).then( + (availability) => availability.available, + (error: unknown) => { + console.warn( + `[chat] standard agent availability unread for the hand-over note (organization ${args.organizationId}):`, + error instanceof Error ? error.message : error, + ); + return false; + }, + ), }; } diff --git a/services/platform/backend/domains/governance/routes.test.ts b/services/platform/backend/domains/governance/routes.test.ts index 7c999613e7..0136ac1174 100644 --- a/services/platform/backend/domains/governance/routes.test.ts +++ b/services/platform/backend/domains/governance/routes.test.ts @@ -509,6 +509,41 @@ describe('POST /policies/sandbox_quota — deployment capacity', () => { ); }); +describe('POST /policies/standard_agent — the runtime a project agent may use', () => { + it('refuses a runtime the managed lane cannot run, naming the ones it can, before any write', async () => { + const response = await post('/policies/standard_agent', { + config: { enabled: true, harness: 'cursor' }, + }); + + expect(response.status).toBe(400); + const body = (await response.json()) as { + error: string; + data: { harnesses: string[] }; + }; + expect(body.error).toBe('STANDARD_AGENT_HARNESS_INVALID'); + expect(body.data.harnesses).toContain('claude-code'); + expect(body.data.harnesses).not.toContain('cursor'); + expect(writeGovernancePolicyFile).not.toHaveBeenCalled(); + }); + + it('saves a runtime the managed lane can run, and Automatic', async () => { + for (const config of [ + { enabled: true, harness: 'codex' }, + { enabled: false }, + ]) { + writeGovernancePolicyFile.mockClear(); + const response = await post('/policies/standard_agent', { config }); + expect(response.status).toBe(200); + expect(writeGovernancePolicyFile).toHaveBeenCalledWith( + expect.anything(), + 'acme', + 'standard_agent', + config, + ); + } + }); +}); + describe('GET /my/model-api', () => { async function read(sql: never = {} as never): Promise { return await createGovernanceRoutes({ sql, auth: {} as never }).request( diff --git a/services/platform/backend/domains/governance/routes.ts b/services/platform/backend/domains/governance/routes.ts index c11515d1f4..1ed90ff84c 100644 --- a/services/platform/backend/domains/governance/routes.ts +++ b/services/platform/backend/domains/governance/routes.ts @@ -10,6 +10,7 @@ import { sandboxQuotaConfigSchema, sandboxQuotaTotal, sandboxWorkspacesConfigSchema, + standardAgentConfigSchema, } from '@tale/shared/schemas/governance'; import { Hono, type Context } from 'hono'; import type { Sql } from 'postgres'; @@ -39,6 +40,7 @@ import { ContactError } from '../contacts/service.ts'; import { syncRagDocumentScope } from '../knowledge/service.ts'; import { readModelApiStanding } from '../model_api/access.ts'; import { listModelApiModels } from '../model_api/models.ts'; +import { eligibleProjectAgentHarnesses } from '../projects/service.ts'; import { getSandboxDeploymentLimits } from '../sandbox/limits.ts'; import { recordUnusedWorkspaceRule } from '../sandbox/unused-rule.ts'; import { holdsApiKeys, listOrgApiKeys } from './api-keys.ts'; @@ -135,7 +137,9 @@ export function createGovernanceRoutes(deps: { deps.sql, c.get('orgId'), policyType, - policyType === 'transcription_model' || policyType === 'image_generation' + policyType === 'transcription_model' || + policyType === 'image_generation' || + policyType === 'standard_agent' ? { strict: true } : {}, ); @@ -185,6 +189,18 @@ export function createGovernanceRoutes(deps: { 400, ); } + if (policyType === 'standard_agent') { + // The runtime a project agent may run on is the managed lane's list, + // which only the platform knows; the shared schema cannot check it. + const { harness } = standardAgentConfigSchema.parse(parsed.data); + const harnesses = eligibleProjectAgentHarnesses(); + if (harness !== undefined && !harnesses.includes(harness)) { + return c.json( + { error: 'STANDARD_AGENT_HARNESS_INVALID', data: { harnesses } }, + 400, + ); + } + } if (policyType === 'sandbox_quota') { const total = sandboxQuotaTotal( sandboxQuotaConfigSchema.parse(parsed.data), diff --git a/services/platform/backend/domains/governance/shim.ts b/services/platform/backend/domains/governance/shim.ts index dc43a451a0..70c664ab75 100644 --- a/services/platform/backend/domains/governance/shim.ts +++ b/services/platform/backend/domains/governance/shim.ts @@ -31,7 +31,8 @@ export function governanceShimHandlers(sql: Sql): ShimHandlers { // established best-effort default posture. args.policyType === 'vision_model' || args.policyType === 'transcription_model' || - args.policyType === 'image_generation' + args.policyType === 'image_generation' || + args.policyType === 'standard_agent' ? { strict: true } : {}, ); diff --git a/services/platform/backend/domains/projects/routes.test.ts b/services/platform/backend/domains/projects/routes.test.ts index ccf17d6d6f..8dcf86c926 100644 --- a/services/platform/backend/domains/projects/routes.test.ts +++ b/services/platform/backend/domains/projects/routes.test.ts @@ -38,6 +38,11 @@ vi.mock('./service.ts', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, ...service }; }); +const standard = vi.hoisted(() => ({ + ensureStandardAgent: vi.fn(), + readStandardAgentAvailability: vi.fn(), +})); +vi.mock('./standard-agent.ts', () => standard); vi.mock('./secrets.ts', () => ({ deleteProjectSecret: vi.fn(), listProjectSecrets: vi.fn(), @@ -147,6 +152,66 @@ describe('project agent session routes share REST configuration limits', () => { }); }); +describe('the standard agent’s doors — any member reads it, any reader hands it work', () => { + it('answers the caller’s view of the standard agent, before a project id could match', async () => { + standard.readStandardAgentAvailability.mockResolvedValue({ + enabled: true, + available: true, + harness: 'claude-code', + model: 'claude-sonnet-5', + }); + + const res = await createProjectRoutes({ + sql: {} as never, + auth: {} as never, + }).request('/standard-agent?orgId=o1'); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ available: true }); + expect(standard.readStandardAgentAvailability).toHaveBeenCalledWith( + expect.anything(), + { organizationId: 'o1', userId: 'u1' }, + ); + }); + + it('adds the project’s standard agent for the caller, in a transaction', async () => { + standard.ensureStandardAgent.mockResolvedValue({ + agentId: 'agent-standard', + created: true, + }); + + const res = await send('POST', '/p1/standard-agent', {}); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toEqual({ + agentId: 'agent-standard', + created: true, + }); + expect(standard.ensureStandardAgent).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ organizationId: 'o1', userId: 'u1' }), + 'p1', + ); + }); + + it('answers a refusal with its own status, code and reason', async () => { + const { ProjectError } = await import('./service.ts'); + standard.ensureStandardAgent.mockRejectedValue( + new ProjectError('STANDARD_AGENT_UNAVAILABLE', 'No model', 409, { + reason: 'no-model', + }), + ); + + const res = await send('POST', '/p1/standard-agent', {}); + + expect(res.status).toBe(409); + await expect(res.json()).resolves.toEqual({ + error: 'STANDARD_AGENT_UNAVAILABLE', + data: { reason: 'no-model' }, + }); + }); +}); + describe('project routes — the shared schemas guard the door', () => { it('refuses an icon or colour outside the shared allowlists', async () => { const badIcon = await send('POST', '/', { name: 'P', icon: 'NotAnIcon' }); diff --git a/services/platform/backend/domains/projects/routes.ts b/services/platform/backend/domains/projects/routes.ts index 7031351c12..2ad913e5d8 100644 --- a/services/platform/backend/domains/projects/routes.ts +++ b/services/platform/backend/domains/projects/routes.ts @@ -53,6 +53,10 @@ import { updateProjectSharing, type ProjectAuthContext, } from './service.ts'; +import { + ensureStandardAgent, + readStandardAgentAvailability, +} from './standard-agent.ts'; // The project bodies parse with the SHARED schemas (`lib/shared/schemas/ // projects.ts`) — the one copy the editor, this door and the service read, @@ -160,6 +164,17 @@ export function createProjectRoutes(deps: { } }); + // The organization's standard agent, as the caller could hand it work: + // on, runnable for them, and what it would run on. Before `/:id`. + app.get('/standard-agent', async (c) => { + return c.json( + await readStandardAgentAvailability(deps.sql, { + organizationId: c.get('orgId'), + userId: c.get('sessionBundle').user.id, + }), + ); + }); + app.get('/:id', async (c) => { try { const auth = await authCtx(c); @@ -367,6 +382,22 @@ export function createProjectRoutes(deps: { } }); + // The project's standard agent, created if the project has no agents of + // its own — anyone who can open the project may hand it work + // (`standard-agent.ts`). + app.post('/:id/standard-agent', async (c) => { + try { + const auth = await authCtx(c); + return c.json( + await transactSerializable(deps.sql, (tx) => + ensureStandardAgent(tx, auth, c.req.param('id')), + ), + ); + } catch (error) { + return handleError(c, error); + } + }); + app.post('/agents/:agentId', async (c) => { const body = projectAgentInputSchema.safeParse(await c.req.json()); if (!body.success) { diff --git a/services/platform/backend/domains/projects/service.agents.test.ts b/services/platform/backend/domains/projects/service.agents.test.ts index 7f8233c73e..7c343236cf 100644 --- a/services/platform/backend/domains/projects/service.agents.test.ts +++ b/services/platform/backend/domains/projects/service.agents.test.ts @@ -13,10 +13,13 @@ import type { Sql, TransactionSql } from 'postgres'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createAuditLog } from '../audit_logs/service.ts'; import { + alignManagedProjectAgent, createProjectAgent, deleteProjectAgent, detachSkillFromAgents, + insertManagedProjectAgent, listProjectsPage, updateProjectAgent, } from './service.ts'; @@ -313,6 +316,132 @@ describe('updateProjectAgent — the optimistic precondition', () => { }); }); +/** A transaction stand-in answering by statement text, for the cases that + * need answers `fakeTx` does not give. */ +function answeringTx(answer: (text: string) => unknown[]): { + tx: TransactionSql; + statements: Statement[]; +} { + const statements: Statement[] = []; + const run = (strings: TemplateStringsArray, ...values: unknown[]) => { + const text = strings.join('?').replace(/\s+/g, ' ').trim(); + statements.push({ text, values }); + return Promise.resolve(answer(text)); + }; + const tx = Object.assign(run, { unsafe: (text: string) => text }); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a template-tag stand-in for the postgres.js transaction + return { tx: tx as unknown as TransactionSql, statements }; +} + +describe('the standard agent follows the organization, not an edit', () => { + it('refuses a save of the standard agent with PROJECT_AGENT_MANAGED, writing nothing', async () => { + const { tx, statements } = answeringTx((text) => + text.includes('FROM app.project_agents WHERE id = ?') + ? [{ ...AGENT, managed: true }] + : [], + ); + + await expect(updateProjectAgent(tx, auth, config)).rejects.toMatchObject({ + code: 'PROJECT_AGENT_MANAGED', + status: 409, + }); + expect(updates(statements)).toEqual([]); + }); + + const FIELDS = { + name: 'Standard agent', + harness: 'claude-code', + model: 'claude-sonnet-5', + modelProvider: 'anthropic', + skills: ['docx'], + instructions: 'Do the task.', + }; + + it('writes it with the project’s count, an audit row naming it managed, and a hint', async () => { + const { tx, statements } = answeringTx((text) => + text.startsWith('INSERT INTO app.project_agents') + ? [{ id: 'agent-standard' }] + : [], + ); + + await expect( + insertManagedProjectAgent(tx, auth, PROJECT, FIELDS), + ).resolves.toEqual({ agentId: 'agent-standard', created: true }); + const insert = statements.find((statement) => + statement.text.startsWith('INSERT INTO app.project_agents'), + ); + expect(insert?.text).toContain('ON CONFLICT (project_id) WHERE managed'); + expect( + statements.some((statement) => + statement.text.includes( + 'project_agent_count = project_agent_count + 1', + ), + ), + ).toBe(true); + expect(createAuditLog).toHaveBeenCalledWith( + tx, + expect.objectContaining({ + metadata: expect.objectContaining({ + op: 'create', + projectAgentId: 'agent-standard', + managed: true, + }), + }), + ); + expect(outbox.emitHintInTx).toHaveBeenCalledTimes(1); + }); + + it('answers the standard agent a concurrent hand-over created, writing nothing more', async () => { + const { tx, statements } = answeringTx((text) => + text.startsWith('SELECT id FROM app.project_agents') + ? [{ id: 'agent-winner' }] + : [], + ); + + await expect( + insertManagedProjectAgent(tx, auth, PROJECT, FIELDS), + ).resolves.toEqual({ agentId: 'agent-winner', created: false }); + expect( + statements.some((statement) => + statement.text.startsWith('UPDATE app.projects'), + ), + ).toBe(false); + expect(createAuditLog).not.toHaveBeenCalled(); + expect(outbox.emitHintInTx).not.toHaveBeenCalled(); + }); + + it('brings its stored settings in line only when they moved, and hints the project then', async () => { + const unchanged = answeringTx(() => []); + await expect( + alignManagedProjectAgent( + unchanged.tx, + { + id: 'agent-standard', + organizationId: 'org_1', + projectId: 'project-1', + }, + FIELDS, + ), + ).resolves.toBe(false); + expect(unchanged.statements[0]?.text).toContain('IS DISTINCT FROM'); + expect(outbox.emitHintInTx).not.toHaveBeenCalled(); + + const moved = answeringTx(() => [{ id: 'agent-standard' }]); + await expect( + alignManagedProjectAgent( + moved.tx, + { + id: 'agent-standard', + organizationId: 'org_1', + projectId: 'project-1', + }, + FIELDS, + ), + ).resolves.toBe(true); + expect(outbox.emitHintInTx).toHaveBeenCalledTimes(1); + }); +}); + describe('updateProjectAgent — equipment the project can no longer see', () => { it('validates only the equipment a save ADDS, so a stored but unshared skill blocks nothing else', async () => { // The agent still names `gone-skill` (unshared from the scope after it diff --git a/services/platform/backend/domains/projects/service.ts b/services/platform/backend/domains/projects/service.ts index 49d3586115..336a9b6df3 100644 --- a/services/platform/backend/domains/projects/service.ts +++ b/services/platform/backend/domains/projects/service.ts @@ -89,7 +89,7 @@ const MAX_PROJECT_AGENTS = 50; * `GET /api/v1/models` lists under `harnesses`. A hard-coded set once stood * beside it, and the refusal named nothing (2026-09-14 evaluation, h9). */ -function eligibleProjectAgentHarnesses(): string[] { +export function eligibleProjectAgentHarnesses(): string[] { return loadHarnesses() .filter((harness) => harness.credentialPolicy.managed) .map((harness) => harness.slug) @@ -1339,6 +1339,10 @@ export interface ProjectAgentRow { tools: string[]; secrets: string[]; instructions: string | null; + /** The organization's standard agent (migration 0146): Tale created it + * and keeps its runtime, model and instructions in line with the + * `standard_agent` policy (`standard-agent.ts`), so nobody edits it here. */ + managed: boolean; createdBy: string; createdAt: number; updatedAt: number; @@ -1347,7 +1351,7 @@ export interface ProjectAgentRow { const PROJECT_AGENT_COLUMNS = ` id, org_id AS "organizationId", project_id AS "projectId", name, harness, model, model_provider AS "modelProvider", skills, connectors, tools, - secrets, instructions, created_by AS "createdBy", + secrets, instructions, managed, created_by AS "createdBy", created_at_ms::float8 AS "createdAt", updated_at_ms::float8 AS "updatedAt" `; @@ -1719,6 +1723,118 @@ export async function createProjectAgent( return agentId; } +/** What the standard agent is made of (`standard-agent.ts` decides it). */ +export interface ManagedProjectAgentFields { + name: string; + harness: string; + model: string; + modelProvider: string; + skills: string[]; + instructions: string; +} + +/** + * Write the organization's standard agent into a project: the managed row, + * the project's agent count, the audit row and the hint, as + * `createProjectAgent` writes a person's agent. The gates are the caller's + * (`ensureStandardAgent`): it may be a Member handing work to a project, so + * no edit right is asked here. Two people handing work to the same project + * at once create one agent — the partial unique index (migration 0146) + * answers the second insert with nothing, and this answers the first's row. + */ +export async function insertManagedProjectAgent( + tx: TransactionSql, + auth: ProjectAuthContext, + project: { id: string; name: string }, + fields: ManagedProjectAgentFields, +): Promise<{ agentId: string; created: boolean }> { + const now = Date.now(); + const inserted = await tx<{ id: string }[]>` + INSERT INTO app.project_agents ( + org_id, project_id, name, harness, model, model_provider, skills, + connectors, tools, secrets, instructions, managed, created_by, + created_at_ms, updated_at_ms + ) VALUES ( + ${auth.organizationId}, ${project.id}, ${fields.name}, + ${fields.harness}, ${fields.model}, ${fields.modelProvider}, + ${fields.skills}, ${[]}, ${[]}, ${[]}, ${fields.instructions}, true, + ${auth.userId}, ${now}, ${now} + ) + ON CONFLICT (project_id) WHERE managed DO NOTHING + RETURNING id + `; + const agentId = inserted[0]?.id; + if (agentId === undefined) { + const standing = await tx<{ id: string }[]>` + SELECT id FROM app.project_agents + WHERE project_id = ${project.id} AND managed + LIMIT 1 + `; + const existing = standing[0]?.id; + if (existing === undefined) { + throw new Error( + 'PROJECT_AGENT_CREATE_FAILED: the standard agent insert answered no row and none stands', + ); + } + return { agentId: existing, created: false }; + } + await tx` + UPDATE app.projects SET + project_agent_count = project_agent_count + 1, updated_at_ms = ${now} + WHERE id = ${project.id} + `; + await createAuditLog( + tx, + projectAudit(auth, project, PROJECT_AUDIT_ACTIONS.agentsChanged, { + newState: { + name: fields.name, + harness: fields.harness, + model: fields.model, + skills: fields.skills, + }, + metadata: { op: 'create', projectAgentId: agentId, managed: true }, + }), + ); + await hintProject(tx, auth.organizationId, project.id); + return { agentId, created: true }; +} + +/** + * Bring a standard agent's stored settings in line with what the policy + * resolved for a run (`standard-agent.ts`), so its row — the Agents tab, the + * run card, the next run's resume plan — says what actually runs. Writes + * only on a difference, and no audit row: this is the organization's own + * setting applied, not a person's edit (the policy save audits that). + */ +export async function alignManagedProjectAgent( + tx: TransactionSql, + agent: { + id: string; + organizationId: string; + projectId: string; + }, + fields: Pick< + ManagedProjectAgentFields, + 'harness' | 'model' | 'modelProvider' | 'instructions' + >, +): Promise { + const changed = await tx<{ id: string }[]>` + UPDATE app.project_agents SET + harness = ${fields.harness}, model = ${fields.model}, + model_provider = ${fields.modelProvider}, + instructions = ${fields.instructions}, updated_at_ms = ${Date.now()} + WHERE id = ${agent.id} AND managed + AND (harness IS DISTINCT FROM ${fields.harness} + OR model IS DISTINCT FROM ${fields.model} + OR model_provider IS DISTINCT FROM ${fields.modelProvider} + OR instructions IS DISTINCT FROM ${fields.instructions}) + RETURNING id + `; + if (changed.length === 0) return false; + await hintProject(tx, agent.organizationId, agent.projectId); + return true; +} + export async function updateProjectAgent( tx: TransactionSql, auth: ProjectAuthContext, @@ -1750,6 +1866,15 @@ export async function updateProjectAgent( if (!agent) { throw new ProjectError('PROJECT_AGENT_NOT_FOUND', 'Agent not found', 404); } + if (agent.managed) { + // Its settings are the organization's: a hand edit would be undone at + // the next start (`standard-agent.ts`), so it is refused instead. + throw new ProjectError( + 'PROJECT_AGENT_MANAGED', + "This is the organization's standard agent: its runtime, model and instructions follow the organization's settings, which an Owner or Admin changes under Governance", + 409, + ); + } if ( args.expectedUpdatedAt !== undefined && args.expectedUpdatedAt !== agent.updatedAt diff --git a/services/platform/backend/domains/projects/standard-agent.integration.ts b/services/platform/backend/domains/projects/standard-agent.integration.ts new file mode 100644 index 0000000000..4bdc52b616 --- /dev/null +++ b/services/platform/backend/domains/projects/standard-agent.integration.ts @@ -0,0 +1,294 @@ +/** Real Postgres proof of the organization's standard agent (migration 0146, + * the `standard_agent` policy): + * + * - `project_agents.managed` is the migration's boolean, false by default, + * and at most one managed agent stands per project (its partial unique + * index); + * - two hand-overs to the same project at the same moment create one agent, + * count it once, and both answer it; + * - nobody edits the standard agent: a save answers `PROJECT_AGENT_MANAGED` + * and writes nothing; + * - a project with agents of its own is left to them + * (`STANDARD_AGENT_NOT_NEEDED`); + * - switched off, the standard agent is created nowhere and starts nothing + * (`STANDARD_AGENT_OFF`, no run row), and a policy file that does not + * parse reads as unavailable, never as on. + * + * The lane resolves no model: creating one through the door needs a + * servable model, which the policy's own unit tests and the live rig cover. */ +import { randomUUID } from 'node:crypto'; +import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { transactSerializable } from '@tale/shared/db/serializable'; +import type { Sql } from 'postgres'; + +import { resolveOrgSlug } from '../../lib/org-config.ts'; +import { kickAgentRun } from '../tasks/agent-runs.ts'; +import { + getProjectAuthContext, + insertManagedProjectAgent, + updateProjectAgent, +} from './service.ts'; +import { ensureStandardAgent } from './standard-agent.ts'; + +type Recorder = (name: string, ok: boolean, detail: string) => void; + +function codeOf(error: unknown): string { + return typeof error === 'object' && + error !== null && + 'code' in error && + typeof error.code === 'string' + ? error.code + : String(error); +} + +function reasonOf(error: unknown): string | undefined { + if (typeof error !== 'object' || error === null || !('data' in error)) { + return undefined; + } + const data: unknown = error.data; + return typeof data === 'object' && + data !== null && + 'reason' in data && + typeof data.reason === 'string' + ? data.reason + : undefined; +} + +export async function checkStandardAgent( + sql: Sql, + ctx: { orgId: string; userId: string }, + record: Recorder, +): Promise { + const { orgId, userId } = ctx; + const projectId = randomUUID(); + const curatedProjectId = randomUUID(); + const emptyProjectId = randomUUID(); + const now = Date.now(); + + const slug = await resolveOrgSlug(sql, orgId); + if (!slug || !process.env.TALE_CONFIG_DIR) { + throw new Error('Missing isolated policy fixture root'); + } + const directory = path.join(process.env.TALE_CONFIG_DIR, slug, 'governance'); + await mkdir(directory, { recursive: true }); + const policy = path.join(directory, 'standard-agent.yml'); + const previous = await readFile(policy).catch((error: unknown) => { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { + return null; + } + throw error; + }); + + try { + for (const [id, name] of [ + [projectId, 'Standard agent lane'], + [curatedProjectId, 'Standard agent lane (curated)'], + [emptyProjectId, 'Standard agent lane (empty)'], + ] as const) { + await sql` + INSERT INTO app.projects (id, org_id, name, created_by, created_at_ms, + updated_at_ms) + VALUES (${id}, ${orgId}, ${name}, ${userId}, ${now}, ${now}) + `; + } + await sql` + INSERT INTO app.project_agents (org_id, project_id, name, harness, model, + created_by, created_at_ms, updated_at_ms) + VALUES (${orgId}, ${curatedProjectId}, 'Curated', 'claude-code', + 'lane-model', ${userId}, ${now}, ${now}) + `; + + // ---- the migration's shape --------------------------------------------- + const column = await sql< + { type: string; nullable: string; fallback: string | null }[] + >` + SELECT data_type AS type, is_nullable AS nullable, + column_default AS fallback + FROM information_schema.columns + WHERE table_schema = 'app' AND table_name = 'project_agents' + AND column_name = 'managed' + `; + const index = await sql<{ definition: string }[]>` + SELECT indexdef AS definition FROM pg_indexes + WHERE schemaname = 'app' AND tablename = 'project_agents' + AND indexname = 'project_agents_one_managed' + `; + record( + 'standard agent: managed is the migration’s boolean, one per project', + column[0]?.type === 'boolean' && + column[0].nullable === 'NO' && + column[0].fallback === 'false' && + (index[0]?.definition.includes('UNIQUE') ?? false) && + (index[0]?.definition.includes('WHERE managed') ?? false), + `column=${JSON.stringify(column)} index=${index[0]?.definition ?? 'missing'}`, + ); + + // ---- two hand-overs at once -------------------------------------------- + const auth = await getProjectAuthContext(sql, { + organizationId: orgId, + userId, + role: 'owner', + }); + const fields = { + name: 'Standard agent', + harness: 'claude-code', + model: 'lane-model', + modelProvider: 'lane-provider', + skills: [] as string[], + instructions: 'Do the task.', + }; + const project = { id: projectId, name: 'Standard agent lane' }; + const [first, second] = await Promise.all([ + transactSerializable(sql, (tx) => + insertManagedProjectAgent(tx, auth, project, fields), + ), + transactSerializable(sql, (tx) => + insertManagedProjectAgent(tx, auth, project, fields), + ), + ]); + const managedRows = await sql<{ id: string }[]>` + SELECT id FROM app.project_agents + WHERE project_id = ${projectId} AND managed + `; + const counted = await sql<{ count: number }[]>` + SELECT project_agent_count AS count FROM app.projects + WHERE id = ${projectId} + `; + record( + 'standard agent: two hand-overs at once create one agent, counted once, and both answer it', + managedRows.length === 1 && + first.agentId === second.agentId && + first.agentId === managedRows[0]?.id && + [first.created, second.created].filter(Boolean).length === 1 && + counted[0]?.count === 1, + `rows=${managedRows.length} first=${JSON.stringify(first)} second=${JSON.stringify(second)} count=${counted[0]?.count}`, + ); + + // ---- nobody edits it --------------------------------------------------- + let editRefusal = ''; + try { + await transactSerializable(sql, (tx) => + updateProjectAgent(tx, auth, { + agentId: first.agentId, + name: 'Renamed by hand', + harness: 'codex', + model: 'other-model', + skills: [], + connectors: [], + }), + ); + } catch (error) { + editRefusal = codeOf(error); + } + const afterEdit = await sql<{ name: string; harness: string }[]>` + SELECT name, harness FROM app.project_agents WHERE id = ${first.agentId} + `; + record( + 'standard agent: a save of it answers PROJECT_AGENT_MANAGED and writes nothing', + editRefusal === 'PROJECT_AGENT_MANAGED' && + afterEdit[0]?.name === 'Standard agent' && + afterEdit[0].harness === 'claude-code', + `refusal=${editRefusal} row=${JSON.stringify(afterEdit[0])}`, + ); + + // ---- a project with agents of its own ---------------------------------- + let curatedRefusal = ''; + try { + await transactSerializable(sql, (tx) => + ensureStandardAgent(tx, auth, curatedProjectId), + ); + } catch (error) { + curatedRefusal = codeOf(error); + } + const curatedManaged = await sql<{ id: string }[]>` + SELECT id FROM app.project_agents + WHERE project_id = ${curatedProjectId} AND managed + `; + record( + 'standard agent: a project with agents of its own is left to them', + curatedRefusal === 'STANDARD_AGENT_NOT_NEEDED' && + curatedManaged.length === 0, + `refusal=${curatedRefusal} managed=${curatedManaged.length}`, + ); + + // ---- switched off ------------------------------------------------------ + await writeFile(policy, 'enabled: false\n'); + let offEnsure = ''; + try { + await transactSerializable(sql, (tx) => + ensureStandardAgent(tx, auth, emptyProjectId), + ); + } catch (error) { + offEnsure = codeOf(error); + } + const taskId = randomUUID(); + await sql` + INSERT INTO app.tasks (id, org_id, project_id, title, status, rank, + assignee_type, assignee_id, created_by, created_by_type, + created_at_ms, updated_at_ms) + VALUES (${taskId}, ${orgId}, ${projectId}, 'Standard agent lane task', + 'in_progress', ${taskId}, 'agent', ${first.agentId}, ${userId}, 'user', + ${now}, ${now}) + `; + let offKick = ''; + try { + await transactSerializable(sql, (tx) => + kickAgentRun(tx, { + organizationId: orgId, + projectId, + taskId, + agentId: first.agentId, + harness: 'claude-code', + model: 'lane-model', + startedBy: userId, + }), + ); + } catch (error) { + offKick = codeOf(error); + } + const offRows = await sql<{ id: string }[]>` + SELECT id FROM app.project_agents + WHERE project_id = ${emptyProjectId} + `; + const runs = await sql<{ id: string }[]>` + SELECT id FROM app.project_agent_runs WHERE task_id = ${taskId} + `; + record( + 'standard agent: switched off, it is created nowhere and starts nothing', + offEnsure === 'STANDARD_AGENT_OFF' && + offKick === 'STANDARD_AGENT_OFF' && + offRows.length === 0 && + runs.length === 0, + `ensure=${offEnsure} kick=${offKick} rows=${offRows.length} runs=${runs.length}`, + ); + + // ---- a policy file that does not parse --------------------------------- + await writeFile(policy, 'enabled: perhaps\n'); + let unreadable = ''; + let unreadableReason: string | undefined; + try { + await transactSerializable(sql, (tx) => + ensureStandardAgent(tx, auth, emptyProjectId), + ); + } catch (error) { + unreadable = codeOf(error); + unreadableReason = reasonOf(error); + } + record( + 'standard agent: a policy file that does not parse reads as unavailable, never as on', + unreadable === 'STANDARD_AGENT_UNAVAILABLE' && + unreadableReason === 'unreadable', + `refusal=${unreadable} reason=${unreadableReason ?? 'none'}`, + ); + } finally { + // Cascades to their agents, tasks and runs. + await sql` + DELETE FROM app.projects + WHERE id IN ${sql([projectId, curatedProjectId, emptyProjectId])} + `; + if (previous === null) await rm(policy, { force: true }); + else await writeFile(policy, previous); + } +} diff --git a/services/platform/backend/domains/projects/standard-agent.test.ts b/services/platform/backend/domains/projects/standard-agent.test.ts new file mode 100644 index 0000000000..27881a351f --- /dev/null +++ b/services/platform/backend/domains/projects/standard-agent.test.ts @@ -0,0 +1,472 @@ +// @vitest-environment node +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { ComposerModelOption } from '../../core/chat/composer.ts'; + +const { + readGovernancePolicyForOrg, + listGovernedChatModels, + listProjectCapabilities, + alignManagedProjectAgent, + insertManagedProjectAgent, + loadProjectOrThrow, +} = vi.hoisted(() => ({ + readGovernancePolicyForOrg: vi.fn(), + listGovernedChatModels: vi.fn(), + listProjectCapabilities: vi.fn(), + alignManagedProjectAgent: vi.fn(), + insertManagedProjectAgent: vi.fn(), + loadProjectOrThrow: vi.fn(), +})); + +vi.mock('../../lib/org-config.ts', () => ({ readGovernancePolicyForOrg })); +vi.mock('../chat/composer.ts', () => ({ + listGovernedChatModels, + listProjectCapabilities, +})); +// Wholly stood in, never `importOriginal`: the real service reaches the kick +// through the task domain (retire → agent runs → this module), and loading +// it here would bind this module to the unmocked service. +vi.mock('./service.ts', () => { + class ProjectError extends Error { + constructor( + readonly code: string, + message: string, + readonly status = 400, + readonly data?: Record, + ) { + super(message); + } + } + return { + ProjectError, + alignManagedProjectAgent, + insertManagedProjectAgent, + loadProjectOrThrow, + assertReadable: () => undefined, + assertProjectActive: (project: { archivedAt: number | null }) => { + if (project.archivedAt !== null) { + throw new ProjectError('PROJECT_ARCHIVED', 'Project is archived', 403); + } + }, + eligibleProjectAgentHarnesses: () => ['claude-code', 'codex', 'opencode'], + }; +}); + +import { ProjectError } from './service.ts'; +import { + chooseStandardAgentServing, + ensureStandardAgent, + STANDARD_AGENT_DEFAULT_INSTRUCTIONS, + standardAgentServingForKick, +} from './standard-agent.ts'; + +const ELIGIBLE = ['claude-code', 'codex', 'opencode']; + +function option( + id: string, + providerSlug: string, + overrides: Partial = {}, +): ComposerModelOption { + return { + id, + label: id, + providerSlug, + providerLabel: providerSlug, + credential: { authMethod: 'api-key' }, + tools: true, + contextWindow: 200_000, + pricing: { inputCentsPerMillion: 100, outputCentsPerMillion: 500 }, + tags: ['chat'], + ...overrides, + }; +} + +function subscription( + id: string, + providerSlug: string, + harness: string, +): ComposerModelOption { + return option(id, providerSlug, { + credential: { + authMethod: 'subscription-key', + constraints: { harness, execution: 'sandbox' }, + }, + }); +} + +describe('chooseStandardAgentServing — what runs the standard agent', () => { + it('runs automatically on Claude Code with the chat Auto choice for document work', () => { + const serving = chooseStandardAgentServing( + [ + option('cheap-model', 'openrouter', { + pricing: { inputCentsPerMillion: 1, outputCentsPerMillion: 2 }, + }), + option('claude-sonnet-5', 'anthropic'), + ], + {}, + ELIGIBLE, + ); + + expect(serving).toEqual({ + ok: true, + harness: 'claude-code', + model: 'claude-sonnet-5', + modelProvider: 'anthropic', + source: 'preferred', + }); + }); + + it('falls back to the cheapest servable model when no curated one is reachable', () => { + const serving = chooseStandardAgentServing( + [ + option('pricey', 'acme', { + pricing: { inputCentsPerMillion: 100, outputCentsPerMillion: 900 }, + }), + option('modest', 'acme', { + pricing: { inputCentsPerMillion: 10, outputCentsPerMillion: 40 }, + }), + ], + {}, + ELIGIBLE, + ); + + expect(serving).toMatchObject({ + ok: true, + model: 'modest', + source: 'cheapest', + }); + }); + + it('runs a subscription-only organization on the runtime its subscription is bound to', () => { + const serving = chooseStandardAgentServing( + [subscription('gpt-5.5', 'openai', 'codex')], + {}, + ELIGIBLE, + ); + + expect(serving).toMatchObject({ + ok: true, + harness: 'codex', + model: 'gpt-5.5', + modelProvider: 'openai', + }); + }); + + it('keeps a pinned runtime and chooses among what it can run', () => { + const serving = chooseStandardAgentServing( + [ + subscription('claude-sonnet-5', 'anthropic', 'claude-code'), + option('gpt-5.5', 'openai'), + ], + { harness: 'codex' }, + ELIGIBLE, + ); + + expect(serving).toMatchObject({ + ok: true, + harness: 'codex', + model: 'gpt-5.5', + }); + }); + + it('uses a pinned model as pinned — on the default runtime, or the one its subscription needs', () => { + expect( + chooseStandardAgentServing( + [option('gpt-5.5', 'openai'), option('claude-sonnet-5', 'anthropic')], + { providerSlug: 'openai', modelId: 'gpt-5.5' }, + ELIGIBLE, + ), + ).toEqual({ + ok: true, + harness: 'claude-code', + model: 'gpt-5.5', + modelProvider: 'openai', + source: 'pinned', + }); + expect( + chooseStandardAgentServing( + [subscription('gpt-5.5', 'openai', 'codex')], + { providerSlug: 'openai', modelId: 'gpt-5.5' }, + ELIGIBLE, + ), + ).toMatchObject({ ok: true, harness: 'codex', source: 'pinned' }); + }); + + it('refuses a pin it cannot run, and never swaps in another model', () => { + expect( + chooseStandardAgentServing( + [option('claude-sonnet-5', 'anthropic')], + { providerSlug: 'openai', modelId: 'gpt-5.5' }, + ELIGIBLE, + ), + ).toEqual({ ok: false, refusal: 'pin-unavailable' }); + expect( + chooseStandardAgentServing( + [subscription('claude-sonnet-5', 'anthropic', 'claude-code')], + { + harness: 'codex', + providerSlug: 'anthropic', + modelId: 'claude-sonnet-5', + }, + ELIGIBLE, + ), + ).toEqual({ ok: false, refusal: 'pin-unavailable' }); + }); + + it('refuses a runtime a project agent may not use, and an organization with nothing to run', () => { + expect( + chooseStandardAgentServing( + [option('gpt-5.5', 'openai')], + { harness: 'cursor' }, + ELIGIBLE, + ), + ).toEqual({ ok: false, refusal: 'harness-invalid' }); + expect(chooseStandardAgentServing([], {}, ELIGIBLE)).toEqual({ + ok: false, + refusal: 'no-model', + }); + expect( + chooseStandardAgentServing( + [subscription('claude-sonnet-5', 'anthropic', 'claude-code')], + { harness: 'codex' }, + ELIGIBLE, + ), + ).toEqual({ ok: false, refusal: 'no-model' }); + }); +}); + +/** A transaction stand-in answering the module's few reads by their text. */ +function fakeTx(answer: (query: string) => unknown[]) { + const queries: string[] = []; + const tx = (strings: TemplateStringsArray) => { + const query = strings.join('?'); + queries.push(query); + return Promise.resolve(answer(query)); + }; + return { tx: tx as never, queries }; +} + +beforeEach(() => { + vi.clearAllMocks(); + listGovernedChatModels.mockResolvedValue([ + option('claude-sonnet-5', 'anthropic'), + ]); +}); + +describe('standardAgentServingForKick — the policy, at every start', () => { + const args = { + organizationId: 'org-1', + agentId: 'agent-1', + startedBy: 'member-1', + harness: 'codex', + model: 'stale-model', + modelProvider: 'openai', + }; + const managedRow = (query: string) => + query.includes('FROM app.project_agents') + ? [{ managed: true, projectId: 'project-1', createdBy: 'editor-1' }] + : []; + + it('starts any other agent exactly as its caller read it', async () => { + const { tx } = fakeTx((query) => + query.includes('FROM app.project_agents') + ? [{ managed: false, projectId: 'project-1', createdBy: 'editor-1' }] + : [], + ); + + await expect(standardAgentServingForKick(tx, args)).resolves.toEqual({ + harness: 'codex', + model: 'stale-model', + modelProvider: 'openai', + }); + expect(readGovernancePolicyForOrg).not.toHaveBeenCalled(); + expect(alignManagedProjectAgent).not.toHaveBeenCalled(); + }); + + it('runs the standard agent on what the policy says now, for the starter, and writes it back', async () => { + readGovernancePolicyForOrg.mockResolvedValue(null); + const { tx } = fakeTx(managedRow); + + await expect(standardAgentServingForKick(tx, args)).resolves.toEqual({ + harness: 'claude-code', + model: 'claude-sonnet-5', + modelProvider: 'anthropic', + }); + expect(listGovernedChatModels).toHaveBeenCalledWith(expect.anything(), { + organizationId: 'org-1', + userId: 'member-1', + }); + expect(alignManagedProjectAgent).toHaveBeenCalledWith( + expect.anything(), + { id: 'agent-1', organizationId: 'org-1', projectId: 'project-1' }, + { + harness: 'claude-code', + model: 'claude-sonnet-5', + modelProvider: 'anthropic', + instructions: STANDARD_AGENT_DEFAULT_INSTRUCTIONS, + }, + ); + }); + + it('resolves a scheduled start for the agent’s creator, and carries the policy’s instructions', async () => { + readGovernancePolicyForOrg.mockResolvedValue({ + enabled: true, + instructions: 'Use the house style.', + }); + const { tx } = fakeTx(managedRow); + + await standardAgentServingForKick(tx, { + ...args, + startedBy: 'trigger:nightly', + }); + + expect(listGovernedChatModels).toHaveBeenCalledWith(expect.anything(), { + organizationId: 'org-1', + userId: 'editor-1', + }); + expect(alignManagedProjectAgent).toHaveBeenCalledWith( + expect.anything(), + expect.anything(), + expect.objectContaining({ instructions: 'Use the house style.' }), + ); + }); + + it('refuses while switched off, and names why it cannot run otherwise', async () => { + readGovernancePolicyForOrg.mockResolvedValue({ enabled: false }); + const off = await standardAgentServingForKick( + fakeTx(managedRow).tx, + args, + ).catch((error: unknown) => error); + expect(off).toBeInstanceOf(ProjectError); + expect(off).toMatchObject({ code: 'STANDARD_AGENT_OFF', status: 403 }); + + readGovernancePolicyForOrg.mockResolvedValue({ + enabled: true, + providerSlug: 'openai', + modelId: 'gpt-5.5', + }); + const pinned = await standardAgentServingForKick( + fakeTx(managedRow).tx, + args, + ).catch((error: unknown) => error); + expect(pinned).toMatchObject({ + code: 'STANDARD_AGENT_UNAVAILABLE', + status: 409, + data: { reason: 'pin-unavailable' }, + }); + expect(alignManagedProjectAgent).not.toHaveBeenCalled(); + }); + + it('refuses a policy file it cannot read instead of reading it as on', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + readGovernancePolicyForOrg.mockRejectedValue(new Error('malformed')); + + await expect( + standardAgentServingForKick(fakeTx(managedRow).tx, args), + ).rejects.toMatchObject({ + code: 'STANDARD_AGENT_UNAVAILABLE', + data: { reason: 'unreadable' }, + }); + expect(warn).toHaveBeenCalledTimes(1); + warn.mockRestore(); + }); +}); + +describe('ensureStandardAgent — the door a Member hands a project work through', () => { + const auth = { + organizationId: 'org-1', + userId: 'member-1', + role: 'member', + teamIds: [], + }; + + beforeEach(() => { + loadProjectOrThrow.mockResolvedValue({ + id: 'project-1', + organizationId: 'org-1', + name: 'Getting started', + archivedAt: null, + teamIds: [], + }); + listProjectCapabilities.mockResolvedValue({ + skills: [{ slug: 'docx' }, { slug: 'pdf' }, { slug: 'brief-summary' }], + connectors: [], + }); + insertManagedProjectAgent.mockResolvedValue({ + agentId: 'agent-new', + created: true, + }); + }); + + it('creates it in a project without agents, with the document skills the project sees and a name in the organization’s language', async () => { + readGovernancePolicyForOrg.mockResolvedValue(null); + const { tx } = fakeTx((query) => + query.includes('FROM "organization"') + ? [{ metadata: { defaultLocale: 'de' } }] + : [], + ); + + await expect(ensureStandardAgent(tx, auth, 'project-1')).resolves.toEqual({ + agentId: 'agent-new', + created: true, + }); + expect(insertManagedProjectAgent).toHaveBeenCalledWith( + expect.anything(), + auth, + expect.objectContaining({ id: 'project-1' }), + { + name: 'Standard-Agent', + harness: 'claude-code', + model: 'claude-sonnet-5', + modelProvider: 'anthropic', + skills: ['docx', 'pdf'], + instructions: STANDARD_AGENT_DEFAULT_INSTRUCTIONS, + }, + ); + }); + + it('answers the standing standard agent, and leaves a project with its own agents to them', async () => { + const standing = fakeTx((query) => + query.includes('FROM app.project_agents') + ? [{ id: 'agent-standing', managed: true }] + : [], + ); + await expect( + ensureStandardAgent(standing.tx, auth, 'project-1'), + ).resolves.toEqual({ agentId: 'agent-standing', created: false }); + + const curated = fakeTx((query) => + query.includes('FROM app.project_agents') + ? [{ id: 'agent-curated', managed: false }] + : [], + ); + await expect( + ensureStandardAgent(curated.tx, auth, 'project-1'), + ).rejects.toMatchObject({ code: 'STANDARD_AGENT_NOT_NEEDED', status: 409 }); + expect(insertManagedProjectAgent).not.toHaveBeenCalled(); + }); + + it('creates nothing while the organization switched it off', async () => { + readGovernancePolicyForOrg.mockResolvedValue({ enabled: false }); + + await expect( + ensureStandardAgent(fakeTx(() => []).tx, auth, 'project-1'), + ).rejects.toMatchObject({ code: 'STANDARD_AGENT_OFF' }); + expect(insertManagedProjectAgent).not.toHaveBeenCalled(); + }); + + it('refuses an archived project', async () => { + loadProjectOrThrow.mockResolvedValue({ + id: 'project-1', + organizationId: 'org-1', + name: 'Getting started', + archivedAt: 1, + teamIds: [], + }); + + await expect( + ensureStandardAgent(fakeTx(() => []).tx, auth, 'project-1'), + ).rejects.toMatchObject({ code: 'PROJECT_ARCHIVED' }); + }); +}); diff --git a/services/platform/backend/domains/projects/standard-agent.ts b/services/platform/backend/domains/projects/standard-agent.ts new file mode 100644 index 0000000000..8ec8766e6b --- /dev/null +++ b/services/platform/backend/domains/projects/standard-agent.ts @@ -0,0 +1,482 @@ +import type { StandardAgentConfig } from '@tale/shared/schemas/governance'; +import type { Sql, TransactionSql } from 'postgres'; + +import { + type ChatChoiceEntry, + chooseChatModel, + eligibleChatCandidates, +} from '../../../lib/chat/model-choice.ts'; +import { DOCUMENT_SKILL_SLUGS } from '../../../lib/shared/document-skills.ts'; +import { getOrganizationDefaultLocale } from '../../../lib/shared/utils/get-organization-default-locale.ts'; +import type { ComposerModelOption } from '../../core/chat/composer.ts'; +import { catalogString } from '../../core/i18n/catalog.ts'; +import { loadHarnesses } from '../../core/lib/providers/load_system_config.ts'; +import { readGovernancePolicyForOrg } from '../../lib/org-config.ts'; +import { + listGovernedChatModels, + listProjectCapabilities, +} from '../chat/composer.ts'; +import { + alignManagedProjectAgent, + assertProjectActive, + assertReadable, + eligibleProjectAgentHarnesses, + insertManagedProjectAgent, + loadProjectOrThrow, + ProjectError, + type ProjectAuthContext, +} from './service.ts'; + +/** + * The organization's standard agent: the project agent Tale provides in + * every project that has none of its own, so work can go to an agent before + * anyone sets one up — without it a Member, who cannot create agents, had + * nowhere to hand a file task in such a project. + * + * The `standard_agent` governance policy decides it (on by default; runtime + * and model automatic unless an Admin pins them). The agent itself is a + * real `app.project_agents` row marked `managed` (migration 0146), created + * the first time someone hands work to the project (`ensureStandardAgent`), + * so every path that runs, mentions or lists an agent works unchanged; and + * whenever a run starts, the kick resolves the policy again and runs what it + * says now (`standardAgentServingForKick`), writing any change back to the + * row. + * + * "Automatic" is resolved for the person the run acts for: the models they + * may use (governance model access applied), chosen by the chat's own Auto + * rules at the band document work gets. A pinned model is used or refused, + * never replaced by another. + */ + +/** The runtime an automatic standard agent runs on: the one automation + * agent steps default to, and able to run any directly served model through + * the gateway. */ +const STANDARD_AGENT_DEFAULT_HARNESS = 'claude-code'; + +/** The standing instructions a standard agent works with unless the policy + * replaces them. General on purpose: it is every project's agent until the + * project gets its own. */ +export const STANDARD_AGENT_DEFAULT_INSTRUCTIONS = [ + "You are this organization's standard agent: the agent a project's tasks go to until the project has agents of its own.", + 'Do what the task asks, using the files attached to it and its comments. When it asks for a file — a document, a presentation, a spreadsheet, a PDF — deliver that file as a task output, in the format it asks for.', + 'Write in the language of the task. Close with a comment that says what you did and what is still open.', + 'When the task is unclear or needs a decision you cannot make, ask in a comment instead of guessing.', +].join('\n\n'); + +/** Why the standard agent cannot run. */ +export type StandardAgentRefusal = + /** The organization switched it off. */ + | 'off' + /** Its policy file cannot be read, or does not parse. */ + | 'unreadable' + /** The pinned runtime is not one a project agent may run on. */ + | 'harness-invalid' + /** Nothing this person may use can run it. */ + | 'no-model' + /** The pinned model is not one this person may use, or its runtime + * cannot run it. */ + | 'pin-unavailable'; + +export type StandardAgentServing = + | { + ok: true; + harness: string; + model: string; + modelProvider: string; + /** Where the model came from — the pin, or the automatic choice. */ + source: 'pinned' | 'preferred' | 'cheapest'; + } + | { + ok: false; + refusal: Exclude; + }; + +/** + * The policy as it stands, or `unreadable`. A missing file is the default — + * on, everything automatic. Read strictly (fresh from disk): the kick, the + * availability read and the ensure door must agree, and a broken file must + * never read as "on with defaults". + */ +export async function readStandardAgentPolicy( + sql: Sql | TransactionSql, + organizationId: string, +): Promise { + try { + const policy = await readGovernancePolicyForOrg( + sql, + organizationId, + 'standard_agent', + { strict: true }, + ); + return policy ?? { enabled: true }; + } catch (error) { + console.warn( + `[standard-agent] policy unreadable for organization ${organizationId}:`, + error instanceof Error ? error.message : error, + ); + return 'unreadable'; + } +} + +/** The runtime a subscription-served option is bound to; `undefined` for a + * directly served (api-key/env) option, which any runtime can run. */ +function boundHarness(option: ComposerModelOption): string | undefined { + const credential = option.credential; + return credential.authMethod === 'api-key' || credential.authMethod === 'env' + ? undefined + : credential.constraints.harness; +} + +/** + * What runs the standard agent, from the models a person may use. Pure: the + * listing and the eligible runtimes in, the choice or the refusal out. + */ +export function chooseStandardAgentServing( + options: readonly ComposerModelOption[], + config: Pick, + eligibleHarnesses: readonly string[], +): StandardAgentServing { + if ( + config.harness !== undefined && + !eligibleHarnesses.includes(config.harness) + ) { + return { ok: false, refusal: 'harness-invalid' }; + } + const defaultHarness = eligibleHarnesses.includes( + STANDARD_AGENT_DEFAULT_HARNESS, + ) + ? STANDARD_AGENT_DEFAULT_HARNESS + : eligibleHarnesses[0]; + const runnable = (option: ComposerModelOption, harness: string) => { + const bound = boundHarness(option); + return bound === undefined || bound === harness; + }; + + if (config.providerSlug !== undefined && config.modelId !== undefined) { + const pinned = options.filter( + (option) => + option.providerSlug === config.providerSlug && + option.id === config.modelId, + ); + const direct = pinned.some((option) => boundHarness(option) === undefined); + const harness = + config.harness ?? + (direct ? defaultHarness : pinned.map(boundHarness).find(Boolean)); + if ( + harness === undefined || + !eligibleHarnesses.includes(harness) || + !pinned.some((option) => runnable(option, harness)) + ) { + return { ok: false, refusal: 'pin-unavailable' }; + } + return { + ok: true, + harness, + model: config.modelId, + modelProvider: config.providerSlug, + source: 'pinned', + }; + } + + // Automatic: with a runtime pinned, what it can run; otherwise the directly + // served models (the default runtime runs any of them), and only when there + // are none, a subscription's model on the runtime it is bound to. + let pool: readonly ComposerModelOption[]; + if (config.harness !== undefined) { + const pinnedHarness = config.harness; + pool = options.filter((option) => runnable(option, pinnedHarness)); + } else { + const direct = options.filter( + (option) => boundHarness(option) === undefined, + ); + pool = + direct.length > 0 && defaultHarness !== undefined + ? direct + : options.filter((option) => { + const bound = boundHarness(option); + return bound !== undefined && eligibleHarnesses.includes(bound); + }); + } + const screened = eligibleChatCandidates( + pool.map((option) => { + const entry: ChatChoiceEntry & { option: ComposerModelOption } = { + id: option.id, + provider: option.providerSlug, + tags: [...option.tags], + supportsTools: option.tools, + supportsVision: option.vision === true, + option, + }; + if (option.pricing !== undefined) entry.pricing = option.pricing; + return entry; + }), + { requiresVision: false }, + ); + if ('refusal' in screened) return { ok: false, refusal: 'no-model' }; + // Document work is the standard agent's everyday task: the band the chat's + // Auto floors document work at. + const choice = chooseChatModel(screened.pool, 'standard'); + if (choice === null) return { ok: false, refusal: 'no-model' }; + const harness = + config.harness ?? boundHarness(choice.entry.option) ?? defaultHarness; + if (harness === undefined) return { ok: false, refusal: 'harness-invalid' }; + return { + ok: true, + harness, + model: choice.entry.id, + modelProvider: choice.entry.provider, + source: choice.source, + }; +} + +/** What runs the standard agent for this person, under this policy. */ +export async function resolveStandardAgentServing( + sql: Sql | TransactionSql, + args: { + organizationId: string; + userId: string; + config: StandardAgentConfig; + }, +): Promise { + const eligible = eligibleProjectAgentHarnesses(); + if ( + args.config.harness !== undefined && + !eligible.includes(args.config.harness) + ) { + return { ok: false, refusal: 'harness-invalid' }; + } + const options = await listGovernedChatModels(sql as Sql, { + organizationId: args.organizationId, + userId: args.userId, + }); + return chooseStandardAgentServing(options, args.config, eligible); +} + +/** Whether this person can hand work to the standard agent now, and what + * it would run on — the picker, the chat's hand-over, the Agents tab and + * the governance page all read this. */ +export interface StandardAgentAvailability { + enabled: boolean; + available: boolean; + refusal?: StandardAgentRefusal; + harness?: string; + harnessLabel?: string; + model?: string; + modelLabel?: string; + modelProvider?: string; + source?: 'pinned' | 'preferred' | 'cheapest'; +} + +export async function readStandardAgentAvailability( + sql: Sql, + args: { organizationId: string; userId: string }, +): Promise { + const config = await readStandardAgentPolicy(sql, args.organizationId); + if (config === 'unreadable') { + return { enabled: false, available: false, refusal: 'unreadable' }; + } + if (!config.enabled) { + return { enabled: false, available: false, refusal: 'off' }; + } + const eligible = eligibleProjectAgentHarnesses(); + const options = + config.harness !== undefined && !eligible.includes(config.harness) + ? [] + : await listGovernedChatModels(sql, args); + const serving = chooseStandardAgentServing(options, config, eligible); + if (!serving.ok) { + return { enabled: true, available: false, refusal: serving.refusal }; + } + const harnessLabel = loadHarnesses().find( + (harness) => harness.slug === serving.harness, + )?.displayName; + const modelLabel = options.find( + (option) => + option.id === serving.model && + option.providerSlug === serving.modelProvider, + )?.label; + return { + enabled: true, + available: true, + harness: serving.harness, + ...(harnessLabel !== undefined ? { harnessLabel } : {}), + model: serving.model, + ...(modelLabel !== undefined ? { modelLabel } : {}), + modelProvider: serving.modelProvider, + source: serving.source, + }; +} + +/** The refusal a door answers when the standard agent cannot be used. */ +function refusalError(refusal: StandardAgentRefusal): ProjectError { + return refusal === 'off' + ? new ProjectError( + 'STANDARD_AGENT_OFF', + "The organization's standard agent is switched off. An Owner or Admin can switch it on under Governance.", + 403, + ) + : new ProjectError( + 'STANDARD_AGENT_UNAVAILABLE', + refusal === 'unreadable' + ? "The organization's standard agent settings cannot be read. An Owner or Admin can check them under Governance." + : refusal === 'harness-invalid' + ? "The runtime chosen for the organization's standard agent is not available. An Owner or Admin can choose another under Governance." + : refusal === 'pin-unavailable' + ? "The model chosen for the organization's standard agent is not one you can use. An Owner or Admin can choose another under Governance." + : "No model you can use can run the organization's standard agent. An Owner or Admin can set up an AI provider, or give you access to a model.", + 409, + { reason: refusal }, + ); +} + +/** The standard agent's name, in the organization's language: it reads + * like any agent's in every list and handle. */ +async function standardAgentName( + sql: Sql | TransactionSql, + organizationId: string, +): Promise { + const rows = await sql<{ metadata: unknown }[]>` + SELECT metadata FROM "organization" WHERE id = ${organizationId} LIMIT 1 + `; + const locale = getOrganizationDefaultLocale(rows[0]?.metadata); + return ( + catalogString(locale, 'projects.agents.standard.name') ?? 'Standard agent' + ); +} + +/** + * The project's standard agent, created if it has none yet — the door a + * Member (or anyone who can open the project) uses to hand it work. Answers + * the standing managed agent when there is one; refuses a project with + * agents of its own (its people chose those), an archived one, and a + * standard agent that is switched off or cannot run for this person. + */ +export async function ensureStandardAgent( + tx: TransactionSql, + auth: ProjectAuthContext, + projectId: string, +): Promise<{ agentId: string; created: boolean }> { + const project = await loadProjectOrThrow(tx, projectId); + assertReadable(project, auth); + assertProjectActive(project); + + const agents = await tx<{ id: string; managed: boolean }[]>` + SELECT id, managed FROM app.project_agents + WHERE project_id = ${projectId} + ORDER BY managed DESC + `; + const standing = agents.find((agent) => agent.managed); + if (standing !== undefined) { + return { agentId: standing.id, created: false }; + } + if (agents.length > 0) { + throw new ProjectError( + 'STANDARD_AGENT_NOT_NEEDED', + 'This project has agents of its own; assign one of them', + 409, + ); + } + + const config = await readStandardAgentPolicy(tx, auth.organizationId); + if (config === 'unreadable') throw refusalError('unreadable'); + if (!config.enabled) throw refusalError('off'); + const serving = await resolveStandardAgentServing(tx, { + organizationId: auth.organizationId, + userId: auth.userId, + config, + }); + if (!serving.ok) throw refusalError(serving.refusal); + + const { skills } = await listProjectCapabilities(tx, { + organizationId: auth.organizationId, + userId: auth.userId, + projectId, + }); + const visible = new Set(skills.map((skill) => skill.slug)); + return insertManagedProjectAgent(tx, auth, project, { + name: await standardAgentName(tx, auth.organizationId), + harness: serving.harness, + model: serving.model, + modelProvider: serving.modelProvider, + skills: DOCUMENT_SKILL_SLUGS.filter((slug) => visible.has(slug)), + instructions: config.instructions ?? STANDARD_AGENT_DEFAULT_INSTRUCTIONS, + }); +} + +/** + * The kick's view of the agent it is about to start: for the standard + * agent, what the policy says NOW — resolved for the person the run acts + * for — written back to its row when it moved; for any other agent, what + * the caller read. Refuses with the policy's reason instead of queuing a run + * that cannot start: `STANDARD_AGENT_OFF` (403) or + * `STANDARD_AGENT_UNAVAILABLE` (409). + */ +export async function standardAgentServingForKick( + tx: TransactionSql, + args: { + organizationId: string; + agentId: string; + /** Who the run acts for: a person's id, or a trigger's + * (`trigger:`), which answers to the agent's creator. */ + startedBy: string; + harness: string; + model: string; + modelProvider?: string; + }, +): Promise<{ harness: string; model: string; modelProvider?: string }> { + const rows = await tx< + { managed: boolean; projectId: string; createdBy: string }[] + >` + SELECT managed, project_id AS "projectId", created_by AS "createdBy" + FROM app.project_agents + WHERE id = ${args.agentId} AND org_id = ${args.organizationId} + LIMIT 1 + `; + const agent = rows[0]; + const passthrough = { + harness: args.harness, + model: args.model, + ...(args.modelProvider !== undefined + ? { modelProvider: args.modelProvider } + : {}), + }; + if (agent === undefined || !agent.managed) return passthrough; + + const config = await readStandardAgentPolicy(tx, args.organizationId); + if (config === 'unreadable') throw refusalError('unreadable'); + if (!config.enabled) throw refusalError('off'); + const serving = await resolveStandardAgentServing(tx, { + organizationId: args.organizationId, + userId: args.startedBy.startsWith('trigger:') + ? agent.createdBy + : args.startedBy, + config, + }); + if (!serving.ok) throw refusalError(serving.refusal); + await alignManagedProjectAgent( + tx, + { + id: args.agentId, + organizationId: args.organizationId, + projectId: agent.projectId, + }, + { + harness: serving.harness, + model: serving.model, + modelProvider: serving.modelProvider, + instructions: config.instructions ?? STANDARD_AGENT_DEFAULT_INSTRUCTIONS, + }, + ); + return { + harness: serving.harness, + model: serving.model, + modelProvider: serving.modelProvider, + }; +} + +/** The codes a kick answers for a standard agent that cannot run — the + * retry job retires a failed run on them instead of retrying forever. */ +export const STANDARD_AGENT_REFUSAL_CODES: ReadonlySet = new Set([ + 'STANDARD_AGENT_OFF', + 'STANDARD_AGENT_UNAVAILABLE', +]); diff --git a/services/platform/backend/domains/tasks/agent-runs.standard-agent.test.ts b/services/platform/backend/domains/tasks/agent-runs.standard-agent.test.ts new file mode 100644 index 0000000000..cafa5d3262 --- /dev/null +++ b/services/platform/backend/domains/tasks/agent-runs.standard-agent.test.ts @@ -0,0 +1,120 @@ +import type { TransactionSql } from 'postgres'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { addJobInTx } from '../../jobs/enqueue.ts'; +import { ProjectError } from '../projects/service.ts'; +import { standardAgentServingForKick } from '../projects/standard-agent.ts'; +import { kickAgentRun } from './agent-runs.ts'; + +vi.mock('../../lib/org-config.ts', () => ({ + readGovernancePolicyForOrg: vi.fn().mockResolvedValue(null), +})); +vi.mock('./run-ledger.ts', () => ({ recordTaskAgentRunLedgerEntry: vi.fn() })); +vi.mock('../../jobs/enqueue.ts', () => ({ addJobInTx: vi.fn() })); +vi.mock('./run-failure-notice.ts', () => ({ + announceAgentRunFailed: vi.fn(), + withdrawAgentRunFailedNotices: vi.fn(), +})); +vi.mock('../sandbox/gateway-keys.ts', () => ({ + revokeSessionGatewayKeys: vi.fn(async () => {}), +})); +vi.mock('../projects/standard-agent.ts', () => ({ + STANDARD_AGENT_REFUSAL_CODES: new Set([ + 'STANDARD_AGENT_OFF', + 'STANDARD_AGENT_UNAVAILABLE', + ]), + standardAgentServingForKick: vi.fn(), +})); + +type Row = Record; + +/** A postgres.js tagged-template stand-in answering each statement from its + * (whitespace-collapsed) text. */ +function fakeTx(answer: (text: string) => Row[]) { + const calls: { text: string; values: unknown[] }[] = []; + const tag = ( + strings: TemplateStringsArray, + ...values: unknown[] + ): Promise => { + const text = strings.join('?').replaceAll(/\s+/g, ' ').trim(); + calls.push({ text, values }); + return Promise.resolve(answer(text)); + }; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a one-member stand-in for the postgres.js template function + return { tx: tag as unknown as TransactionSql, calls }; +} + +const KICK = { + organizationId: 'org-1', + projectId: 'p-1', + taskId: 'task-1', + agentId: 'agent-standard', + harness: 'codex', + model: 'stale-model', + modelProvider: 'openai', + startedBy: 'member-1', +}; + +beforeEach(() => { + vi.mocked(addJobInTx).mockReset(); + vi.mocked(standardAgentServingForKick).mockReset(); +}); + +describe('kickAgentRun — the standard agent runs what its policy says at the start', () => { + it('writes the serving the kick view answers onto the run, not what the caller read', async () => { + vi.mocked(standardAgentServingForKick).mockResolvedValue({ + harness: 'claude-code', + model: 'claude-sonnet-5', + modelProvider: 'anthropic', + }); + const { tx, calls } = fakeTx((text) => + text.startsWith('INSERT INTO app.project_agent_runs') + ? [{ id: 'run-new' }] + : [], + ); + + await expect(kickAgentRun(tx, KICK)).resolves.toMatchObject({ + runId: 'run-new', + reused: false, + }); + expect(standardAgentServingForKick).toHaveBeenCalledWith(tx, { + organizationId: 'org-1', + agentId: 'agent-standard', + startedBy: 'member-1', + harness: 'codex', + model: 'stale-model', + modelProvider: 'openai', + }); + const insert = calls.find((call) => + call.text.startsWith('INSERT INTO app.project_agent_runs'), + ); + expect(insert?.values).toEqual( + expect.arrayContaining(['claude-code', 'claude-sonnet-5', 'anthropic']), + ); + expect(insert?.values).not.toContain('stale-model'); + }); + + it.each([ + ['STANDARD_AGENT_OFF', 403], + ['STANDARD_AGENT_UNAVAILABLE', 409], + ] as const)( + 'answers %s as the task door’s own refusal, and queues nothing', + async (code, status) => { + vi.mocked(standardAgentServingForKick).mockRejectedValue( + new ProjectError(code, 'The standard agent cannot run', status, { + reason: 'no-model', + }), + ); + const { tx, calls } = fakeTx(() => []); + + await expect(kickAgentRun(tx, KICK)).rejects.toMatchObject({ + name: 'TaskError', + code, + status, + data: { reason: 'no-model' }, + }); + expect(calls.some((call) => call.text.startsWith('INSERT'))).toBe(false); + expect(addJobInTx).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/services/platform/backend/domains/tasks/agent-runs.ts b/services/platform/backend/domains/tasks/agent-runs.ts index 192e4cd4be..283f52d614 100644 --- a/services/platform/backend/domains/tasks/agent-runs.ts +++ b/services/platform/backend/domains/tasks/agent-runs.ts @@ -13,6 +13,11 @@ import { } from '../../core/tasks/task_auto_retry.ts'; import { addJobInTx } from '../../jobs/enqueue.ts'; import { emitHintInTx } from '../../realtime/outbox.ts'; +import { ProjectError } from '../projects/service.ts'; +import { + STANDARD_AGENT_REFUSAL_CODES, + standardAgentServingForKick, +} from '../projects/standard-agent.ts'; import { revokeSessionGatewayKeys } from '../sandbox/gateway-keys.ts'; import { TaskError } from './errors.ts'; import { loadTaskRetryHistory } from './kick-plan.ts'; @@ -189,6 +194,39 @@ export interface KickAgentRunArgs { sessionId?: string; } +/** The kick's serving for this agent (`standardAgentServingForKick`), its + * refusals answered as the task door's own errors. */ +async function standardAgentServing( + tx: TransactionSql, + args: KickAgentRunArgs, +): Promise<{ harness: string; model: string; modelProvider?: string }> { + try { + return await standardAgentServingForKick(tx, { + organizationId: args.organizationId, + agentId: args.agentId, + startedBy: args.startedBy, + harness: args.harness, + model: args.model, + ...(args.modelProvider !== undefined + ? { modelProvider: args.modelProvider } + : {}), + }); + } catch (error) { + if ( + error instanceof ProjectError && + STANDARD_AGENT_REFUSAL_CODES.has(error.code) + ) { + throw new TaskError( + error.code, + error.message, + error.status === 403 ? 403 : 409, + error.data, + ); + } + throw error; + } +} + /** * Kick one run: insert the `queued` row and enqueue the turn job in the * SAME transaction. At most one live (queued|running) run per task — a @@ -228,6 +266,10 @@ export async function kickAgentRun( return { runId: standing.id, execId: standing.execId, reused: true }; } await assertTaskAutomationEnabled(tx, args.organizationId); + // The organization's standard agent runs what its policy says now, not + // what its row said when the caller read it (`standard-agent.ts`); every + // other agent runs what the caller read. + const serving = await standardAgentServing(tx, args); // The workspace follows the starter: a project editor's run joins the // agent's standing session, a member's run works in its own // (`run-authority.ts`). @@ -255,8 +297,8 @@ export async function kickAgentRun( ) VALUES ( ${args.organizationId}, ${args.projectId}, ${args.taskId}, ${args.agentId}, ${execId}, ${sessionId}, - 'queued', ${args.harness}, ${args.model}, - ${args.modelProvider ?? null}, ${args.trigger ?? 'manual'}, + 'queued', ${serving.harness}, ${serving.model}, + ${serving.modelProvider ?? null}, ${args.trigger ?? 'manual'}, ${args.feedback ?? null}, ${args.mentionSource ?? null}, ${args.autoRetryAttempt ?? null}, ${args.startedBy}, ${now}, diff --git a/services/platform/backend/domains/tasks/errors.test.ts b/services/platform/backend/domains/tasks/errors.test.ts index 79472eb953..48f5d7e016 100644 --- a/services/platform/backend/domains/tasks/errors.test.ts +++ b/services/platform/backend/domains/tasks/errors.test.ts @@ -290,6 +290,11 @@ const ADMITTED = [ // whose team ids ride in `data`. "domains/folders/service.ts 'FOLDER_NAME_INVALID' error.message", 'domains/folders/service.ts error.code error.message', + // The organization's standard agent refuses a start under the projects + // domain's class (`refusalError` in `domains/projects/standard-agent.ts`: + // one fixed sentence per reason, the reason in `data`); the kick re-throws + // its code and sentence under the task door's own. + 'domains/tasks/agent-runs.ts error.code error.message', // The competences a review policy requires and the responder lacks: the // organization's own governance names, told to the PERSON approving so // they know what to acquire. Only a user's approve runs that check @@ -320,7 +325,12 @@ describe('task refusal sentences', () => { sourceFiles(BACKEND), 'domains/projects/', ); - expect([...reached.keys()]).toEqual(['domains/projects/service.ts']); + // Every start reaches the standard agent's kick view, whose refusals are + // fixed sentences (`refusalError`). + expect([...reached.keys()].sort()).toEqual([ + 'domains/projects/service.ts', + 'domains/projects/standard-agent.ts', + ]); expect([...(reached.get('domains/projects/service.ts') ?? [])]).toEqual( expect.arrayContaining([ 'getProjectAuthContext', @@ -328,6 +338,9 @@ describe('task refusal sentences', () => { 'loadProjectOrThrow', ]), ); + expect([ + ...(reached.get('domains/projects/standard-agent.ts') ?? []), + ]).toEqual(expect.arrayContaining(['standardAgentServingForKick'])); }); it('follow every automations-domain function a task door reaches', () => { diff --git a/services/platform/backend/integration-check.ts b/services/platform/backend/integration-check.ts index cb258066e6..e92d0f8a1d 100644 --- a/services/platform/backend/integration-check.ts +++ b/services/platform/backend/integration-check.ts @@ -84,6 +84,7 @@ import { checkKnowledgeEntryIndexing } from './domains/knowledge_entries/indexin import { writeNotificationForOrgs } from './domains/notifications/service.ts'; import { ensureDefaultObjectStore } from './domains/object_storage/bootstrap.ts'; import { checkOrphanedOrgRowsBackfill } from './domains/organizations/orphaned-rows.integration.ts'; +import { checkStandardAgent } from './domains/projects/standard-agent.integration.ts'; import { checkBrokerAccountSelection } from './domains/provider_credentials/broker-selection.integration.ts'; import { checkProviderCredentialConfiguration } from './domains/provider_credentials/configuration.integration.ts'; import { checkCustomProviderCredentialEdit } from './domains/provider_credentials/custom-provider-edit.integration.ts'; @@ -57016,6 +57017,7 @@ async function main(): Promise { 'checkTaskSourceThread', () => checkTaskSourceThread(sql, authCtx, record), ], + ['checkStandardAgent', () => checkStandardAgent(sql, authCtx, record)], [ 'checkScheduledAgentStarts', () => checkScheduledAgentStarts(sql, baseUrl, authCtx, record), diff --git a/services/platform/backend/jobs/task-list.agent-retry.test.ts b/services/platform/backend/jobs/task-list.agent-retry.test.ts index 87e81c09f5..2534b379e0 100644 --- a/services/platform/backend/jobs/task-list.agent-retry.test.ts +++ b/services/platform/backend/jobs/task-list.agent-retry.test.ts @@ -58,6 +58,7 @@ import { AUTO_RETRY_HISTORY_LIMIT, AUTO_RETRY_MAX_ATTEMPTS, } from '../core/tasks/task_auto_retry.ts'; +import { TaskError } from '../domains/tasks/errors.ts'; import { addJobInTx } from './enqueue.ts'; import { agentRetryRecheckKey, createTaskList } from './task-list.ts'; import { TASK_QUEUE_OPTIONS } from './tasks.ts'; @@ -463,6 +464,37 @@ describe('task.agent_retry admission', () => { }, ); + it.each(['STANDARD_AGENT_OFF', 'STANDARD_AGENT_UNAVAILABLE'])( + 'retires the failed run once, and tells, when the standard agent refuses its retry (%s)', + async (code) => { + kickAgentRun.mockRejectedValueOnce( + new TaskError(code, 'The standard agent cannot run', 409), + ); + const handler = createTaskList({ + sql: sqlWith([failedRun('run-failed', 'harness_error')]), + })['task.agent_retry']; + + await handler?.(PAYLOAD); + + expect(kickAgentRun).toHaveBeenCalledTimes(1); + expect(retireAutoRetry).toHaveBeenCalledWith(...retiredWith(true)); + }, + ); + + it('lets any other kick refusal fail the delivery, so the queue retries it', async () => { + kickAgentRun.mockRejectedValueOnce( + new TaskError('TASK_AUTOMATION_UNAVAILABLE', 'unreadable', 409), + ); + const handler = createTaskList({ + sql: sqlWith([failedRun('run-failed', 'harness_error')]), + })['task.agent_retry']; + + await expect(handler?.(PAYLOAD)).rejects.toMatchObject({ + code: 'TASK_AUTOMATION_UNAVAILABLE', + }); + expect(retireAutoRetry).not.toHaveBeenCalled(); + }); + it('retries a member on a task of their own, which they may still work', async () => { await deliver({ member: { role: 'member' }, createdBy: 'user-starter' }); diff --git a/services/platform/backend/jobs/task-list.ts b/services/platform/backend/jobs/task-list.ts index bf8f929bf9..593c1e1bef 100644 --- a/services/platform/backend/jobs/task-list.ts +++ b/services/platform/backend/jobs/task-list.ts @@ -44,6 +44,7 @@ import { runOneDriveSyncScan, } from '../domains/onedrive/service.ts'; import { scaffoldNewOrganization } from '../domains/organizations/scaffold.ts'; +import { STANDARD_AGENT_REFUSAL_CODES } from '../domains/projects/standard-agent.ts'; import { releaseIdleSession } from '../domains/sandbox/idle-release.ts'; import { recreatePinnedSession } from '../domains/sandbox/service.ts'; import { reconcileSessionOpKey } from '../domains/sandbox/spend-settlement.ts'; @@ -72,6 +73,7 @@ import { retireBusyRetry, SCHEDULE_REVOKED_BEFORE_LAUNCH, } from '../domains/tasks/delegated-start.ts'; +import { TaskError } from '../domains/tasks/errors.ts'; import { loadTaskRetryHistory, resolveTaskKickStartArgs, @@ -455,29 +457,44 @@ export function createTaskList(deps: TaskDeps): BackendTaskList { return 'task_circuit_breaker'; } } - await kickAgentRun(tx, { - organizationId: input.organizationId, - projectId: task.projectId, - taskId: input.taskId, - agentId: input.agentId, - harness: agent.harness, - model: agent.model, - ...(agent.modelProvider !== null - ? { modelProvider: agent.modelProvider } - : {}), - startedBy: newest.startedBy, - trigger: 'auto_retry', - ...(startedVia !== undefined - ? { startedVia, inPlace: await inPlaceOfRun(tx, newest.id) } - : {}), - autoRetryAttempt: budget.attempt, - // Queued now, so the card shows the retry; started once the - // broker's cooldown has an account back. - ...(input.startAfterMs !== undefined - ? { startAfterMs: input.startAfterMs } - : {}), - ...(sessionId !== undefined ? { sessionId } : {}), - }); + try { + await kickAgentRun(tx, { + organizationId: input.organizationId, + projectId: task.projectId, + taskId: input.taskId, + agentId: input.agentId, + harness: agent.harness, + model: agent.model, + ...(agent.modelProvider !== null + ? { modelProvider: agent.modelProvider } + : {}), + startedBy: newest.startedBy, + trigger: 'auto_retry', + ...(startedVia !== undefined + ? { startedVia, inPlace: await inPlaceOfRun(tx, newest.id) } + : {}), + autoRetryAttempt: budget.attempt, + // Queued now, so the card shows the retry; started once the + // broker's cooldown has an account back. + ...(input.startAfterMs !== undefined + ? { startAfterMs: input.startAfterMs } + : {}), + ...(sessionId !== undefined ? { sessionId } : {}), + }); + } catch (error) { + // The organization's standard agent was switched off, or no longer + // runs for the starter: no retry changes that, so the failed run + // ends here and its watchers are told. The refusal is a check, not + // a failed statement, so the transaction is still good to write. + if ( + error instanceof TaskError && + STANDARD_AGENT_REFUSAL_CODES.has(error.code) + ) { + await retire(true); + return 'standard_agent_unavailable'; + } + throw error; + } return 'kicked'; }); if (typeof outcome === 'object') { diff --git a/services/platform/backend/rest/error-codes.ts b/services/platform/backend/rest/error-codes.ts index 4d31ed0d83..ac7e15a133 100644 --- a/services/platform/backend/rest/error-codes.ts +++ b/services/platform/backend/rest/error-codes.ts @@ -154,6 +154,7 @@ export const REST_ERROR_CODES = [ 'PROJECT_AGENT_CONNECTOR_UNKNOWN', 'PROJECT_AGENT_HARNESS_INVALID', 'PROJECT_AGENT_LIMIT', + 'PROJECT_AGENT_MANAGED', 'PROJECT_AGENT_MODEL_INVALID', 'PROJECT_AGENT_NAME_TAKEN', 'PROJECT_AGENT_NOT_FOUND', @@ -194,6 +195,8 @@ export const REST_ERROR_CODES = [ 'SKILL_PUBLISH_FORBIDDEN', 'SKILL_STALE', 'SKILL_TEAM_UNKNOWN', + 'STANDARD_AGENT_OFF', + 'STANDARD_AGENT_UNAVAILABLE', 'TASK_ARCHIVED', 'TASK_AUTOMATION_DISABLED', 'TASK_AUTOMATION_UNAVAILABLE', diff --git a/services/platform/lib/chat/context.test.ts b/services/platform/lib/chat/context.test.ts index 5e71319cff..804954a19f 100644 --- a/services/platform/lib/chat/context.test.ts +++ b/services/platform/lib/chat/context.test.ts @@ -50,11 +50,13 @@ const HANDOVER: TaskHandover = { projectsWithoutAgents: 1, canAddAgents: false, automationOff: false, + standardAgent: false, labels: { createTask: 'Aufgabe erstellen', createAndStart: 'Erstellen und Agent starten', assignee: 'Zuständig', createAgent: 'Agent erstellen …', + standardAgent: 'Standard-Agent', }, }; diff --git a/services/platform/lib/chat/handover.test.ts b/services/platform/lib/chat/handover.test.ts index d92f2b89a8..2bba4f3fea 100644 --- a/services/platform/lib/chat/handover.test.ts +++ b/services/platform/lib/chat/handover.test.ts @@ -7,6 +7,7 @@ const LABELS: TaskHandover['labels'] = { createAndStart: 'Create and start agent', assignee: 'Assignee', createAgent: 'Create an agent…', + standardAgent: 'Standard agent', }; function handover(overrides: Partial = {}): TaskHandover { @@ -15,6 +16,7 @@ function handover(overrides: Partial = {}): TaskHandover { projectsWithoutAgents: 1, canAddAgents: false, automationOff: false, + standardAgent: false, labels: LABELS, ...overrides, }; @@ -58,6 +60,28 @@ describe('renderTaskHandover', () => { expect(note).not.toContain('Create an agent…'); }); + it('sends work in a project without agents to the standard agent, by its label', () => { + const note = renderTaskHandover( + handover({ standardAgent: true, projectsWithoutAgents: 2 }), + ); + + expect(note).toContain( + 'Website relaunch already have agents; in any other project the organization\'s standard agent ("Standard agent") is assigned to the task.', + ); + expect(note).not.toContain('an Editor or Admin adds agents'); + }); + + it('names the standard agent when no project has an agent of its own', () => { + const note = renderTaskHandover( + handover({ standardAgent: true, projectsWithAgents: [] }), + ); + + expect(note).toContain( + 'No project they can open has an agent yet, so the organization\'s standard agent ("Standard agent") is assigned to the task.', + ); + expect(note).not.toContain('Create an agent…'); + }); + it('says agents cannot start while task automation is off', () => { const note = renderTaskHandover(handover({ automationOff: true })); diff --git a/services/platform/lib/chat/handover.ts b/services/platform/lib/chat/handover.ts index 10b36126fc..94eeeee65a 100644 --- a/services/platform/lib/chat/handover.ts +++ b/services/platform/lib/chat/handover.ts @@ -28,6 +28,9 @@ export interface TaskHandover { readonly canAddAgents: boolean; /** The organization switched task automation off: agents cannot start. */ readonly automationOff: boolean; + /** The organization's standard agent takes work, for this person, in a + * project with no agent of its own. */ + readonly standardAgent: boolean; /** The interface's own words for the controls, in the person's language. */ readonly labels: { /** The chat header's hand-over verb. */ @@ -38,6 +41,8 @@ export interface TaskHandover { readonly assignee: string; /** The assignee list's way to add an agent in place. */ readonly createAgent: string; + /** The assignee list's entry for the organization's standard agent. */ + readonly standardAgent: string; }; } @@ -65,7 +70,16 @@ export function renderTaskHandover(handover: TaskHandover): string { HEADING, `1. In this chat's header, choose ${quote(labels.createTask)}. The task takes their request, the files they shared, and a link back to this chat.`, ]; - if (named.length > 0) { + if (handover.standardAgent && handover.projectsWithoutAgents > 0) { + // Every project can take the work: those without an agent of their own + // get the organization's standard agent. + const others = unnamed > 0 ? ` (and ${unnamed} more)` : ''; + lines.push( + named.length > 0 + ? `2. Pick the project the work belongs to. ${named.join(', ')}${others} already have agents; in any other project the organization's standard agent (${quote(labels.standardAgent)}) is assigned to the task.` + : `2. Pick the project the work belongs to. No project they can open has an agent yet, so the organization's standard agent (${quote(labels.standardAgent)}) is assigned to the task.`, + ); + } else if (named.length > 0) { const others = unnamed > 0 ? ` (and ${unnamed} more)` : ''; lines.push( `2. Pick a project with an agent: ${named.join(', ')}${others}. Its agent is assigned when it is the only one.`, diff --git a/services/platform/lib/chat/index.ts b/services/platform/lib/chat/index.ts index a2e7cdd2dc..f2927af069 100644 --- a/services/platform/lib/chat/index.ts +++ b/services/platform/lib/chat/index.ts @@ -74,6 +74,7 @@ export { chooseChatModel, eligibleChatCandidates, type ChatAutoRefusal, + type ChatChoiceEntry, type ChatModelChoice, } from './model-choice'; export { diff --git a/services/platform/lib/chat/model-choice.ts b/services/platform/lib/chat/model-choice.ts index 9a36f010c1..531fc09f96 100644 --- a/services/platform/lib/chat/model-choice.ts +++ b/services/platform/lib/chat/model-choice.ts @@ -84,14 +84,31 @@ export const PREFERRED_CHAT_MODELS: Readonly< * refusals, never as a silent fallback to some other model. */ export type ChatAutoRefusal = 'no-chat-model' | 'no-vision-model'; -export interface ChatModelChoice { - entry: ModelCatalogEntry; +/** What the choice reads of a model — enough to screen and rank it, so a + * listing that is not a raw catalog (the composer's servable options, as the + * standard agent's automatic model chooses from) is chosen by the same + * rules. */ +export type ChatChoiceEntry = Pick< + ModelCatalogEntry, + | 'id' + | 'provider' + | 'tags' + | 'supportsTools' + | 'supportsVision' + | 'outputsMedia' + | 'pricing' +>; + +export interface ChatModelChoice< + T extends ChatChoiceEntry = ModelCatalogEntry, +> { + entry: T; source: 'preferred' | 'cheapest'; } /** A single entry's hazard screen — the tag says "chat", these say "and a * real chat call will actually be served". */ -function isServableChatEntry(entry: ModelCatalogEntry): boolean { +function isServableChatEntry(entry: ChatChoiceEntry): boolean { if (!entry.tags.includes('chat')) return false; // A media GENERATOR may take text in, but a chat call to it is a provider // 400, and its 0 token price is a per-artifact-billing artifact. @@ -114,10 +131,10 @@ function isServableChatEntry(entry: ModelCatalogEntry): boolean { * there is none. `entries` must already be credential- and * governance-filtered — this screen is about the models themselves. */ -export function eligibleChatCandidates( - entries: readonly ModelCatalogEntry[], +export function eligibleChatCandidates( + entries: readonly T[], opts: { requiresVision: boolean }, -): { pool: readonly ModelCatalogEntry[] } | { refusal: ChatAutoRefusal } { +): { pool: readonly T[] } | { refusal: ChatAutoRefusal } { const servable = entries.filter(isServableChatEntry); if (servable.length === 0) return { refusal: 'no-chat-model' }; @@ -146,10 +163,10 @@ function bandsToTry(target: ModelBand): readonly ModelBand[] { * price fallback always yields an entry, so `null` only ever means "empty * pool" (which {@link eligibleChatCandidates} already refuses earlier). */ -export function chooseChatModel( - pool: readonly ModelCatalogEntry[], +export function chooseChatModel( + pool: readonly T[], band: ModelBand, -): ChatModelChoice | null { +): ChatModelChoice | null { for (const tryBand of bandsToTry(band)) { for (const preferred of PREFERRED_CHAT_MODELS[tryBand]) { const entry = pool.find((candidate) => @@ -159,7 +176,7 @@ export function chooseChatModel( } } - let cheapest: { entry: ModelCatalogEntry; price: number } | null = null; + let cheapest: { entry: T; price: number } | null = null; for (const entry of pool) { const price = entry.pricing?.outputCentsPerMillion ?? Number.POSITIVE_INFINITY; diff --git a/services/platform/lib/shared/config/document-skills-catalog.test.ts b/services/platform/lib/shared/config/document-skills-catalog.test.ts index f460e3a5b3..71bc99b1c2 100644 --- a/services/platform/lib/shared/config/document-skills-catalog.test.ts +++ b/services/platform/lib/shared/config/document-skills-catalog.test.ts @@ -13,7 +13,7 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; -import { DOCUMENT_SKILL_SLUGS } from '@/app/features/projects/lib/document-skills'; +import { DOCUMENT_SKILL_SLUGS } from '@/lib/shared/document-skills'; const BUILTIN_SKILLS = path.resolve( path.dirname(fileURLToPath(import.meta.url)), diff --git a/services/platform/lib/shared/document-skills.ts b/services/platform/lib/shared/document-skills.ts new file mode 100644 index 0000000000..f9b5107d65 --- /dev/null +++ b/services/platform/lib/shared/document-skills.ts @@ -0,0 +1,7 @@ +/** + * The document bundles seeded from `configs/platform/custom/skills/` — Word, + * PowerPoint, Excel and PDF. A new project agent starts with the ones its + * project can see (the agent dialog ticks them), and so does the + * organization's standard agent (`backend/domains/projects/standard-agent.ts`). + */ +export const DOCUMENT_SKILL_SLUGS = ['docx', 'pptx', 'xlsx', 'pdf'] as const; diff --git a/services/platform/messages/de.yml b/services/platform/messages/de.yml index f8f8e0d0fa..584064d28a 100644 --- a/services/platform/messages/de.yml +++ b/services/platform/messages/de.yml @@ -1100,6 +1100,7 @@ chat: agentCount: '{count, plural, one {# Agent} other {# Agenten}}' noAgentEditor: Du kannst in der Aufgabe einen hinzufügen noAgentReader: Ein Redakteur oder Admin kann einen hinzufügen + standardAgent: Standard-Agent taskTray: label: Aufgaben aus diesem Chat working: Der Agent arbeitet @@ -4421,6 +4422,40 @@ governance: removedMailbox: Entferntes Postfach duplicateRule: Für dieses Postfach und diese Adresse gibt es bereits eine Regel precedence: 'Die genaueste Regel gewinnt: zuerst ein Postfach mit genau dieser Adresse, dann ein Postfach mit der Grundadresse, dann eine Adresse in beliebigem Postfach, zuletzt ein Postfach allein.' + standardAgent: + title: Standard-Agent + description: Der Agent, den Tale in jedem Projekt ohne eigene Agenten bereitstellt. So kann jeder, der das Projekt öffnen kann, ihm eine Aufgabe übergeben, auch Mitglieder. + enabledLabel: Standard-Agenten bereitstellen + harnessLabel: Agent-Laufzeit + harnessHint: Automatisch nutzt Claude Code oder die Agent-Laufzeit, an die ein Abo-Modell gebunden ist. + modelLabel: Modell + modelHint: Automatisch wählt ein empfohlenes Modell, das die Person nutzen darf, die die Aufgabe startet. Ein gewähltes Modell bleibt in Kraft, bis du es änderst, auch wenn es nicht mehr verfügbar ist. + automaticLabel: Automatisch + automaticHarnessHint: Tale wählt die Agent-Laufzeit. + automaticModelHint: Tale wählt für jede Person ein Modell. + instructionsLabel: Anweisungen + instructionsHint: Was der Standard-Agent immer beachten soll. Lass das Feld leer, um die eingebauten Anweisungen zu nutzen. + instructionsPlaceholder: Eingebaute Anweisungen + current: Für dich läuft er mit {harness} und {model}. + refusal: + switchedOff: Der Standard-Agent ist ausgeschaltet. + unreadable: Die gespeicherten Einstellungen können nicht gelesen werden. Versuche es erneut oder speichere sie noch einmal, um sie zu reparieren. + harnessInvalid: Die gewählte Agent-Laufzeit ist nicht verfügbar, deshalb kann der Standard-Agent nicht starten. Wähle eine andere Agent-Laufzeit oder Automatisch. + noModel: Kein Modell, das du nutzen darfst, kann den Standard-Agenten ausführen. Füge unter KI-Anbieter einen Zugang hinzu oder prüfe den Modellzugriff. + pinUnavailable: Das gewählte Modell steht dir nicht zur Verfügung, deshalb kann der Standard-Agent für dich nicht starten. Wähle ein anderes Modell oder Automatisch. Solange diese Auswahl gespeichert ist, wechselt Tale nicht zu einem anderen Modell. + invalidPolicy: Die gespeicherten Einstellungen des Standard-Agenten sind ungültig. Speichere sie noch einmal, um sie zu reparieren. + savedUnavailable: Gespeicherte Auswahl ist derzeit nicht verfügbar + searchHarnesses: Agent-Laufzeiten durchsuchen + noHarnessesFound: Keine passende Agent-Laufzeit + searchModels: Modelle durchsuchen + noModelsFound: Kein passendes Modell + draftHint: Speichere, um diese Einstellungen anzuwenden. + saveFailed: Die Einstellungen des Standard-Agenten konnten nicht gespeichert werden + loadFailed: Die Einstellungen des Standard-Agenten konnten nicht geladen werden. Versuche es erneut. + remoteUpdate: Diese Einstellungen wurden in einer anderen Sitzung geändert. Verwirf deinen Entwurf, um sie zu laden, oder speichere, um sie zu ersetzen. + offNote: Solange das ausgeschaltet ist, bieten Projekte ohne eigene Agenten keinen Agenten an, und Aufgaben, die schon einem Standard-Agenten gehören, können nicht starten. + providersLink: KI-Anbieter + retry: Erneut versuchen metrics: title: Metriken groups: @@ -7349,6 +7384,13 @@ tasks: start: 'Der Lauf konnte nicht starten. Versuche es erneut — schlägt er wieder fehl, zeig einem Admin, was der Lauf unter "Details" gemeldet hat.' interrupted: Der Lauf wurde unterbrochen, bevor der Agent fertig war. Starte den Agenten erneut. unknown: 'Der Lauf ist fehlgeschlagen. Starte den Agenten erneut — schlägt er wieder fehl, zeig einem Admin, was der Lauf unter "Details" gemeldet hat.' + standardAgent: + switchedOff: Der Standard-Agent der Organisation ist ausgeschaltet. Bitte einen Admin, ihn unter Richtlinien einzuschalten. + noModel: Kein Modell, das du nutzen darfst, kann den Standard-Agenten ausführen. Bitte einen Admin, einen KI-Anbieter einzurichten oder dir Zugriff auf ein Modell zu geben. + pinUnavailable: Das für den Standard-Agenten gewählte Modell steht dir nicht zur Verfügung. Bitte einen Admin, unter Richtlinien ein anderes zu wählen. + harnessInvalid: Die für den Standard-Agenten gewählte Agent-Laufzeit ist nicht verfügbar. Bitte einen Admin, unter Richtlinien eine andere zu wählen. + unreadable: Die Einstellungen des Standard-Agenten können nicht gelesen werden. Bitte einen Admin, sie unter Richtlinien zu prüfen. + notNeeded: Dieses Projekt hat eigene Agenten. Weise stattdessen einen davon zu. automation: hint: '{name} betreibt diese Aufgabe und führt sie durch ihre Schritte.' chipReady: Bereit zum Start @@ -7584,6 +7626,9 @@ tasks: Tab "Agenten" des Projekts. noAgentsReader: 'Dieses Projekt hat noch keine Agenten — bitte einen Redakteur oder Admin, im Tab "Agenten" des Projekts einen hinzuzufügen.' liveAgentsOnlyReader: 'Hier erscheinen nur die Agenten dieses Projekts — Redakteure und Admins fügen sie im Tab "Agenten" des Projekts hinzu.' + standardAgent: Standard-Agent + standardAgentHint: Der Agent der Organisation für Projekte ohne eigene Agenten + standardAgentFooter: Bis dieses Projekt eigene Agenten hat, übernimmt der Standard-Agent der Organisation seine Aufgaben. activity: created: Erstellt updated: Aktualisiert @@ -8412,6 +8457,13 @@ projects: mutationError: Agent konnte nicht gespeichert werden deleteTitle: Agent löschen deleteBody: '"{name}" löschen? Aufgaben, die auf ihn verwiesen haben, behalten ihre Historie.' + standard: + name: Standard-Agent + badge: Standard + managedNote: Von Tale für dieses Projekt eingerichtet. Agent-Laufzeit, Modell und Anweisungen folgen den Einstellungen der Organisation unter Richtlinien. + emptyTitle: Der Standard-Agent übernimmt die Aufgaben dieses Projekts + emptyBody: "Bis dieses Projekt eigene Agenten hat, können seine Aufgaben an den Standard-Agenten der Organisation gehen. Füge mit \"Neuer Agent\" einen hinzu, um dem Projekt eine eigene Agent-Laufzeit, ein eigenes Modell und eigene Anweisungen zu geben." + emptyReaderBody: Bis dieses Projekt eigene Agenten hat, kannst du seine Aufgaben dem Standard-Agenten der Organisation übergeben. Ein Redakteur oder Admin kann eigene Agenten hinzufügen. settings: name: Name nameHint: Wird in der Projektliste und in der Seitenleiste von Start angezeigt. diff --git a/services/platform/messages/en.yml b/services/platform/messages/en.yml index 9d57e6dac8..661245b8c9 100644 --- a/services/platform/messages/en.yml +++ b/services/platform/messages/en.yml @@ -1058,6 +1058,7 @@ chat: agentCount: '{count, plural, one {# agent} other {# agents}}' noAgentEditor: You can add one in the task noAgentReader: An Editor or Admin can add one + standardAgent: Standard agent taskTray: label: Tasks from this chat working: The agent is working @@ -4258,6 +4259,40 @@ governance: removedMailbox: Removed mailbox duplicateRule: A rule for this mailbox and address already exists precedence: 'The most specific rule wins: a mailbox with its exact address, then a mailbox with the base address, then an address on any mailbox, then a mailbox alone.' + standardAgent: + title: Standard agent + description: The agent Tale provides in every project that has none of its own, so anyone who can open the project can hand it a task, Members included. + enabledLabel: Provide a standard agent + harnessLabel: Agent type + harnessHint: Automatic runs Claude Code, or the agent type a subscription model is bound to. + modelLabel: Model + modelHint: Automatic picks a recommended model the person starting the task may use. A chosen model stays in effect until you change it, even if it becomes unavailable. + automaticLabel: Automatic + automaticHarnessHint: Let Tale choose the agent type. + automaticModelHint: Let Tale choose a model for each person. + instructionsLabel: Instructions + instructionsHint: What the standard agent always keeps in mind. Leave this empty to use the built-in instructions. + instructionsPlaceholder: Built-in instructions + current: For you, it runs on {harness} with {model}. + refusal: + switchedOff: The standard agent is switched off. + unreadable: The saved settings can't be read. Retry, or save them again to repair them. + harnessInvalid: The chosen agent type isn't available, so the standard agent can't start. Choose another agent type or Automatic. + noModel: No model you can use can run the standard agent. Add a credential under AI providers, or check model access. + pinUnavailable: The chosen model isn't available to you, so the standard agent can't start for you. Choose another model or Automatic. Tale won't switch to another model while this choice is saved. + invalidPolicy: The saved standard agent settings are invalid. Save them again to repair them. + savedUnavailable: Saved selection is not currently available + searchHarnesses: Search agent types + noHarnessesFound: No matching agent type + searchModels: Search models + noModelsFound: No matching model + draftHint: Save to apply these settings. + saveFailed: Couldn't save the standard agent settings + loadFailed: Couldn't load the standard agent settings. Retry to load them. + remoteUpdate: These settings changed in another session. Discard your draft to load them, or save to replace them. + offNote: While this is off, projects without agents of their own offer no agent, and tasks already given to a standard agent can't start. + providersLink: AI providers + retry: Retry metrics: title: Metrics groups: @@ -5493,6 +5528,13 @@ projects: mutationError: Couldn't save the agent deleteTitle: Delete agent deleteBody: 'Delete "{name}"? Tasks that referenced it keep their history.' + standard: + name: Standard agent + badge: Standard + managedNote: Set up by Tale for this project. Its agent type, model and instructions follow the organization's settings under Governance. + emptyTitle: The standard agent takes this project's tasks + emptyBody: Until this project has agents of its own, its tasks can go to the organization's standard agent. Add one with New agent to give this project its own agent type, model and instructions. + emptyReaderBody: Until this project has agents of its own, you can hand its tasks to the organization's standard agent. An Editor or Admin can add agents of its own. settings: name: Name nameHint: Shown in the projects list and the Home panel. @@ -7474,6 +7516,13 @@ tasks: start: The run couldn't start. Try again — if it fails again, show an Admin what the run reported under Details. interrupted: The run was interrupted before the agent finished. Start the agent again. unknown: The run failed. Start the agent again — if it fails again, show an Admin what the run reported under Details. + standardAgent: + switchedOff: The organization's standard agent is switched off. Ask an Admin to switch it on under Governance. + noModel: No model you can use can run the standard agent. Ask an Admin to set up an AI provider or to give you access to a model. + pinUnavailable: The model chosen for the standard agent isn't one you can use. Ask an Admin to choose another under Governance. + harnessInvalid: The agent type chosen for the standard agent isn't available. Ask an Admin to choose another under Governance. + unreadable: The standard agent's settings can't be read. Ask an Admin to check them under Governance. + notNeeded: This project has agents of its own. Assign one of them instead. automation: hint: 'Operated by {name} — it drives this task through its steps.' chipReady: Ready to start @@ -7703,6 +7752,9 @@ tasks: the project's Agents tab. noAgentsReader: This project has no agents yet — ask an Editor or Admin to add one on the project's Agents tab. liveAgentsOnlyReader: Only this project's agents appear here — Editors and Admins add them on the project's Agents tab. + standardAgent: Standard agent + standardAgentHint: The organization's agent for projects without their own + standardAgentFooter: Until this project has agents of its own, the organization's standard agent takes its tasks. activity: created: Created updated: Updated diff --git a/services/platform/messages/fr.yml b/services/platform/messages/fr.yml index cb9e8ff29e..0f812b14d3 100644 --- a/services/platform/messages/fr.yml +++ b/services/platform/messages/fr.yml @@ -1112,6 +1112,7 @@ chat: agentCount: '{count, plural, one {# agent} other {# agents}}' noAgentEditor: Tu peux en ajouter un dans la tâche noAgentReader: Un éditeur ou un admin peut en ajouter un + standardAgent: Agent standard taskTray: label: Tâches issues de ce chat working: L’agent travaille @@ -4489,6 +4490,40 @@ governance: removedMailbox: Boîte supprimée duplicateRule: Une règle existe déjà pour cette boîte et cette adresse precedence: 'La règle la plus précise l''emporte : une boîte avec son adresse exacte, puis une boîte avec l''adresse de base, puis une adresse sur n''importe quelle boîte, enfin une boîte seule.' + standardAgent: + title: Agent standard + description: L'agent que Tale fournit dans chaque projet qui n'en a pas, pour que toute personne qui peut ouvrir le projet puisse lui confier une tâche, membres compris. + enabledLabel: Fournir un agent standard + harnessLabel: Harness + harnessHint: Automatique utilise Claude Code, ou le harness auquel un modèle d'abonnement est lié. + modelLabel: Modèle + modelHint: Automatique choisit un modèle recommandé que la personne qui lance la tâche peut utiliser. Un modèle choisi reste en vigueur jusqu'à ce que tu le changes, même s'il devient indisponible. + automaticLabel: Automatique + automaticHarnessHint: Laisse Tale choisir le harness. + automaticModelHint: Laisse Tale choisir un modèle pour chaque personne. + instructionsLabel: Instructions + instructionsHint: Ce que l'agent standard garde toujours en tête. Laisse ce champ vide pour utiliser les instructions intégrées. + instructionsPlaceholder: Instructions intégrées + current: Pour toi, il fonctionne avec {harness} et {model}. + refusal: + switchedOff: L'agent standard est désactivé. + unreadable: Les réglages enregistrés sont illisibles. Réessaie, ou enregistre-les à nouveau pour les réparer. + harnessInvalid: Le harness choisi n'est pas disponible, l'agent standard ne peut donc pas démarrer. Choisis un autre harness ou Automatique. + noModel: Aucun modèle que tu peux utiliser ne peut faire fonctionner l'agent standard. Ajoute un accès dans Fournisseurs IA, ou vérifie l'accès aux modèles. + pinUnavailable: Le modèle choisi ne t'est pas accessible, l'agent standard ne peut donc pas démarrer pour toi. Choisis un autre modèle ou Automatique. Tale ne passe pas à un autre modèle tant que ce choix est enregistré. + invalidPolicy: Les réglages enregistrés de l'agent standard ne sont pas valides. Enregistre-les à nouveau pour les réparer. + savedUnavailable: La sélection enregistrée est actuellement indisponible + searchHarnesses: Rechercher un harness + noHarnessesFound: Aucun harness correspondant + searchModels: Rechercher un modèle + noModelsFound: Aucun modèle correspondant + draftHint: Enregistre pour appliquer ces réglages. + saveFailed: Impossible d'enregistrer les réglages de l'agent standard + loadFailed: Impossible de charger les réglages de l'agent standard. Réessaie de les charger. + remoteUpdate: Ces réglages ont changé dans une autre session. Abandonne tes modifications pour les charger, ou enregistre pour les remplacer. + offNote: Tant que ce réglage est désactivé, les projets sans agents propres ne proposent aucun agent, et les tâches déjà confiées à un agent standard ne peuvent pas démarrer. + providersLink: Fournisseurs IA + retry: Réessayer metrics: title: Métriques groups: @@ -7460,6 +7495,13 @@ tasks: start: L’exécution n’a pas pu démarrer. Réessaie — si elle échoue encore, montre à un admin ce que l’exécution a signalé dans « Détails ». interrupted: L’exécution a été interrompue avant que l’agent ait terminé. Relance l’agent. unknown: L’exécution a échoué. Relance l’agent — si elle échoue encore, montre à un admin ce que l’exécution a signalé dans « Détails ». + standardAgent: + switchedOff: L'agent standard de l'organisation est désactivé. Demande à un admin de l'activer dans Gouvernance. + noModel: Aucun modèle que tu peux utiliser ne peut faire fonctionner l'agent standard. Demande à un admin de configurer un fournisseur IA ou de te donner accès à un modèle. + pinUnavailable: Le modèle choisi pour l'agent standard ne t'est pas accessible. Demande à un admin d'en choisir un autre dans Gouvernance. + harnessInvalid: Le harness choisi pour l'agent standard n'est pas disponible. Demande à un admin d'en choisir un autre dans Gouvernance. + unreadable: Les réglages de l'agent standard sont illisibles. Demande à un admin de les vérifier dans Gouvernance. + notNeeded: Ce projet a ses propres agents. Assigne plutôt l'un d'eux. automation: hint: '{name} opère cette tâche et la fait avancer dans ses étapes.' chipReady: Prête à démarrer @@ -7692,6 +7734,9 @@ tasks: l'onglet Agents du projet. noAgentsReader: Ce projet n’a pas encore d’agent — demande à un éditeur ou à un admin d’en ajouter un dans l’onglet Agents du projet. liveAgentsOnlyReader: Seuls les agents de ce projet apparaissent ici — les éditeurs et les admins les ajoutent dans l’onglet Agents du projet. + standardAgent: Agent standard + standardAgentHint: L'agent de l'organisation pour les projets sans agent propre + standardAgentFooter: Tant que ce projet n'a pas d'agents propres, l'agent standard de l'organisation prend en charge ses tâches. activity: created: Créé updated: Mis à jour @@ -8518,6 +8563,13 @@ projects: mutationError: Impossible d'enregistrer l'agent deleteTitle: Supprimer l'agent deleteBody: 'Supprimer « {name} » ? Les tâches qui y faisaient référence gardent leur historique.' + standard: + name: Agent standard + badge: Standard + managedNote: Mis en place par Tale pour ce projet. Son harness, son modèle et ses instructions suivent les réglages de l'organisation dans Gouvernance. + emptyTitle: L'agent standard prend en charge les tâches de ce projet + emptyBody: Tant que ce projet n'a pas d'agents propres, ses tâches peuvent aller à l'agent standard de l'organisation. Ajoutes-en un avec Nouvel agent pour donner à ce projet son propre harness, son propre modèle et ses propres instructions. + emptyReaderBody: Tant que ce projet n'a pas d'agents propres, tu peux confier ses tâches à l'agent standard de l'organisation. Un éditeur ou un admin peut ajouter des agents propres au projet. settings: name: Nom nameHint: Affiché dans la liste des projets et dans le panneau latéral d’Accueil. diff --git a/services/platform/scripts/openapi/spec.ts b/services/platform/scripts/openapi/spec.ts index 4289f3060e..cf073b49e5 100644 --- a/services/platform/scripts/openapi/spec.ts +++ b/services/platform/scripts/openapi/spec.ts @@ -3173,9 +3173,12 @@ export function buildSpec(): Json { ...projectAgentErrors, '409': errorResponse( '`expectedUpdatedAt` is older than the agent’s `updatedAt` ' + - '(`PROJECT_AGENT_STALE`), or the new name is another agent’s ' + + '(`PROJECT_AGENT_STALE`), the new name is another agent’s ' + 'in this project, compared without regard to case ' + - '(`PROJECT_AGENT_NAME_TAKEN`) — nothing was written', + '(`PROJECT_AGENT_NAME_TAKEN`), or the agent is the ' + + "organization's standard agent, whose settings follow the " + + '`standard_agent` policy (`PROJECT_AGENT_MANAGED`) — nothing was ' + + 'written', ), }, }, @@ -9761,6 +9764,7 @@ curl -H "Authorization: Bearer " \\ 'tools', 'secrets', 'instructions', + 'managed', 'createdBy', 'createdAt', 'updatedAt', @@ -9782,6 +9786,15 @@ curl -H "Authorization: Bearer " \\ 'Granted organization secret names. Secret values are never returned.', }, instructions: nullable(str), + managed: { + type: 'boolean', + description: + "The organization's standard agent: Tale created it in a " + + 'project that had no agents of its own, and keeps its ' + + "runtime, model and instructions in line with the organization's " + + '`standard_agent` governance policy, so it cannot be saved ' + + 'here (`PROJECT_AGENT_MANAGED`). It can be deleted.', + }, createdBy: str, createdAt: epochMs, updatedAt: epochMs, From dbfab0ae518fbd14edefda610be40751969d58ea Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 1 Oct 2026 07:17:29 +0200 Subject: [PATCH 02/14] feat(platform): offer the standard agent where tasks are assigned In a project without agents of its own, Assignee offers Standard agent to everyone who may assign the task, and the chat hand-over lists such projects as startable and pre-assigns it. The project's Agents tab marks it Standard, without an edit action, and its empty state says where tasks go. Governance > Models gets a Standard agent section: the switch, the agent type, the model, the instructions, and what it runs on for the viewer, with a repair path for a malformed policy. Refusals map to localized messages that say who can fix them. --- .../components/create-task-from-chat.test.tsx | 74 +++ .../chat/components/create-task-from-chat.tsx | 104 ++++- .../components/project-agents-tab.test.tsx | 54 ++- .../components/project-agents-tab.tsx | 69 ++- .../app/features/projects/hooks/mutations.ts | 8 + .../app/features/projects/hooks/queries.ts | 22 +- .../components/standard-agent-editor.test.tsx | 265 +++++++++++ .../components/standard-agent-editor.tsx | 426 ++++++++++++++++++ .../tasks/components/assignee-picker.test.tsx | 103 ++++- .../tasks/components/assignee-picker.tsx | 101 ++++- .../tasks/hooks/use-actor-directory.test.ts | 24 + .../tasks/hooks/use-actor-directory.ts | 13 +- .../app/features/tasks/lib/task-run-error.ts | 20 +- .../app/lib/backend/contract/projects.ts | 32 ++ services/platform/app/lib/backend/projects.ts | 28 ++ .../settings/governance/content-models.tsx | 3 + services/platform/lib/utils/backend-error.ts | 9 + 17 files changed, 1305 insertions(+), 50 deletions(-) create mode 100644 services/platform/app/features/settings/governance/components/standard-agent-editor.test.tsx create mode 100644 services/platform/app/features/settings/governance/components/standard-agent-editor.tsx diff --git a/services/platform/app/features/chat/components/create-task-from-chat.test.tsx b/services/platform/app/features/chat/components/create-task-from-chat.test.tsx index 6f571e6909..ac558b70f0 100644 --- a/services/platform/app/features/chat/components/create-task-from-chat.test.tsx +++ b/services/platform/app/features/chat/components/create-task-from-chat.test.tsx @@ -21,6 +21,11 @@ const state = vi.hoisted(() => ({ messages: [] as ChatMessageView[], navigate: vi.fn(), toast: vi.fn(), + standardAgent: { enabled: true, available: false } as { + enabled: boolean; + available: boolean; + }, + ensure: vi.fn(), })); vi.mock('../data/chat-backend', () => ({ @@ -41,6 +46,11 @@ vi.mock('@/app/features/projects/hooks/queries', () => ({ projectId === undefined ? [] : (state.agentsByProject[projectId] ?? []), isLoading: false, }), + useStandardAgent: () => state.standardAgent, +})); + +vi.mock('@/app/features/projects/hooks/mutations', () => ({ + useEnsureStandardAgent: () => ({ mutateAsync: state.ensure }), })); vi.mock('@tanstack/react-router', async (importOriginal) => ({ @@ -140,6 +150,8 @@ function open(props: { projectId?: string; viewerIsOwner?: boolean } = {}) { beforeEach(() => { state.projects = [WEBSITE, HANDBOOK]; state.agentsByProject = {}; + state.standardAgent = { enabled: true, available: false }; + state.ensure.mockReset(); state.projectsFailed = false; state.messages = conversation(); state.navigate.mockReset(); @@ -258,6 +270,68 @@ describe('CreateTaskFromChat', () => { ).toBeInTheDocument(); }); + it('lists a project without agents as one the standard agent takes, while the organization provides it', async () => { + state.standardAgent = { enabled: true, available: true }; + state.projects = [ + { ...WEBSITE, agentCount: 2, canEdit: false }, + { ...HANDBOOK, agentCount: 0, canEdit: false }, + ]; + const { user } = open(); + + await user.click(screen.getByRole('button', { name: /^Project/ })); + + expect(screen.getByText('With an agent')).toBeInTheDocument(); + expect(screen.queryByText('No agent yet')).not.toBeInTheDocument(); + expect( + screen.getByRole('option', { name: /Employee handbook.*Standard agent/ }), + ).toBeInTheDocument(); + }); + + it('adds the standard agent to the chosen project and hands it the task', async () => { + state.standardAgent = { enabled: true, available: true }; + state.ensure.mockResolvedValue({ + agentId: 'agent-standard', + created: true, + }); + state.projects = [ + { ...WEBSITE, agentCount: 2 }, + { ...HANDBOOK, agentCount: 0 }, + ]; + const { user } = open(); + + await user.click(screen.getByRole('button', { name: /^Project/ })); + await user.click(screen.getByRole('option', { name: /Employee handbook/ })); + await user.click(screen.getByRole('button', { name: 'Continue' })); + + expect(await screen.findByTestId('assignee')).toHaveTextContent( + 'agent-standard', + ); + expect(state.ensure).toHaveBeenCalledWith({ projectId: HANDBOOK.id }); + expect(screen.getByTestId('start')).toHaveTextContent('true'); + }); + + it('opens the task unassigned, saying why, when the standard agent cannot be added', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + state.standardAgent = { enabled: true, available: true }; + state.ensure.mockRejectedValue( + Object.assign(new Error('off'), { + data: { code: 'STANDARD_AGENT_OFF' }, + }), + ); + state.projects = [{ ...HANDBOOK, agentCount: 0 }]; + open(); + + expect(await screen.findByTestId('project')).toHaveTextContent(HANDBOOK.id); + expect(screen.getByTestId('assignee')).toBeEmptyDOMElement(); + expect(state.toast).toHaveBeenCalledWith( + expect.objectContaining({ + title: expect.stringContaining('standard agent is switched off'), + variant: 'destructive', + }), + ); + warn.mockRestore(); + }); + it('picks the one project with an agent in advance', async () => { state.projects = [ { ...WEBSITE, agentCount: 1 }, diff --git a/services/platform/app/features/chat/components/create-task-from-chat.tsx b/services/platform/app/features/chat/components/create-task-from-chat.tsx index 1155763ccc..b96b2ab15f 100644 --- a/services/platform/app/features/chat/components/create-task-from-chat.tsx +++ b/services/platform/app/features/chat/components/create-task-from-chat.tsx @@ -10,9 +10,11 @@ * The hand-over is meant to finish: the project step says which projects * have an agent (and who could add one where there is none), a lone project * is taken without asking, a project's only agent is picked, and the dialog's - * main verb creates the task AND starts the agent. The task names this - * conversation as its source, so the chat keeps a live row of it - * (`ChatTaskTray`). + * main verb creates the task AND starts the agent. A project with no agent + * of its own gets the organization's standard agent, when the organization + * provides one: going on into it creates the agent there and picks it. The + * task names this conversation as its source, so the chat keeps a live row + * of it (`ChatTaskTray`). */ import * as ToastPrimitives from '@radix-ui/react-toast'; @@ -23,10 +25,15 @@ import { SearchableSelect } from '@tale/ui/searchable-select'; import { Text } from '@tale/ui/text'; import { toast } from '@tale/ui/use-toast'; import { useNavigate } from '@tanstack/react-router'; -import { useMemo, useState } from 'react'; +import { useEffect, useMemo, useState } from 'react'; -import { useProjectAgents } from '@/app/features/projects/hooks/queries'; +import { useEnsureStandardAgent } from '@/app/features/projects/hooks/mutations'; +import { + useProjectAgents, + useStandardAgent, +} from '@/app/features/projects/hooks/queries'; import { TaskModal } from '@/app/features/tasks/components/task-modal'; +import { taskRunErrorMessage } from '@/app/features/tasks/lib/task-run-error'; import { chatMessagesQuery } from '@/app/lib/backend/chat'; import { useT } from '@/lib/i18n/client'; @@ -67,6 +74,7 @@ export function CreateTaskFromChat({ }: CreateTaskFromChatProps) { const { t } = useT('chat'); const { t: tCommon } = useT('common'); + const { t: tTasks } = useT('tasks'); const navigate = useNavigate(); const projects = useChatProjects(organizationId); const messages = useChatMessages( @@ -85,7 +93,10 @@ export function CreateTaskFromChat({ ? projectId : undefined; // Where work can go: projects with an agent first, then the rest, each - // saying who could add one. + // saying who could add one — or, while the organization provides a + // standard agent, saying it takes the work there. + const standardAgentAvailable = + useStandardAgent(open ? organizationId : undefined)?.available === true; const withAgents = listed.filter((row) => (row.agentCount ?? 0) > 0); const withoutAgents = listed.filter((row) => (row.agentCount ?? 0) === 0); // A lone project is the answer; asking would be a step with one choice. @@ -95,18 +106,72 @@ export function CreateTaskFromChat({ : undefined; const [pickedProjectId, setPickedProjectId] = useState(null); // Pre-picked when exactly one project has an agent: that is where the - // work can start. + // work can start. With a standard agent, every project has one. + const startable = standardAgentAvailable ? listed : withAgents; const pickedOrDefault = pickedProjectId ?? - (withAgents.length === 1 ? (withAgents[0]?.id ?? null) : null); + (startable.length === 1 ? (startable[0]?.id ?? null) : null); const [chosenProjectId, setChosenProjectId] = useState( undefined, ); const targetProjectId = homeProjectId ?? onlyProjectId ?? chosenProjectId; // The target project's agents: its only one is picked for the person. const agents = useProjectAgents(open ? targetProjectId : undefined); + // A target with none of its own gets the organization's standard agent, + // created once the person has chosen the project — so the form opens with + // it picked, as with any project's only agent. A refusal opens the form + // unassigned and says why. + const { mutateAsync: ensureStandardAgent } = useEnsureStandardAgent(); + const [standardAgent, setStandardAgent] = useState< + { projectId: string; agentId: string | null } | undefined + >(undefined); + const needsStandardAgent = + open && + targetProjectId !== undefined && + standardAgentAvailable && + !agents.isLoading && + agents.agents.length === 0; + useEffect(() => { + if (!needsStandardAgent || targetProjectId === undefined) return undefined; + if (standardAgent?.projectId === targetProjectId) return undefined; + let cancelled = false; + ensureStandardAgent({ projectId: targetProjectId }).then( + ({ agentId }) => { + if (!cancelled) + setStandardAgent({ projectId: targetProjectId, agentId }); + }, + (error: unknown) => { + console.warn( + '[chat] the standard agent could not be added for the hand-over', + error, + ); + if (cancelled) return; + setStandardAgent({ projectId: targetProjectId, agentId: null }); + toast({ + title: + taskRunErrorMessage(error, tTasks) ?? tCommon('errors.generic'), + variant: 'destructive', + }); + }, + ); + return () => { + cancelled = true; + }; + }, [ + ensureStandardAgent, + needsStandardAgent, + standardAgent?.projectId, + targetProjectId, + tCommon, + tTasks, + ]); + const ensuredAgentId = + standardAgent?.projectId === targetProjectId + ? (standardAgent?.agentId ?? undefined) + : undefined; const onlyAgentId = - agents.agents.length === 1 ? agents.agents[0]?._id : undefined; + ensuredAgentId ?? + (agents.agents.length === 1 ? agents.agents[0]?._id : undefined); // The draft is taken from a conversation that was actually read: the form // keeps what it opened with, so a read that failed must not open it with @@ -162,6 +227,7 @@ export function CreateTaskFromChat({ onOpenChange(false); setPickedProjectId(null); setChosenProjectId(undefined); + setStandardAgent(undefined); }; const announce = (taskId: string, taskProjectId: string) => { @@ -218,8 +284,12 @@ export function CreateTaskFromChat({ if (targetProjectId !== undefined) { // The form reads its draft once, when it mounts: wait for the agent - // list, so the project's one agent is already picked. + // list — and for the standard agent a project without one gets — so the + // project's one agent is already picked. if (agents.isLoading) return null; + if (needsStandardAgent && standardAgent?.projectId !== targetProjectId) { + return null; + } return ( 0 + ...(withAgents.length > 0 || + (standardAgentAvailable && withoutAgents.length > 0) ? [ { value: '__section:with-agents', @@ -282,9 +353,18 @@ export function CreateTaskFromChat({ count: row.agentCount ?? 0, }), })), + // The organization's standard agent takes the work in + // a project with no agent of its own. + ...(standardAgentAvailable + ? withoutAgents.map((row) => ({ + value: row.id, + label: row.name, + description: t('createTask.standardAgent'), + })) + : []), ] : []), - ...(withoutAgents.length > 0 + ...(withoutAgents.length > 0 && !standardAgentAvailable ? [ { value: '__section:without-agents', diff --git a/services/platform/app/features/projects/components/project-agents-tab.test.tsx b/services/platform/app/features/projects/components/project-agents-tab.test.tsx index d323574458..65e58d010f 100644 --- a/services/platform/app/features/projects/components/project-agents-tab.test.tsx +++ b/services/platform/app/features/projects/components/project-agents-tab.test.tsx @@ -11,7 +11,7 @@ vi.mock('@tale/ui/i18n/client', () => ({ })); const { state } = vi.hoisted(() => ({ - state: { canEdit: true, agents: [] as unknown[] }, + state: { canEdit: true, agents: [] as unknown[], standardAgent: false }, })); vi.mock('../hooks/queries', () => ({ @@ -22,6 +22,10 @@ vi.mock('../hooks/queries', () => ({ useProjectAgents: () => ({ agents: state.agents, isLoading: false }), useProjectHarnesses: () => ({ data: undefined }), useProjectCapabilityCatalog: () => ({ data: undefined }), + useStandardAgent: () => ({ + enabled: true, + available: state.standardAgent, + }), })); vi.mock('../hooks/mutations', () => ({ @@ -41,6 +45,7 @@ describe('ProjectAgentsTab', () => { beforeEach(() => { state.canEdit = true; state.agents = []; + state.standardAgent = false; }); it('invites an editor to add the first agent', () => { @@ -75,4 +80,51 @@ describe('ProjectAgentsTab', () => { screen.queryByRole('button', { name: 'projects.agents.newAgent' }), ).not.toBeInTheDocument(); }); + + it('says the standard agent takes the tasks of a project without agents, by who is looking', () => { + state.standardAgent = true; + const { unmount } = renderTab(); + + expect( + screen.getByText('projects.agents.standard.emptyTitle'), + ).toBeInTheDocument(); + expect( + screen.getByText('projects.agents.standard.emptyBody'), + ).toBeInTheDocument(); + unmount(); + + state.canEdit = false; + renderTab(); + expect( + screen.getByText('projects.agents.standard.emptyReaderBody'), + ).toBeInTheDocument(); + }); + + it('marks the standard agent and offers no edit for it, while it stays removable', () => { + state.agents = [ + { + _id: 'agent-standard', + name: 'Standard agent', + harness: 'claude-code', + model: 'claude-sonnet-5', + skills: ['docx'], + connectors: [], + managed: true, + }, + ]; + renderTab(); + + expect( + screen.getByText('projects.agents.standard.badge'), + ).toBeInTheDocument(); + expect( + screen.getByText('projects.agents.standard.managedNote'), + ).toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: 'projects.agents.rowEdit' }), + ).not.toBeInTheDocument(); + expect( + screen.getByRole('button', { name: 'projects.agents.rowDelete' }), + ).toBeInTheDocument(); + }); }); diff --git a/services/platform/app/features/projects/components/project-agents-tab.tsx b/services/platform/app/features/projects/components/project-agents-tab.tsx index d6faca222e..9b57cfed2d 100644 --- a/services/platform/app/features/projects/components/project-agents-tab.tsx +++ b/services/platform/app/features/projects/components/project-agents-tab.tsx @@ -1,5 +1,6 @@ 'use client'; +import { Badge } from '@tale/ui/badge'; import { Button } from '@tale/ui/button'; import { DeleteDialog } from '@tale/ui/dialog/delete-dialog'; import { EmptyState } from '@tale/ui/empty-state'; @@ -19,6 +20,7 @@ import { useProjectAgents, useProjectCapabilityCatalog, useProjectHarnesses, + useStandardAgent, } from '../hooks/queries'; import { toModelOptions, type ModelOption } from '../lib/model-options'; import { type HarnessOption, ProjectAgentDialog } from './project-agent-dialog'; @@ -40,6 +42,12 @@ interface ProjectAgentsTabProps { * come from the same org-scoped composer actions, so the surfaces can never * drift. (The fixed per-harness equipment list this tab used to be is * retired — equipment now travels with the agent instance.) + * + * The organization's standard agent shows here too once someone handed the + * project work: marked, and without Edit — its runtime, model and + * instructions follow the organization's settings. Editors may remove it. + * A project without agents says the standard agent takes its tasks, while + * the organization provides one. */ export function ProjectAgentsTab({ organizationId, @@ -50,6 +58,8 @@ export function ProjectAgentsTab({ const rosterQuery = useProjectHarnesses(organizationId); const catalogQuery = useProjectCapabilityCatalog(organizationId, projectId); const { agents, isLoading: agentsLoading } = useProjectAgents(projectId); + const standardAgentAvailable = + useStandardAgent(organizationId)?.available === true; const { mutateAsync: deleteAgent } = useDeleteProjectAgent(); const [dialogOpen, setDialogOpen] = useState(false); @@ -138,12 +148,26 @@ export function ProjectAgentsTab({ ) : agents.length === 0 ? ( // Adding an agent is the editors'. A reader is told who can, not to - // "give one a model" on a page that offers them no way to. + // "give one a model" on a page that offers them no way to — and, + // while the organization provides one, that its standard agent + // takes the project's tasks meanwhile. ) : ( @@ -173,7 +197,16 @@ export function ProjectAgentsTab({ /> )} - {agent.name} + + + {agent.name} + + {agent.managed && ( + + {t('agents.standard.badge')} + + )} + + {agent.managed && ( + + {t('agents.standard.managedNote')} + + )} {canEdit ? ( - + {/* The standard agent's settings are the + organization's: removable here, not editable. */} + {!agent.managed && ( + + )}