diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index bce4ff8..9f16e4b 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -2,7 +2,7 @@ ## What this system is -Aryx is a desktop workspace for Copilot-powered development work. It combines a persistent session model, project-aware context, reusable multi-agent orchestration patterns, optional external tooling, and live run visibility inside a single Electron application. +Aryx is a desktop workspace for Copilot-powered development work. It combines a persistent session model, project-aware context, reusable workflow orchestration, optional external tooling, and live run visibility inside a single Electron application. At a high level, the architecture is built around one core idea: @@ -23,7 +23,7 @@ The current architecture optimizes for: - **persistent workspaces** rather than disposable chat threads - **project-aware execution** with repository context and optional tooling - **observable AI runs** with streamed output, activity, and history -- **extensible orchestration** so patterns, models, and tool integrations can evolve without collapsing boundaries +- **extensible orchestration** so workflows, models, and tool integrations can evolve without collapsing boundaries ## System context @@ -56,7 +56,7 @@ flowchart LR | Renderer | Screens, interaction, local view composition, theme application | Filesystem, process spawning, raw Electron access, Copilot runtime | Typed preload API and pushed events | | Preload | Narrow bridge between browser context and Electron IPC | Business logic, persistence, orchestration | `ipcRenderer` / `ipcMain` | | Main process | Workspace mutation, persistence, git inspection/write operations, run change attribution, commit workflow orchestration, session lifecycle, native window state, sidecar lifecycle, PTY-backed terminal lifecycle | UI rendering, LLM orchestration internals | IPC, filesystem, git CLI, stdio with sidecar, native child processes | -| Sidecar | Capability discovery, pattern validation, run execution, streaming deltas and activity | UI, workspace persistence, Electron APIs | Line-delimited JSON over stdio | +| Sidecar | Capability discovery, workflow validation, run execution, streaming deltas and activity | UI, workspace persistence, Electron APIs | Line-delimited JSON over stdio | | External systems | Git data, Copilot account/model access, OS window chrome | Application state and UI behavior | Controlled adapters owned by main or sidecar | This split is the most important architectural feature in the app. It is what keeps the system understandable as more capabilities are added. @@ -108,9 +108,8 @@ This flow is important because it shows that Aryx is not architected as a simple The durable state of the app is a **workspace**. The workspace contains: - connected projects -- orchestration patterns -- workflow templates - workflows +- workflow templates - sessions - settings - run history @@ -130,36 +129,34 @@ Project-backed entries also persist scanned Copilot customization metadata disco For git-backed projects, the main process also owns background git refreshes, captures a structured pre-run working-tree snapshot on each run record, and persists a post-run git change summary after project-backed turns complete. It also owns all git write operations exposed by Aryx — selective discard, staging, commit, push/pull/fetch, and branch lifecycle actions — so the renderer never shells out directly or manipulates repository state on its own. -### Patterns +### Workflows -Patterns describe how agents collaborate. The architecture supports: +Workflows describe how agents collaborate. The architecture supports: - one-agent conversations -- sequential workflows -- concurrent responses -- handoff flows -- group chat style collaboration +- sequential execution +- concurrent fan-out / fan-in flows +- handoff-style routing +- group-chat style collaboration Their runtime semantics follow the Agent Framework orchestration model: sequential and group chat preserve a visible shared conversation, concurrent aggregates multiple independent responses into one turn, and handoff turns can end once the active agent has responded and is waiting for the next user input. -For Copilot-backed agents, Aryx uses a repo-local adapter around the Copilot SDK session layer so handoff routes still behave like Agent Framework handoffs. This is necessary because the upstream `GitHubCopilotAgent` does not currently project run-time handoff tool declarations into Copilot sessions or surface Copilot tool requests back as `FunctionCallContent` for the workflow runtime. +For Copilot-backed agents, Aryx uses a repo-local adapter around the Copilot SDK session layer so workflow agent routes still behave like Agent Framework handoffs. This is necessary because the upstream `GitHubCopilotAgent` does not currently project run-time handoff tool declarations into Copilot sessions or surface Copilot tool requests back as `FunctionCallContent` for the workflow runtime. -Patterns are shared application data, not renderer-only configuration. That means the same pattern definition can drive validation, persistence, UI rendering, and sidecar execution. +Workflows are shared application data, not renderer-only configuration. The same workflow definition now drives validation, persistence, session execution, and sidecar orchestration. -Patterns now persist an explicit graph-backed topology alongside the flat agent list. Agent nodes carry stable agent ids, ordering, and layout metadata, while system nodes such as user input/output, distributor, collector, and orchestrator make mode-specific flow visible in the saved contract. +Each workflow persists an explicit graph-backed topology. Agent nodes carry stable ids, ordering, and layout metadata, while start/end, fan-out/fan-in, sub-workflow, function, and request-port nodes make execution structure visible in the saved contract. -That graph is now the execution contract for the sidecar: sequential order comes from the saved path, handoff routes come from directed graph edges, and concurrent/group-chat participant ordering can be derived from graph node metadata instead of hard-coded runtime assumptions. +That graph is the execution contract for the sidecar: sequencing comes from saved edges, sub-workflow execution comes from referenced workflow graphs, and orchestration hints such as handoff or group-chat are carried as workflow settings rather than through a separate pattern domain. -The pattern editor renders an interactive graph canvas powered by React Flow (`@xyflow/react`). The canvas projects the authoritative `PatternGraph` into React Flow nodes and edges via a view-model layer (`src/renderer/lib/patternGraph.ts`). Users can drag nodes to reposition them, and in handoff mode can draw new agent-to-agent edges directly on the canvas. A right-side inspector panel shows the details of the selected node — system node metadata for system nodes, or the full agent configuration form (model, reasoning, instructions) for agent nodes. The mode selector, pattern metadata, approval checkpoints, and tool auto-approval settings remain below the graph as scrollable settings sections. The `syncPatternGraph()` adapter is still called when agents are added/removed or the mode changes, rebuilding the graph from the current state; direct graph edits (drag positions, handoff edges) are persisted without the adapter. - -Workflows now sit alongside patterns as a first-class shared-domain contract. The shared layer owns workflow definitions, workflow template definitions, and workflow import/export helpers (YAML import/export plus Mermaid and DOT export). Built-in workflow templates are derived from built-in patterns, while custom templates are persisted in workspace state and used by the main process to create new saved workflows without expanding the sidecar protocol. +Workflow templates remain a first-class shared-domain contract. The shared layer owns workflow definitions, workflow template definitions, and workflow import/export helpers (YAML import/export plus Mermaid and DOT export). Built-in workflows seed workspace state directly, while built-in and custom templates let the main process create additional saved workflows without expanding the sidecar protocol. ### Sessions A session is the working unit of the product. It binds together: - a project -- a pattern +- a workflow - a message history - status and errors - optional per-session tool selection @@ -212,7 +209,7 @@ This is a structured stdio protocol used for: - capability discovery - on-demand account quota lookup -- pattern validation +- workflow validation - run execution - streaming partial output - streaming agent activity @@ -241,7 +238,7 @@ The same boundary also supports server-scoped sidecar commands that do not requi For project-backed sessions, the sidecar also discovers GitHub Copilot CLI hook definitions from `.github/hooks/*.json` under the repository root. Those files are parsed and merged once per run bundle, then projected onto the SDK session hook delegates. Hook commands run synchronously in the sidecar through the platform shell, with stdin JSON payloads shaped to match Copilot CLI hook expectations as closely as the SDK allows. Hook failures are logged to stderr and treated as non-fatal diagnostics, while `preToolUse` hook outputs can still deny a tool call before Aryx falls back to its built-in approval policy. -The `run-turn` command now also carries a project-instruction payload derived from scanned repo customization files. The main process composes that payload from always-on repo instructions plus formatted file-scoped and task-scoped `.instructions.md` / `.claude/rules` entries, while omitting manual-only instruction files from automatic injection. It also merges enabled discovered custom agent profiles into the primary pattern agent's Copilot configuration before sending the command across the stdio boundary. Prompt-file submissions can additionally attach a structured `promptInvocation` payload with prompt identity, resolved prompt body, optional `agent`, optional `model`, and optional `tools` metadata. The main process stores that prompt invocation metadata on the triggering user message so replay and regenerate flows can rebuild it, hydrates missing metadata from the scanned prompt definition, promotes `agent: plan` to a per-turn plan-mode override, applies per-turn prompt model overrides to the effective pattern before execution, and falls back to a lightweight transcript message instead of pasting the full prompt body into chat history. The sidecar then folds both the project instructions and prompt invocation into the final SDK system message, uses prompt agent metadata to override `SessionConfig.Agent`, and narrows available tools for that turn when prompt `tools` metadata is present. +The `run-turn` command now also carries a project-instruction payload derived from scanned repo customization files. The main process composes that payload from always-on repo instructions plus formatted file-scoped and task-scoped `.instructions.md` / `.claude/rules` entries, while omitting manual-only instruction files from automatic injection. It also merges enabled discovered custom agent profiles into the primary workflow agent's Copilot configuration before sending the command across the stdio boundary. Prompt-file submissions can additionally attach a structured `promptInvocation` payload with prompt identity, resolved prompt body, optional `agent`, optional `model`, and optional `tools` metadata. The main process stores that prompt invocation metadata on the triggering user message so replay and regenerate flows can rebuild it, hydrates missing metadata from the scanned prompt definition, promotes `agent: plan` to a per-turn plan-mode override, applies per-turn prompt model overrides to the effective workflow before execution, and falls back to a lightweight transcript message instead of pasting the full prompt body into chat history. The sidecar then folds both the project instructions and prompt invocation into the final SDK system message, uses prompt agent metadata to override `SessionConfig.Agent`, and narrows available tools for that turn when prompt `tools` metadata is present. For handoff workflows, the sidecar now also enables Agent Framework JSON checkpointing backed by a per-turn filesystem store under local app data. Each saved checkpoint is surfaced to the main process, which pairs the durable Agent Framework checkpoint with an in-memory rollback snapshot of `session.messages` and the active run timeline events. If the sidecar child process exits unexpectedly during the same app lifetime, Aryx restores the latest snapshot, clears pending approval/user-input/MCP-auth state for that run, and retries the `run-turn` request once with `resumeFromCheckpoint`. Checkpoint directories are deleted after the turn completes, cancels, or fails. This recovery path is intentionally scoped to same-app sidecar restarts; full app-restart workflow rehydration would require durable rollback snapshots in addition to the Agent Framework checkpoint payloads. @@ -303,7 +300,7 @@ Tooling is deliberately split into two levels: - **global definitions** for MCP servers and LSP profiles - **MCP tool discovery** — when MCP server configs declare wildcard tools (empty `tools` array), the main process probes each server directly via the MCP protocol `tools/list` method to discover available tools, using the same auth credentials Aryx manages for OAuth-protected servers - **incremental probe progress** — MCP probing runs concurrently and publishes per-server progress through the pushed workspace snapshot, using the runtime-only `mcpProbingServerIds` field so the renderer can reflect in-flight discovery without persisting transient UI state -- **pattern defaults** where tool-call approval is enabled by default, plus which known runtime tools can bypass manual approval +- **workflow defaults** where tool-call approval is enabled by default, plus which known runtime tools can bypass manual approval - **per-session overrides** for both tool enablement and tool auto-approval This lets the application treat tooling as reusable workspace capability while still preserving session-level control and safety. diff --git a/sidecar/src/Aryx.AgentHost/Contracts/ProtocolModels.cs b/sidecar/src/Aryx.AgentHost/Contracts/ProtocolModels.cs index dfe7475..c4343f7 100644 --- a/sidecar/src/Aryx.AgentHost/Contracts/ProtocolModels.cs +++ b/sidecar/src/Aryx.AgentHost/Contracts/ProtocolModels.cs @@ -3,18 +3,7 @@ using System.Text.Json.Serialization; namespace Aryx.AgentHost.Contracts; -public sealed class PatternAgentDefinitionDto -{ - public string Id { get; init; } = string.Empty; - public string Name { get; init; } = string.Empty; - public string Description { get; init; } = string.Empty; - public string Instructions { get; init; } = string.Empty; - public string Model { get; init; } = string.Empty; - public string? ReasoningEffort { get; init; } - public PatternAgentCopilotConfigDto? Copilot { get; init; } -} - -public sealed class PatternAgentCopilotConfigDto +public sealed class WorkflowAgentCopilotConfigDto { public IReadOnlyList CustomAgents { get; init; } = []; public string? Agent { get; init; } @@ -23,50 +12,6 @@ public sealed class PatternAgentCopilotConfigDto public RunTurnInfiniteSessionsConfigDto? InfiniteSessions { get; init; } } -public sealed class PatternGraphPositionDto -{ - public double X { get; init; } - public double Y { get; init; } -} - -public sealed class PatternGraphNodeDto -{ - public string Id { get; init; } = string.Empty; - public string Kind { get; init; } = string.Empty; - public PatternGraphPositionDto Position { get; init; } = new(); - public string? AgentId { get; init; } - public int? Order { get; init; } -} - -public sealed class PatternGraphEdgeDto -{ - public string Id { get; init; } = string.Empty; - public string Source { get; init; } = string.Empty; - public string Target { get; init; } = string.Empty; -} - -public sealed class PatternGraphDto -{ - public IReadOnlyList Nodes { get; init; } = []; - public IReadOnlyList Edges { get; init; } = []; -} - -public sealed class PatternDefinitionDto -{ - public string Id { get; init; } = string.Empty; - public string Name { get; init; } = string.Empty; - public string Description { get; init; } = string.Empty; - public string Mode { get; init; } = string.Empty; - public string Availability { get; init; } = "available"; - public string? UnavailabilityReason { get; init; } - public int MaxIterations { get; init; } - public ApprovalPolicyDto? ApprovalPolicy { get; init; } - public IReadOnlyList Agents { get; init; } = []; - public PatternGraphDto? Graph { get; init; } - public string CreatedAt { get; init; } = string.Empty; - public string UpdatedAt { get; init; } = string.Empty; -} - public sealed class WorkflowPositionDto { public double X { get; init; } @@ -84,7 +29,7 @@ public sealed class WorkflowNodeConfigDto public string Instructions { get; init; } = string.Empty; public string Model { get; init; } = string.Empty; public string? ReasoningEffort { get; init; } - public PatternAgentCopilotConfigDto? Copilot { get; init; } + public WorkflowAgentCopilotConfigDto? Copilot { get; init; } public string? WorkspaceAgentId { get; init; } public string? Implementation { get; init; } public string? FunctionRef { get; init; } @@ -170,6 +115,7 @@ public sealed class WorkflowSettingsDto { public WorkflowCheckpointSettingsDto Checkpointing { get; init; } = new(); public string ExecutionMode { get; init; } = "off-thread"; + public string? OrchestrationMode { get; init; } public int? MaxIterations { get; init; } public ApprovalPolicyDto? ApprovalPolicy { get; init; } public IReadOnlyList StateScopes { get; init; } = []; @@ -220,13 +166,6 @@ public sealed class ChatMessageAttachmentDto public string? DisplayName { get; init; } } -public sealed class PatternValidationIssueDto -{ - public string Level { get; init; } = "error"; - public string? Field { get; init; } - public string Message { get; init; } = string.Empty; -} - public sealed class WorkflowValidationIssueDto { public string Level { get; init; } = "error"; @@ -303,11 +242,6 @@ public class SidecarCommandEnvelope public sealed class DescribeCapabilitiesCommandDto : SidecarCommandEnvelope; -public sealed class ValidatePatternCommandDto : SidecarCommandEnvelope -{ - public PatternDefinitionDto Pattern { get; init; } = new(); -} - public sealed class ValidateWorkflowCommandDto : SidecarCommandEnvelope { public WorkflowDefinitionDto Workflow { get; init; } = new(); @@ -322,8 +256,7 @@ public sealed class RunTurnCommandDto : SidecarCommandEnvelope public string Mode { get; init; } = "interactive"; public string MessageMode { get; init; } = "enqueue"; public string? ProjectInstructions { get; init; } - public PatternDefinitionDto Pattern { get; init; } = new(); - public WorkflowDefinitionDto? Workflow { get; init; } + public WorkflowDefinitionDto Workflow { get; init; } = new(); public IReadOnlyList WorkflowLibrary { get; init; } = []; public IReadOnlyList Messages { get; init; } = []; public RunTurnPromptInvocationDto? PromptInvocation { get; init; } @@ -464,11 +397,6 @@ public sealed class CapabilitiesEventDto : SidecarEventDto public SidecarCapabilitiesDto Capabilities { get; init; } = new(); } -public sealed class PatternValidationEventDto : SidecarEventDto -{ - public IReadOnlyList Issues { get; init; } = []; -} - public sealed class WorkflowValidationEventDto : SidecarEventDto { public IReadOnlyList Issues { get; init; } = []; diff --git a/sidecar/src/Aryx.AgentHost/Services/AgentIdentityResolver.cs b/sidecar/src/Aryx.AgentHost/Services/AgentIdentityResolver.cs index 597de50..44bcb21 100644 --- a/sidecar/src/Aryx.AgentHost/Services/AgentIdentityResolver.cs +++ b/sidecar/src/Aryx.AgentHost/Services/AgentIdentityResolver.cs @@ -10,14 +10,14 @@ internal static class AgentIdentityResolver private const string GenericAssistantIdentifier = "assistant"; public static bool TryResolveKnownAgentIdentity( - PatternDefinitionDto pattern, + WorkflowDefinitionDto workflow, string? agentIdentifier, out AgentIdentity agent) { agent = default; - PatternAgentDefinitionDto? match = FindKnownAgent(pattern, agentIdentifier) - ?? ResolveSingleAgentAssistantAlias(pattern, agentIdentifier); + WorkflowNodeDto? match = FindKnownAgent(workflow, agentIdentifier) + ?? ResolveSingleAgentAssistantAlias(workflow, agentIdentifier); if (match is null) { return false; @@ -28,12 +28,12 @@ internal static class AgentIdentityResolver } public static bool TryResolveObservedAgentIdentity( - PatternDefinitionDto pattern, + WorkflowDefinitionDto workflow, string? agentIdentifier, AgentIdentity? fallbackAgent, out AgentIdentity agent) { - if (TryResolveKnownAgentIdentity(pattern, agentIdentifier, out agent)) + if (TryResolveKnownAgentIdentity(workflow, agentIdentifier, out agent)) { return true; } @@ -49,13 +49,13 @@ internal static class AgentIdentityResolver } public static AgentIdentity ResolveAgentIdentity( - PatternDefinitionDto pattern, + WorkflowDefinitionDto workflow, string? agentId, string? agentName) { - PatternAgentDefinitionDto? match = FindKnownAgent(pattern, agentId) - ?? FindKnownAgent(pattern, agentName) - ?? ResolveSingleAgentAssistantAlias(pattern, agentId, agentName); + WorkflowNodeDto? match = FindKnownAgent(workflow, agentId) + ?? FindKnownAgent(workflow, agentName) + ?? ResolveSingleAgentAssistantAlias(workflow, agentId, agentName); return match is not null ? ToAgentIdentity(match) @@ -63,16 +63,16 @@ internal static class AgentIdentityResolver } public static string ResolveDisplayAuthorName( - PatternDefinitionDto pattern, + WorkflowDefinitionDto workflow, string? primaryIdentifier, string? fallbackIdentifier = null) { - if (TryResolveKnownAgentIdentity(pattern, primaryIdentifier, out AgentIdentity primaryAgent)) + if (TryResolveKnownAgentIdentity(workflow, primaryIdentifier, out AgentIdentity primaryAgent)) { return primaryAgent.AgentName; } - if (TryResolveKnownAgentIdentity(pattern, fallbackIdentifier, out AgentIdentity fallbackAgent)) + if (TryResolveKnownAgentIdentity(workflow, fallbackIdentifier, out AgentIdentity fallbackAgent)) { return fallbackAgent.AgentName; } @@ -98,26 +98,23 @@ internal static class AgentIdentityResolver StringComparison.Ordinal); } - private static PatternAgentDefinitionDto? ResolveSingleAgentAssistantAlias( - PatternDefinitionDto pattern, + private static WorkflowNodeDto? ResolveSingleAgentAssistantAlias( + WorkflowDefinitionDto workflow, params string?[] agentIdentifiers) { - return pattern.Agents.Count == 1 && agentIdentifiers.Any(IsGenericAssistantIdentifier) - ? pattern.Agents[0] + IReadOnlyList agentNodes = workflow.GetAgentNodes(); + return agentNodes.Count == 1 && agentIdentifiers.Any(IsGenericAssistantIdentifier) + ? agentNodes[0] : null; } - private static PatternAgentDefinitionDto? FindKnownAgent(PatternDefinitionDto pattern, string? candidate) + private static WorkflowNodeDto? FindKnownAgent(WorkflowDefinitionDto workflow, string? candidate) { - return pattern.Agents.FirstOrDefault(agent => MatchesAgent(agent, candidate)); + return workflow.GetAgentNodes().FirstOrDefault(agent => MatchesAgent(agent, candidate)); } - private static AgentIdentity ToAgentIdentity(PatternAgentDefinitionDto agent) - { - return new AgentIdentity( - agent.Id, - string.IsNullOrWhiteSpace(agent.Name) ? agent.Id : agent.Name); - } + private static AgentIdentity ToAgentIdentity(WorkflowNodeDto agent) + => new(agent.GetAgentId(), agent.GetAgentName()); private static AgentIdentity CreateFallbackIdentity(string? agentId, string? agentName) { @@ -131,22 +128,24 @@ internal static class AgentIdentityResolver return new AgentIdentity(resolvedAgentId, resolvedAgentName); } - private static bool MatchesAgent(PatternAgentDefinitionDto agent, string? candidate) + private static bool MatchesAgent(WorkflowNodeDto agent, string? candidate) { if (string.IsNullOrWhiteSpace(candidate)) { return false; } - if (string.Equals(agent.Id, candidate, StringComparison.OrdinalIgnoreCase) - || string.Equals(agent.Name, candidate, StringComparison.OrdinalIgnoreCase)) + string agentId = agent.GetAgentId(); + string agentName = agent.GetAgentName(); + if (string.Equals(agentId, candidate, StringComparison.OrdinalIgnoreCase) + || string.Equals(agentName, candidate, StringComparison.OrdinalIgnoreCase)) { return true; } string normalizedCandidate = NormalizeComparisonKey(candidate); - string normalizedId = NormalizeComparisonKey(agent.Id); - string normalizedName = NormalizeComparisonKey(agent.Name); + string normalizedId = NormalizeComparisonKey(agentId); + string normalizedName = NormalizeComparisonKey(agentName); if (normalizedCandidate.Length == 0) { return false; diff --git a/sidecar/src/Aryx.AgentHost/Services/AgentInstructionComposer.cs b/sidecar/src/Aryx.AgentHost/Services/AgentInstructionComposer.cs index 79c96fc..f731862 100644 --- a/sidecar/src/Aryx.AgentHost/Services/AgentInstructionComposer.cs +++ b/sidecar/src/Aryx.AgentHost/Services/AgentInstructionComposer.cs @@ -5,15 +5,15 @@ namespace Aryx.AgentHost.Services; internal static class AgentInstructionComposer { public static string Compose( - PatternDefinitionDto pattern, - PatternAgentDefinitionDto agent, + WorkflowDefinitionDto workflow, + WorkflowNodeDto agentNode, int agentIndex, string workspaceKind = "project", string interactionMode = "interactive", string? projectInstructions = null, RunTurnPromptInvocationDto? promptInvocation = null) { - string baseInstructions = agent.Instructions.Trim(); + string baseInstructions = agentNode.Config.Instructions.Trim(); string repositoryInstructions = projectInstructions?.Trim() ?? string.Empty; string promptInvocationInstructions = FormatPromptInvocation(promptInvocation); string workspaceGuidance = string.Equals(workspaceKind, "scratchpad", StringComparison.OrdinalIgnoreCase) @@ -34,7 +34,7 @@ internal static class AgentInstructionComposer """ : string.Empty; - if (string.Equals(pattern.Mode, "group-chat", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(workflow.Settings.OrchestrationMode, "group-chat", StringComparison.OrdinalIgnoreCase)) { string groupChatGuidance = agentIndex == 0 ? """ diff --git a/sidecar/src/Aryx.AgentHost/Services/CopilotAgentBundle.cs b/sidecar/src/Aryx.AgentHost/Services/CopilotAgentBundle.cs index 3378345..79c102d 100644 --- a/sidecar/src/Aryx.AgentHost/Services/CopilotAgentBundle.cs +++ b/sidecar/src/Aryx.AgentHost/Services/CopilotAgentBundle.cs @@ -1,10 +1,9 @@ -using System.Threading; -using GitHub.Copilot.SDK; +using System.Linq; using Aryx.AgentHost.Contracts; +using GitHub.Copilot.SDK; using Microsoft.Agents.AI; using Microsoft.Agents.AI.GitHub.Copilot; using Microsoft.Agents.AI.Workflows; -using Microsoft.Agents.AI.Workflows.Specialized; using Microsoft.Extensions.AI; namespace Aryx.AgentHost.Services; @@ -32,9 +31,9 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable public static async Task CreateAsync( RunTurnCommandDto command, - Func> onPermissionRequest, - Func> onUserInputRequest, - Action? onSessionEvent, + Func> onPermissionRequest, + Func> onUserInputRequest, + Action? onSessionEvent, CancellationToken cancellationToken) { List disposables = []; @@ -53,7 +52,8 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable disposables.Add(toolingBundle); } - foreach ((PatternAgentDefinitionDto definition, int agentIndex) in command.Pattern.Agents.Select((definition, index) => (definition, index))) + IReadOnlyList agentNodes = command.Workflow.GetAgentNodes(); + foreach ((WorkflowNodeDto definition, int agentIndex) in agentNodes.Select((definition, index) => (definition, index))) { CopilotClient client = new(clientOptions); await client.StartAsync(cancellationToken).ConfigureAwait(false); @@ -75,9 +75,9 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable client, sessionConfig, ownsClient: true, - id: definition.Id, - name: definition.Name, - description: definition.Description); + id: definition.GetAgentId(), + name: definition.GetAgentName(), + description: NormalizeOptionalString(definition.Config.Description)); agents.Add(agent); disposables.Add(agent); @@ -90,7 +90,7 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable internal static SessionConfig CreateSessionConfig( RunTurnCommandDto command, - PatternAgentDefinitionDto definition, + WorkflowNodeDto definition, int agentIndex, PermissionRequestHandler? onPermissionRequest = null, UserInputHandler? onUserInputRequest = null, @@ -98,16 +98,14 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable ResolvedHookSet? configuredHooks = null, IHookCommandRunner? hookCommandRunner = null) { - // Let the Copilot SDK allocate session IDs. Explicit custom SessionId values currently - // cause turns to complete without assistant output, even for simple single-agent prompts. return new SessionConfig { - Model = definition.Model, - ReasoningEffort = definition.ReasoningEffort, + Model = definition.Config.Model, + ReasoningEffort = definition.Config.ReasoningEffort, SystemMessage = new SystemMessageConfig { Content = AgentInstructionComposer.Compose( - command.Pattern, + command.Workflow, definition, agentIndex, command.WorkspaceKind, @@ -121,11 +119,11 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable Hooks = CopilotSessionHooks.Create(command, definition, configuredHooks, hookCommandRunner), OnEvent = onSessionEvent, Streaming = true, - CustomAgents = CreateCustomAgents(definition.Copilot?.CustomAgents), - Agent = ResolveEffectiveAgent(definition.Copilot?.Agent, command.PromptInvocation), - SkillDirectories = CreateStringList(definition.Copilot?.SkillDirectories), - DisabledSkills = CreateStringList(definition.Copilot?.DisabledSkills), - InfiniteSessions = CreateInfiniteSessions(definition.Copilot?.InfiniteSessions), + CustomAgents = CreateCustomAgents(definition.Config.Copilot?.CustomAgents), + Agent = ResolveEffectiveAgent(definition.Config.Copilot?.Agent, command.PromptInvocation), + SkillDirectories = CreateStringList(definition.Config.Copilot?.SkillDirectories), + DisabledSkills = CreateStringList(definition.Config.Copilot?.DisabledSkills), + InfiniteSessions = CreateInfiniteSessions(definition.Config.Copilot?.InfiniteSessions), }; } @@ -205,6 +203,34 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable }; } + internal static AIAgentHostOptions CreateAgentHostOptions() + { + return new AIAgentHostOptions + { + EmitAgentUpdateEvents = null, + EmitAgentResponseEvents = false, + InterceptUserInputRequests = false, + InterceptUnterminatedFunctionCalls = false, + ReassignOtherAgentsAsUsers = true, + ForwardIncomingMessages = true, + }; + } + + internal static HandoffsWorkflowBuilder CreateHandoffWorkflowBuilder(AIAgent entryAgent) + { + return AgentWorkflowBuilder.CreateHandoffBuilderWith(entryAgent) + .WithToolCallFilteringBehavior(HandoffToolCallFilteringBehavior.HandoffOnly) + .WithHandoffInstructions(HandoffWorkflowGuidance.CreateWorkflowInstructions()); + } + + public async ValueTask DisposeAsync() + { + foreach (IAsyncDisposable disposable in _disposables) + { + await disposable.DisposeAsync().ConfigureAwait(false); + } + } + private static List? CreateStringList(IReadOnlyList? values) { return values is { Count: > 0 } @@ -277,221 +303,4 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable { return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); } - - public Workflow BuildWorkflow(PatternDefinitionDto pattern) - { - return pattern.Mode switch - { - "single" => BuildSequentialWorkflow(pattern), - "sequential" => BuildSequentialWorkflow(pattern), - "concurrent" => BuildConcurrentWorkflow(pattern), - "handoff" => BuildHandoffWorkflow(pattern), - "group-chat" => BuildGroupChatWorkflow(pattern), - "magentic" => throw new NotSupportedException( - pattern.UnavailabilityReason - ?? "Magentic orchestration is not yet supported in the .NET Agent Framework."), - _ => throw new NotSupportedException($"Unsupported orchestration mode '{pattern.Mode}'."), - }; - } - - public async ValueTask DisposeAsync() - { - foreach (IAsyncDisposable disposable in _disposables) - { - await disposable.DisposeAsync().ConfigureAwait(false); - } - } - - private Workflow BuildHandoffWorkflow(PatternDefinitionDto pattern) - { - Dictionary agentMap = BuildAgentMap(pattern); - Dictionary definitionMap = pattern.Agents.ToDictionary( - definition => definition.Id, - definition => definition, - StringComparer.Ordinal); - PatternHandoffTopology topology = PatternGraphResolver.ResolveHandoff(pattern); - string entryAgentId = agentMap.ContainsKey(topology.EntryAgentId) - ? topology.EntryAgentId - : pattern.Agents.FirstOrDefault()?.Id ?? topology.EntryAgentId; - AIAgent entryAgent = agentMap.GetValueOrDefault(entryAgentId) ?? Agents[0]; - - HandoffsWorkflowBuilder builder = CreateHandoffWorkflowBuilder(entryAgent); - - foreach (PatternHandoffRoute route in topology.Routes) - { - if (!agentMap.TryGetValue(route.SourceAgentId, out AIAgent? sourceAgent) - || !agentMap.TryGetValue(route.TargetAgentId, out AIAgent? targetAgent) - || !definitionMap.TryGetValue(route.TargetAgentId, out PatternAgentDefinitionDto? targetDefinition)) - { - continue; - } - - string handoffReason = string.Equals( - route.TargetAgentId, - topology.EntryAgentId, - StringComparison.Ordinal) - ? HandoffWorkflowGuidance.CreateReturnReason(targetDefinition) - : HandoffWorkflowGuidance.CreateForwardReason(targetDefinition); - - builder = builder.WithHandoff( - sourceAgent, - targetAgent, - handoffReason); - } - - return builder.Build(); - } - - internal static AIAgentHostOptions CreateAgentHostOptions() - { - return new AIAgentHostOptions - { - // Aryx controls per-turn streaming with TurnToken(emitEvents: true), so keep this - // null to preserve that behavior while making the host defaults explicit in code. - EmitAgentUpdateEvents = null, - // Aryx already projects streamed transcript state itself; enabling this would add - // extra response events that need separate reconciliation first. - EmitAgentResponseEvents = false, - InterceptUserInputRequests = false, - InterceptUnterminatedFunctionCalls = false, - ReassignOtherAgentsAsUsers = true, - ForwardIncomingMessages = true, - }; - } - - internal static HandoffsWorkflowBuilder CreateHandoffWorkflowBuilder(AIAgent entryAgent) - { - return AgentWorkflowBuilder.CreateHandoffBuilderWith(entryAgent) - // Preserve normal tool-call history across handoffs while still hiding the - // workflow's handoff plumbing. Make this explicit so AF default changes - // cannot silently alter Aryx handoff behavior. - .WithToolCallFilteringBehavior(HandoffToolCallFilteringBehavior.HandoffOnly) - .WithHandoffInstructions(HandoffWorkflowGuidance.CreateWorkflowInstructions()); - } - - private Workflow BuildSequentialWorkflow(PatternDefinitionDto pattern) - { - IReadOnlyList agents = ResolveOrderedAgents(pattern); - List agentExecutors = agents - .Select(CreateAgentExecutorBinding) - .ToList(); - - ExecutorBinding previous = agentExecutors[0]; - WorkflowBuilder builder = new(previous); - - foreach (ExecutorBinding next in agentExecutors.Skip(1)) - { - builder.AddEdge(previous, next); - previous = next; - } - - WorkflowOutputMessagesExecutor end = new(); - builder = builder.AddEdge(previous, end).WithOutputFrom(end); - - if (pattern.Name is not null) - { - builder = builder.WithName(pattern.Name); - } - - return builder.Build(); - } - - private Workflow BuildConcurrentWorkflow(PatternDefinitionDto pattern) - { - IReadOnlyList agents = ResolveOrderedAgents(pattern); - ChatForwardingExecutor start = new("Start"); - WorkflowBuilder builder = new(start); - - ExecutorBinding[] agentExecutors = agents - .Select(CreateAgentExecutorBinding) - .ToArray(); - ExecutorBinding[] accumulators = agentExecutors - .Select(executor => CreateAggregateMessagesExecutorBinding($"Batcher/{executor.Id}")) - .ToArray(); - - builder.AddFanOutEdge(start, agentExecutors); - - for (int index = 0; index < agentExecutors.Length; index++) - { - builder.AddEdge(agentExecutors[index], accumulators[index]); - } - - Func> endFactory = - (_, __) => new(new WorkflowConcurrentEndExecutor(agentExecutors.Length, AggregateConcurrentResults)); - ExecutorBinding end = endFactory.BindExecutor(WorkflowConcurrentEndExecutor.ExecutorId); - - builder.AddFanInBarrierEdge(accumulators, end); - builder = builder.WithOutputFrom(end); - - if (pattern.Name is not null) - { - builder = builder.WithName(pattern.Name); - } - - return builder.Build(); - } - - private Workflow BuildGroupChatWorkflow(PatternDefinitionDto pattern) - { - int maximumIterations = pattern.MaxIterations <= 0 ? 5 : pattern.MaxIterations; - AIAgent[] agents = ResolveOrderedAgents(pattern).ToArray(); - Dictionary agentMap = agents.ToDictionary( - agent => agent, - CreateAgentExecutorBinding); - - Func> groupChatHostFactory = - (id, _) => new(new WorkflowRoundRobinGroupChatHost( - id, - agents, - agentMap, - maximumIterations)); - - ExecutorBinding host = groupChatHostFactory.BindExecutor("GroupChatHost"); - WorkflowBuilder builder = new(host); - - foreach (ExecutorBinding participant in agentMap.Values) - { - builder - .AddEdge(host, participant) - .AddEdge(participant, host); - } - - return builder.WithOutputFrom(host).Build(); - } - - private static ExecutorBinding CreateAgentExecutorBinding(AIAgent agent) - => agent.BindAsExecutor(CreateAgentHostOptions()); - - private static ExecutorBinding CreateAggregateMessagesExecutorBinding(string id) - { - Func> factory = - (_, __) => new(new WorkflowAggregateTurnMessagesExecutor(id)); - return factory.BindExecutor(id); - } - - private static List AggregateConcurrentResults(IList> lists) - => [.. from list in lists where list.Count > 0 select list.Last()]; - - private IReadOnlyList ResolveOrderedAgents(PatternDefinitionDto pattern) - { - Dictionary agentMap = BuildAgentMap(pattern); - List orderedAgents = PatternGraphResolver.ResolveOrderedAgentIds(pattern) - .Select(agentId => agentMap.TryGetValue(agentId, out AIAgent? agent) ? agent : null) - .Where(agent => agent is not null) - .Cast() - .ToList(); - - return orderedAgents.Count == Agents.Count ? orderedAgents : Agents; - } - - private Dictionary BuildAgentMap(PatternDefinitionDto pattern) - { - Dictionary agentMap = new(StringComparer.Ordinal); - foreach ((PatternAgentDefinitionDto definition, AIAgent agent) in pattern.Agents.Zip(Agents)) - { - agentMap[definition.Id] = agent; - } - - return agentMap; - } } diff --git a/sidecar/src/Aryx.AgentHost/Services/CopilotApprovalCoordinator.cs b/sidecar/src/Aryx.AgentHost/Services/CopilotApprovalCoordinator.cs index fd0e29e..6b65fb1 100644 --- a/sidecar/src/Aryx.AgentHost/Services/CopilotApprovalCoordinator.cs +++ b/sidecar/src/Aryx.AgentHost/Services/CopilotApprovalCoordinator.cs @@ -67,7 +67,7 @@ internal sealed class CopilotApprovalCoordinator public async Task RequestApprovalAsync( RunTurnCommandDto command, - PatternAgentDefinitionDto agent, + WorkflowNodeDto agent, PermissionRequest request, PermissionInvocation invocation, IReadOnlyDictionary toolNamesByCallId, @@ -88,7 +88,7 @@ internal sealed class CopilotApprovalCoordinator public async Task RequestApprovalAsync( RunTurnCommandDto command, - PatternAgentDefinitionDto agent, + WorkflowNodeDto agent, PermissionRequest request, PermissionInvocation invocation, IReadOnlyDictionary toolNamesByCallId, @@ -108,7 +108,7 @@ internal sealed class CopilotApprovalCoordinator } if (IsToolApprovedForRequest(command.RequestId, approvalCacheKey) - || !RequiresToolCallApproval(command.Pattern.ApprovalPolicy, agent.Id, toolName, autoApprovedToolName, mcpServerApprovalKey)) + || !RequiresToolCallApproval(command.Workflow.Settings.ApprovalPolicy, agent.GetAgentId(), toolName, autoApprovedToolName, mcpServerApprovalKey)) { return CreateApprovalResult(PermissionRequestResultKind.Approved); } @@ -149,7 +149,7 @@ internal sealed class CopilotApprovalCoordinator internal static ApprovalRequestedEventDto BuildPermissionApprovalEvent( RunTurnCommandDto command, - PatternAgentDefinitionDto agent, + WorkflowNodeDto agent, PermissionRequest request, PermissionInvocation invocation, string approvalId, @@ -157,7 +157,8 @@ internal sealed class CopilotApprovalCoordinator { string permissionKind = ResolvePermissionKind(request, command.Tooling?.McpServers); - string agentName = string.IsNullOrWhiteSpace(agent.Name) ? agent.Id : agent.Name; + string agentId = agent.GetAgentId(); + string agentName = agent.GetAgentName(); string? sessionId = NormalizeOptionalString(invocation.SessionId); string? normalizedToolName = NormalizeOptionalString(toolName); string? requestedUrl = request is PermissionRequestUrl urlRequest @@ -191,7 +192,7 @@ internal sealed class CopilotApprovalCoordinator SessionId = command.SessionId, ApprovalId = approvalId, ApprovalKind = ToolCallApprovalKind, - AgentId = NormalizeOptionalString(agent.Id), + AgentId = NormalizeOptionalString(agentId), AgentName = NormalizeOptionalString(agentName), ToolName = normalizedToolName, PermissionKind = permissionKind, @@ -203,7 +204,7 @@ internal sealed class CopilotApprovalCoordinator internal static AgentActivityEventDto? BuildToolCallFileChangeActivity( RunTurnCommandDto command, - PatternAgentDefinitionDto agent, + WorkflowNodeDto agent, PermissionRequest request, string? toolName) { @@ -218,14 +219,15 @@ internal sealed class CopilotApprovalCoordinator return null; } - string agentName = string.IsNullOrWhiteSpace(agent.Name) ? agent.Id : agent.Name; + string agentId = agent.GetAgentId(); + string agentName = agent.GetAgentName(); return new AgentActivityEventDto { Type = "agent-activity", RequestId = command.RequestId, SessionId = command.SessionId, ActivityType = ToolCallingActivityType, - AgentId = NormalizeOptionalString(agent.Id), + AgentId = NormalizeOptionalString(agentId), AgentName = NormalizeOptionalString(agentName), ToolName = NormalizeOptionalString(toolName), ToolCallId = NormalizeOptionalString(write.ToolCallId), diff --git a/sidecar/src/Aryx.AgentHost/Services/CopilotExitPlanModeCoordinator.cs b/sidecar/src/Aryx.AgentHost/Services/CopilotExitPlanModeCoordinator.cs index d272fd9..f3f8260 100644 --- a/sidecar/src/Aryx.AgentHost/Services/CopilotExitPlanModeCoordinator.cs +++ b/sidecar/src/Aryx.AgentHost/Services/CopilotExitPlanModeCoordinator.cs @@ -11,7 +11,7 @@ internal sealed class CopilotExitPlanModeCoordinator public ExitPlanModeRequestedEventDto RecordExitPlanModeRequest( RunTurnCommandDto command, - PatternAgentDefinitionDto agent, + WorkflowNodeDto agent, ExitPlanModeRequestedEvent request) { ArgumentNullException.ThrowIfNull(command); @@ -33,7 +33,7 @@ internal sealed class CopilotExitPlanModeCoordinator internal static ExitPlanModeRequestedEventDto BuildExitPlanModeRequestedEvent( RunTurnCommandDto command, - PatternAgentDefinitionDto agent, + WorkflowNodeDto agent, ExitPlanModeRequestedEvent request) { ArgumentNullException.ThrowIfNull(command); @@ -45,8 +45,8 @@ internal sealed class CopilotExitPlanModeCoordinator string exitPlanId = NormalizeOptionalString(requestData.RequestId) ?? throw new InvalidOperationException("Exit plan mode request ID is required."); - string? normalizedAgentId = NormalizeOptionalString(agent.Id); - string? normalizedAgentName = NormalizeOptionalString(agent.Name) ?? normalizedAgentId; + string? normalizedAgentId = NormalizeOptionalString(agent.GetAgentId()); + string? normalizedAgentName = NormalizeOptionalString(agent.GetAgentName()) ?? normalizedAgentId; return new ExitPlanModeRequestedEventDto { diff --git a/sidecar/src/Aryx.AgentHost/Services/CopilotMcpOAuthCoordinator.cs b/sidecar/src/Aryx.AgentHost/Services/CopilotMcpOAuthCoordinator.cs index 8e32ce8..2d68986 100644 --- a/sidecar/src/Aryx.AgentHost/Services/CopilotMcpOAuthCoordinator.cs +++ b/sidecar/src/Aryx.AgentHost/Services/CopilotMcpOAuthCoordinator.cs @@ -7,7 +7,7 @@ internal sealed class CopilotMcpOAuthCoordinator { public McpOauthRequiredEventDto BuildMcpOauthRequiredEvent( RunTurnCommandDto command, - PatternAgentDefinitionDto agent, + WorkflowNodeDto agent, McpOauthRequiredEvent request) { ArgumentNullException.ThrowIfNull(command); @@ -19,8 +19,8 @@ internal sealed class CopilotMcpOAuthCoordinator string oauthRequestId = NormalizeOptionalString(requestData.RequestId) ?? throw new InvalidOperationException("MCP OAuth request ID is required."); - string? normalizedAgentId = NormalizeOptionalString(agent.Id); - string? normalizedAgentName = NormalizeOptionalString(agent.Name) ?? normalizedAgentId; + string? normalizedAgentId = NormalizeOptionalString(agent.GetAgentId()); + string? normalizedAgentName = NormalizeOptionalString(agent.GetAgentName()) ?? normalizedAgentId; return new McpOauthRequiredEventDto { diff --git a/sidecar/src/Aryx.AgentHost/Services/CopilotSessionHooks.cs b/sidecar/src/Aryx.AgentHost/Services/CopilotSessionHooks.cs index f4be24f..6886186 100644 --- a/sidecar/src/Aryx.AgentHost/Services/CopilotSessionHooks.cs +++ b/sidecar/src/Aryx.AgentHost/Services/CopilotSessionHooks.cs @@ -40,7 +40,7 @@ internal static class CopilotSessionHooks public static SessionHooks Create( RunTurnCommandDto command, - PatternAgentDefinitionDto agentDefinition, + WorkflowNodeDto agentDefinition, ResolvedHookSet? configuredHooks = null, IHookCommandRunner? hookCommandRunner = null) { @@ -62,7 +62,7 @@ internal static class CopilotSessionHooks private static async Task CreatePreToolUseOutputAsync( RunTurnCommandDto command, - PatternAgentDefinitionDto agentDefinition, + WorkflowNodeDto agentDefinition, ResolvedHookSet configuredHooks, IHookCommandRunner hookCommandRunner, PreToolUseHookInput input) @@ -236,7 +236,7 @@ internal static class CopilotSessionHooks private static PreToolUseHookOutput CreateApprovalPolicyOutput( RunTurnCommandDto command, - PatternAgentDefinitionDto agentDefinition, + WorkflowNodeDto agentDefinition, PreToolUseHookInput input) { string? toolName = Normalize(input.ToolName); @@ -254,8 +254,8 @@ internal static class CopilotSessionHooks command.Tooling?.McpServers); bool requiresApproval = CopilotApprovalCoordinator.RequiresToolCallApproval( - command.Pattern.ApprovalPolicy, - agentDefinition.Id, + command.Workflow.Settings.ApprovalPolicy, + agentDefinition.GetAgentId(), toolName, autoApprovedToolName, mcpServerApprovalKey); diff --git a/sidecar/src/Aryx.AgentHost/Services/CopilotTurnExecutionState.cs b/sidecar/src/Aryx.AgentHost/Services/CopilotTurnExecutionState.cs index bfefc99..0b0aa52 100644 --- a/sidecar/src/Aryx.AgentHost/Services/CopilotTurnExecutionState.cs +++ b/sidecar/src/Aryx.AgentHost/Services/CopilotTurnExecutionState.cs @@ -65,12 +65,12 @@ internal sealed class CopilotTurnExecutionState } } - public void ObserveSessionEvent(PatternAgentDefinitionDto agentDefinition, SessionEvent sessionEvent) + public void ObserveSessionEvent(WorkflowNodeDto agentDefinition, SessionEvent sessionEvent) { AgentIdentity agent = AgentIdentityResolver.ResolveAgentIdentity( - _command.Pattern, - agentDefinition.Id, - agentDefinition.Name); + _command.Workflow, + agentDefinition.GetAgentId(), + agentDefinition.GetAgentName()); switch (sessionEvent) { diff --git a/sidecar/src/Aryx.AgentHost/Services/CopilotUserInputCoordinator.cs b/sidecar/src/Aryx.AgentHost/Services/CopilotUserInputCoordinator.cs index 089c98f..cf59802 100644 --- a/sidecar/src/Aryx.AgentHost/Services/CopilotUserInputCoordinator.cs +++ b/sidecar/src/Aryx.AgentHost/Services/CopilotUserInputCoordinator.cs @@ -32,7 +32,7 @@ internal sealed class CopilotUserInputCoordinator public async Task RequestUserInputAsync( RunTurnCommandDto command, - PatternAgentDefinitionDto agent, + WorkflowNodeDto agent, UserInputRequest request, UserInputInvocation invocation, Func onUserInput, @@ -46,8 +46,8 @@ internal sealed class CopilotUserInputCoordinator return await RequestUserInputCoreAsync( command, - agent.Id, - agent.Name, + agent.GetAgentId(), + agent.GetAgentName(), request, onUserInput, cancellationToken).ConfigureAwait(false); @@ -74,7 +74,7 @@ internal sealed class CopilotUserInputCoordinator internal static UserInputRequestedEventDto BuildUserInputRequestedEvent( RunTurnCommandDto command, - PatternAgentDefinitionDto agent, + WorkflowNodeDto agent, UserInputRequest request, string userInputId) { @@ -82,8 +82,8 @@ internal sealed class CopilotUserInputCoordinator ArgumentNullException.ThrowIfNull(agent); ArgumentNullException.ThrowIfNull(request); - string? normalizedAgentId = NormalizeOptionalString(agent.Id); - string? normalizedAgentName = NormalizeOptionalString(agent.Name) ?? normalizedAgentId; + string? normalizedAgentId = NormalizeOptionalString(agent.GetAgentId()); + string? normalizedAgentName = NormalizeOptionalString(agent.GetAgentName()) ?? normalizedAgentId; return new UserInputRequestedEventDto { diff --git a/sidecar/src/Aryx.AgentHost/Services/CopilotWorkflowRunner.cs b/sidecar/src/Aryx.AgentHost/Services/CopilotWorkflowRunner.cs index 6a5ebdf..c8b19f7 100644 --- a/sidecar/src/Aryx.AgentHost/Services/CopilotWorkflowRunner.cs +++ b/sidecar/src/Aryx.AgentHost/Services/CopilotWorkflowRunner.cs @@ -14,7 +14,6 @@ namespace Aryx.AgentHost.Services; public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner { private const string HandoffFunctionPrefix = "handoff_to_"; - private readonly PatternValidator _patternValidator; private readonly WorkflowValidator _workflowValidator; private readonly WorkflowRunner _workflowRunner = new(); private readonly CopilotApprovalCoordinator _approvalCoordinator = new(); @@ -22,9 +21,8 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner private readonly CopilotMcpOAuthCoordinator _mcpOAuthCoordinator = new(); private readonly CopilotExitPlanModeCoordinator _exitPlanModeCoordinator = new(); - public CopilotWorkflowRunner(PatternValidator patternValidator, WorkflowValidator? workflowValidator = null) + public CopilotWorkflowRunner(WorkflowValidator? workflowValidator = null) { - _patternValidator = patternValidator; _workflowValidator = workflowValidator ?? new WorkflowValidator(); } @@ -38,9 +36,8 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner Func onExitPlanMode, CancellationToken cancellationToken) { - string? validationError = command.Workflow is null - ? _patternValidator.Validate(command.Pattern).FirstOrDefault()?.Message - : _workflowValidator.Validate(command.Workflow, command.WorkflowLibrary).FirstOrDefault()?.Message; + string? validationError = _workflowValidator.Validate(command.Workflow, command.WorkflowLibrary) + .FirstOrDefault()?.Message; if (validationError is not null) { throw new InvalidOperationException(validationError); @@ -87,9 +84,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner }, runCancellation.Token); ConfigureHookLifecycleEventSuppression(state, bundle); - Workflow workflow = command.Workflow is null - ? bundle.BuildWorkflow(command.Pattern) - : _workflowRunner.BuildWorkflow(command.Workflow, command.Pattern, bundle.Agents, command.WorkflowLibrary); + Workflow workflow = _workflowRunner.BuildWorkflow(command.Workflow, bundle.Agents, command.WorkflowLibrary); List inputMessages = command.Messages.Select(WorkflowTranscriptProjector.ToChatMessage).ToList(); WorkflowTranscriptProjector.AttachMessageMode(inputMessages, command.MessageMode); @@ -166,12 +161,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner internal static bool ShouldEnableWorkflowCheckpointing(RunTurnCommandDto command) { ArgumentNullException.ThrowIfNull(command); - if (command.Workflow is not null) - { - return command.Workflow.Settings.Checkpointing.Enabled; - } - - return string.Equals(command.Pattern.Mode, "handoff", StringComparison.OrdinalIgnoreCase); + return command.Workflow.Settings.Checkpointing.Enabled; } internal static string GetCheckpointStorePath(RunTurnCommandDto command) @@ -210,7 +200,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner { ArgumentNullException.ThrowIfNull(command); - string executionMode = command.Workflow?.Settings.ExecutionMode?.Trim() ?? "off-thread"; + string executionMode = command.Workflow.Settings.ExecutionMode?.Trim() ?? "off-thread"; InProcessExecutionEnvironment environment = string.Equals( executionMode, "lockstep", @@ -300,7 +290,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner if (evt is ExecutorInvokedEvent invoked) { if (AgentIdentityResolver.TryResolveKnownAgentIdentity( - command.Pattern, + command.Workflow, invoked.ExecutorId, out AgentIdentity invokedAgent)) { @@ -357,7 +347,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner if (evt is ExecutorCompletedEvent completed) { if (AgentIdentityResolver.TryResolveObservedAgentIdentity( - command.Pattern, + command.Workflow, completed.ExecutorId, state.ActiveAgent, out AgentIdentity completedAgent)) @@ -471,7 +461,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner authorName = observedMessageAgent.AgentName; } else if (AgentIdentityResolver.TryResolveObservedAgentIdentity( - command.Pattern, + command.Workflow, update.ExecutorId, state.ActiveAgent, out AgentIdentity resolvedUpdateAgent)) @@ -594,7 +584,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner case ExecutorFailedEvent executorFailed: { AgentIdentity? agent = AgentIdentityResolver.TryResolveObservedAgentIdentity( - command.Pattern, + command.Workflow, executorFailed.ExecutorId, state.ActiveAgent, out AgentIdentity resolvedAgent) @@ -754,7 +744,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner private static void TraceHandoff(RunTurnCommandDto command, string message) { - if (!string.Equals(command.Pattern.Mode, "handoff", StringComparison.OrdinalIgnoreCase)) + if (!command.Workflow.IsOrchestrationMode("handoff")) { return; } diff --git a/sidecar/src/Aryx.AgentHost/Services/HandoffWorkflowGuidance.cs b/sidecar/src/Aryx.AgentHost/Services/HandoffWorkflowGuidance.cs index 676aa15..3998995 100644 --- a/sidecar/src/Aryx.AgentHost/Services/HandoffWorkflowGuidance.cs +++ b/sidecar/src/Aryx.AgentHost/Services/HandoffWorkflowGuidance.cs @@ -21,17 +21,17 @@ internal static class HandoffWorkflowGuidance """; } - public static string CreateForwardReason(PatternAgentDefinitionDto target) + public static string CreateForwardReason(WorkflowNodeDto target) { - string specialty = string.IsNullOrWhiteSpace(target.Description) - ? target.Name - : target.Description.TrimEnd('.'); + string specialty = string.IsNullOrWhiteSpace(target.Config.Description) + ? target.GetAgentName() + : target.Config.Description.TrimEnd('.'); - return $"Hand off when the request primarily concerns {specialty}. Once handed off, let {target.Name} own the substantive response."; + return $"Hand off when the request primarily concerns {specialty}. Once handed off, let {target.GetAgentName()} own the substantive response."; } - public static string CreateReturnReason(PatternAgentDefinitionDto triageAgent) + public static string CreateReturnReason(WorkflowNodeDto triageAgent) { - return $"Hand off back to {triageAgent.Name} only when the task needs re-routing, cross-specialist coordination, or is outside your specialty."; + return $"Hand off back to {triageAgent.GetAgentName()} only when the task needs re-routing, cross-specialist coordination, or is outside your specialty."; } } diff --git a/sidecar/src/Aryx.AgentHost/Services/PatternGraphResolver.cs b/sidecar/src/Aryx.AgentHost/Services/PatternGraphResolver.cs deleted file mode 100644 index c7f218b..0000000 --- a/sidecar/src/Aryx.AgentHost/Services/PatternGraphResolver.cs +++ /dev/null @@ -1,345 +0,0 @@ -using Aryx.AgentHost.Contracts; - -namespace Aryx.AgentHost.Services; - -internal sealed record PatternHandoffRoute(string SourceAgentId, string TargetAgentId); - -internal sealed record PatternHandoffTopology(string EntryAgentId, IReadOnlyList Routes); - -internal static class PatternGraphResolver -{ - private const string UserInputKind = "user-input"; - private const string UserOutputKind = "user-output"; - private const string AgentKind = "agent"; - private const string DistributorKind = "distributor"; - private const string CollectorKind = "collector"; - private const string OrchestratorKind = "orchestrator"; - - private static readonly StringComparer Comparer = StringComparer.OrdinalIgnoreCase; - - public static PatternGraphDto Resolve(PatternDefinitionDto pattern) - => pattern.Graph ?? CreateDefault(pattern); - - public static IReadOnlyList ResolveOrderedAgentIds(PatternDefinitionDto pattern) - { - PatternGraphDto graph = Resolve(pattern); - - return pattern.Mode switch - { - "single" or "sequential" or "magentic" => ResolveLinearAgentIds(pattern, graph), - "concurrent" or "group-chat" or "handoff" => ResolveAgentOrder(pattern, graph), - _ => pattern.Agents.Select(agent => agent.Id).ToList() - }; - } - - public static PatternHandoffTopology ResolveHandoff(PatternDefinitionDto pattern) - { - return TryResolveHandoff(pattern, Resolve(pattern)) - ?? TryResolveHandoff(pattern, CreateDefault(pattern)) - ?? new PatternHandoffTopology( - pattern.Agents.FirstOrDefault()?.Id ?? string.Empty, - []); - } - - public static PatternGraphDto CreateDefault(PatternDefinitionDto pattern) - { - return pattern.Mode switch - { - "single" or "sequential" or "magentic" => CreateLinearGraph(pattern.Agents), - "concurrent" => CreateConcurrentGraph(pattern.Agents), - "handoff" => CreateHandoffGraph(pattern.Agents), - "group-chat" => CreateGroupChatGraph(pattern.Agents), - _ => CreateLinearGraph(pattern.Agents) - }; - } - - private static IReadOnlyList ResolveLinearAgentIds(PatternDefinitionDto pattern, PatternGraphDto graph) - { - PatternGraphNodeDto? inputNode = GetNodeByKind(graph, UserInputKind); - PatternGraphNodeDto? outputNode = GetNodeByKind(graph, UserOutputKind); - if (inputNode is null || outputNode is null) - { - return pattern.Agents.Select(agent => agent.Id).ToList(); - } - - Dictionary nodesById = graph.Nodes.ToDictionary(node => node.Id, node => node); - Dictionary> outgoing = BuildOutgoingLookup(graph); - List orderedAgentIds = []; - HashSet visitedNodeIds = []; - string currentNodeId = inputNode.Id; - - while (visitedNodeIds.Add(currentNodeId)) - { - if (!outgoing.TryGetValue(currentNodeId, out List? edges) || edges.Count != 1) - { - break; - } - - string nextNodeId = edges[0].Target; - if (!nodesById.TryGetValue(nextNodeId, out PatternGraphNodeDto? nextNode)) - { - break; - } - - if (Comparer.Equals(nextNode.Id, outputNode.Id)) - { - break; - } - - if (Comparer.Equals(nextNode.Kind, AgentKind) && !string.IsNullOrWhiteSpace(nextNode.AgentId)) - { - orderedAgentIds.Add(nextNode.AgentId); - } - - currentNodeId = nextNodeId; - } - - return orderedAgentIds.Count == pattern.Agents.Count - ? orderedAgentIds - : pattern.Agents.Select(agent => agent.Id).ToList(); - } - - private static IReadOnlyList ResolveAgentOrder(PatternDefinitionDto pattern, PatternGraphDto graph) - { - Dictionary fallbackOrder = pattern.Agents - .Select((agent, index) => new { agent.Id, Index = index }) - .ToDictionary(item => item.Id, item => item.Index); - - List orderedAgentIds = graph.Nodes - .Where(node => Comparer.Equals(node.Kind, AgentKind) && !string.IsNullOrWhiteSpace(node.AgentId)) - .OrderBy(node => node.Order ?? int.MaxValue) - .ThenBy(node => fallbackOrder.GetValueOrDefault(node.AgentId!, int.MaxValue)) - .Select(node => node.AgentId!) - .Distinct() - .ToList(); - - return orderedAgentIds.Count == pattern.Agents.Count - ? orderedAgentIds - : pattern.Agents.Select(agent => agent.Id).ToList(); - } - - private static PatternHandoffTopology? TryResolveHandoff(PatternDefinitionDto pattern, PatternGraphDto graph) - { - Dictionary nodesById = graph.Nodes.ToDictionary(node => node.Id, node => node); - PatternGraphNodeDto? inputNode = GetNodeByKind(graph, UserInputKind); - string? entryAgentId = null; - - if (inputNode is not null) - { - entryAgentId = graph.Edges - .Where(edge => Comparer.Equals(edge.Source, inputNode.Id)) - .Select(edge => nodesById.TryGetValue(edge.Target, out PatternGraphNodeDto? targetNode) - ? targetNode.AgentId - : null) - .FirstOrDefault(agentId => !string.IsNullOrWhiteSpace(agentId)); - } - - List routes = graph.Edges - .Select(edge => (SourceNode: nodesById.GetValueOrDefault(edge.Source), TargetNode: nodesById.GetValueOrDefault(edge.Target))) - .Where(item => - item.SourceNode is not null - && item.TargetNode is not null - && Comparer.Equals(item.SourceNode.Kind, AgentKind) - && Comparer.Equals(item.TargetNode.Kind, AgentKind) - && !string.IsNullOrWhiteSpace(item.SourceNode.AgentId) - && !string.IsNullOrWhiteSpace(item.TargetNode.AgentId)) - .Select(item => new PatternHandoffRoute(item.SourceNode!.AgentId!, item.TargetNode!.AgentId!)) - .Distinct() - .ToList(); - - if (string.IsNullOrWhiteSpace(entryAgentId) || routes.Count == 0) - { - return null; - } - - return new PatternHandoffTopology(entryAgentId!, routes); - } - - private static Dictionary> BuildOutgoingLookup(PatternGraphDto graph) - { - Dictionary> lookup = new(StringComparer.Ordinal); - foreach (PatternGraphNodeDto node in graph.Nodes) - { - lookup[node.Id] = []; - } - - foreach (PatternGraphEdgeDto edge in graph.Edges) - { - if (!lookup.TryGetValue(edge.Source, out List? edges)) - { - edges = []; - lookup[edge.Source] = edges; - } - - edges.Add(edge); - } - - return lookup; - } - - private static PatternGraphNodeDto? GetNodeByKind(PatternGraphDto graph, string kind) - => graph.Nodes.FirstOrDefault(node => Comparer.Equals(node.Kind, kind)); - - private static PatternGraphDto CreateLinearGraph(IReadOnlyList agents) - { - PatternGraphNodeDto inputNode = CreateSystemNode("system-user-input", UserInputKind, 0, 0); - PatternGraphNodeDto outputNode = CreateSystemNode("system-user-output", UserOutputKind, 220 * Math.Max(agents.Count + 1, 2), 0); - List agentNodes = agents - .Select((agent, index) => CreateAgentNode(agent, index, 220 * (index + 1), 0)) - .ToList(); - List edges = []; - List path = [inputNode.Id, .. agentNodes.Select(node => node.Id), outputNode.Id]; - for (int index = 0; index < path.Count - 1; index += 1) - { - edges.Add(CreateEdge(path[index], path[index + 1])); - } - - return new PatternGraphDto - { - Nodes = [inputNode, .. agentNodes, outputNode], - Edges = edges - }; - } - - private static PatternGraphDto CreateConcurrentGraph(IReadOnlyList agents) - { - PatternGraphNodeDto inputNode = CreateSystemNode("system-user-input", UserInputKind, 0, 0); - PatternGraphNodeDto distributorNode = CreateSystemNode("system-distributor", DistributorKind, 190, 0); - PatternGraphNodeDto collectorNode = CreateSystemNode("system-collector", CollectorKind, 650, 0); - PatternGraphNodeDto outputNode = CreateSystemNode("system-user-output", UserOutputKind, 860, 0); - List agentNodes = agents - .Select((agent, index) => CreateAgentNode(agent, index, 430, SpreadY(index, Math.Max(agents.Count, 1), 170))) - .ToList(); - - return new PatternGraphDto - { - Nodes = [inputNode, distributorNode, .. agentNodes, collectorNode, outputNode], - Edges = - [ - CreateEdge(inputNode.Id, distributorNode.Id), - .. agentNodes.Select(node => CreateEdge(distributorNode.Id, node.Id)), - .. agentNodes.Select(node => CreateEdge(node.Id, collectorNode.Id)), - CreateEdge(collectorNode.Id, outputNode.Id) - ] - }; - } - - private static PatternGraphDto CreateHandoffGraph(IReadOnlyList agents) - { - PatternGraphNodeDto inputNode = CreateSystemNode("system-user-input", UserInputKind, 0, 0); - PatternGraphNodeDto outputNode = CreateSystemNode("system-user-output", UserOutputKind, 860, 0); - PatternAgentDefinitionDto? entryAgent = agents.FirstOrDefault(); - PatternGraphNodeDto? entryNode = entryAgent is null - ? null - : CreateAgentNode(entryAgent, 0, 220, 0); - List specialistNodes = agents - .Skip(1) - .Select((agent, index) => CreateAgentNode(agent, index + 1, 540, SpreadY(index, Math.Max(agents.Count - 1, 1), 220))) - .ToList(); - - List edges = []; - if (entryNode is not null) - { - edges.Add(CreateEdge(inputNode.Id, entryNode.Id)); - edges.Add(CreateEdge(entryNode.Id, outputNode.Id)); - - foreach (PatternGraphNodeDto specialistNode in specialistNodes) - { - edges.Add(CreateEdge(entryNode.Id, specialistNode.Id)); - edges.Add(CreateEdge(specialistNode.Id, entryNode.Id)); - edges.Add(CreateEdge(specialistNode.Id, outputNode.Id)); - } - } - - List nodes = [inputNode]; - if (entryNode is not null) - { - nodes.Add(entryNode); - } - nodes.AddRange(specialistNodes); - nodes.Add(outputNode); - - return new PatternGraphDto - { - Nodes = nodes, - Edges = edges - }; - } - - private static PatternGraphDto CreateGroupChatGraph(IReadOnlyList agents) - { - PatternGraphNodeDto inputNode = CreateSystemNode("system-user-input", UserInputKind, 0, 0); - PatternGraphNodeDto orchestratorNode = CreateSystemNode("system-orchestrator", OrchestratorKind, 250, 0); - PatternGraphNodeDto outputNode = CreateSystemNode("system-user-output", UserOutputKind, 900, 0); - const double centerX = 560; - const double centerY = 0; - const double radiusX = 190; - const double radiusY = 170; - - List agentNodes = agents - .Select((agent, index) => - { - double angle = agents.Count <= 1 - ? 0 - : (Math.PI * 2 * index) / agents.Count - (Math.PI / 2); - return CreateAgentNode( - agent, - index, - Math.Round(centerX + Math.Cos(angle) * radiusX), - Math.Round(centerY + Math.Sin(angle) * radiusY)); - }) - .ToList(); - - return new PatternGraphDto - { - Nodes = [inputNode, orchestratorNode, .. agentNodes, outputNode], - Edges = - [ - CreateEdge(inputNode.Id, orchestratorNode.Id), - .. agentNodes.SelectMany(node => new[] - { - CreateEdge(orchestratorNode.Id, node.Id), - CreateEdge(node.Id, orchestratorNode.Id) - }), - CreateEdge(orchestratorNode.Id, outputNode.Id) - ] - }; - } - - private static PatternGraphNodeDto CreateSystemNode(string id, string kind, double x, double y) - => new() - { - Id = id, - Kind = kind, - Position = new PatternGraphPositionDto - { - X = x, - Y = y - } - }; - - private static PatternGraphNodeDto CreateAgentNode(PatternAgentDefinitionDto agent, int order, double x, double y) - => new() - { - Id = $"agent-node-{agent.Id}", - Kind = AgentKind, - AgentId = agent.Id, - Order = order, - Position = new PatternGraphPositionDto - { - X = x, - Y = y - } - }; - - private static PatternGraphEdgeDto CreateEdge(string source, string target) - => new() - { - Id = $"edge-{source}-to-{target}", - Source = source, - Target = target - }; - - private static double SpreadY(int index, int count, double gap) - => (index - ((count - 1) / 2d)) * gap; -} diff --git a/sidecar/src/Aryx.AgentHost/Services/PatternValidator.cs b/sidecar/src/Aryx.AgentHost/Services/PatternValidator.cs deleted file mode 100644 index b87a47e..0000000 --- a/sidecar/src/Aryx.AgentHost/Services/PatternValidator.cs +++ /dev/null @@ -1,573 +0,0 @@ -using Aryx.AgentHost.Contracts; - -namespace Aryx.AgentHost.Services; - -public sealed class PatternValidator -{ - private static readonly StringComparer Comparer = StringComparer.OrdinalIgnoreCase; - - public IReadOnlyList Validate(PatternDefinitionDto pattern) - { - List issues = []; - - if (string.IsNullOrWhiteSpace(pattern.Name)) - { - issues.Add(new PatternValidationIssueDto - { - Field = "name", - Message = "Pattern name is required.", - }); - } - - if (string.Equals(pattern.Availability, "unavailable", StringComparison.OrdinalIgnoreCase)) - { - issues.Add(new PatternValidationIssueDto - { - Field = "availability", - Message = pattern.UnavailabilityReason ?? "This orchestration mode is currently unavailable.", - }); - } - - if (pattern.Agents.Count == 0) - { - issues.Add(new PatternValidationIssueDto - { - Field = "agents", - Message = "At least one agent is required.", - }); - } - - if (string.Equals(pattern.Mode, "single", StringComparison.OrdinalIgnoreCase) && pattern.Agents.Count != 1) - { - issues.Add(new PatternValidationIssueDto - { - Field = "agents", - Message = "Single-agent chat requires exactly one agent.", - }); - } - - if (string.Equals(pattern.Mode, "handoff", StringComparison.OrdinalIgnoreCase) && pattern.Agents.Count < 2) - { - issues.Add(new PatternValidationIssueDto - { - Field = "agents", - Message = "Handoff orchestration requires at least two agents.", - }); - } - - if (string.Equals(pattern.Mode, "group-chat", StringComparison.OrdinalIgnoreCase) && pattern.Agents.Count < 2) - { - issues.Add(new PatternValidationIssueDto - { - Field = "agents", - Message = "Group chat requires at least two agents.", - }); - } - - if (string.Equals(pattern.Mode, "magentic", StringComparison.OrdinalIgnoreCase)) - { - issues.Add(new PatternValidationIssueDto - { - Field = "mode", - Message = pattern.UnavailabilityReason - ?? "Magentic orchestration is currently documented as unsupported in the .NET Agent Framework.", - }); - } - - foreach (PatternAgentDefinitionDto agent in pattern.Agents) - { - if (string.IsNullOrWhiteSpace(agent.Name)) - { - issues.Add(new PatternValidationIssueDto - { - Field = "agents.name", - Message = "Every agent needs a name.", - }); - } - - if (string.IsNullOrWhiteSpace(agent.Model)) - { - issues.Add(new PatternValidationIssueDto - { - Field = "agents.model", - Message = $"Agent \"{agent.Name}\" requires a model identifier.", - }); - } - } - - ValidateGraph(pattern, PatternGraphResolver.Resolve(pattern), issues); - return issues; - } - - private static void ValidateGraph( - PatternDefinitionDto pattern, - PatternGraphDto graph, - List issues) - { - if (graph.Nodes.Count == 0) - { - AddGraphIssue(issues, "Pattern graph must include nodes."); - return; - } - - HashSet nodeIds = new(StringComparer.Ordinal); - HashSet edgeIds = new(StringComparer.Ordinal); - HashSet agentIds = pattern.Agents.Select(agent => agent.Id).ToHashSet(StringComparer.Ordinal); - HashSet seenAgentIds = new(StringComparer.Ordinal); - HashSet seenAgentOrders = []; - Dictionary nodesById = new(StringComparer.Ordinal); - - foreach (PatternGraphNodeDto node in graph.Nodes) - { - if (!nodeIds.Add(node.Id)) - { - AddGraphIssue(issues, $"Pattern graph contains duplicate node \"{node.Id}\"."); - } - - nodesById[node.Id] = node; - - if (Comparer.Equals(node.Kind, "agent")) - { - if (string.IsNullOrWhiteSpace(node.AgentId) || !agentIds.Contains(node.AgentId)) - { - AddGraphIssue(issues, $"Agent node \"{node.Id}\" must reference a known agent."); - } - - if (!string.IsNullOrWhiteSpace(node.AgentId) && !seenAgentIds.Add(node.AgentId)) - { - AddGraphIssue(issues, $"Pattern graph contains multiple nodes for agent \"{node.AgentId}\"."); - } - - if (!node.Order.HasValue) - { - AddGraphIssue(issues, $"Agent node \"{node.Id}\" must define an order."); - } - else if (!seenAgentOrders.Add(node.Order.Value)) - { - AddGraphIssue(issues, $"Pattern graph contains duplicate agent order \"{node.Order.Value}\"."); - } - } - else if (!string.IsNullOrWhiteSpace(node.AgentId)) - { - AddGraphIssue(issues, $"System node \"{node.Id}\" cannot reference an agent."); - } - } - - foreach (PatternAgentDefinitionDto agent in pattern.Agents) - { - if (!seenAgentIds.Contains(agent.Id)) - { - AddGraphIssue(issues, $"Pattern graph is missing node metadata for agent \"{agent.Id}\"."); - } - } - - foreach (PatternGraphEdgeDto edge in graph.Edges) - { - if (!edgeIds.Add(edge.Id)) - { - AddGraphIssue(issues, $"Pattern graph contains duplicate edge \"{edge.Id}\"."); - } - - if (!nodesById.ContainsKey(edge.Source) || !nodesById.ContainsKey(edge.Target)) - { - AddGraphIssue(issues, $"Pattern graph edge \"{edge.Id}\" must connect known nodes."); - } - } - - switch (pattern.Mode) - { - case "single": - case "sequential": - case "magentic": - ValidateLinearGraph(pattern, graph, issues); - break; - case "concurrent": - ValidateConcurrentGraph(pattern, graph, issues); - break; - case "handoff": - ValidateHandoffGraph(graph, issues); - break; - case "group-chat": - ValidateGroupChatGraph(pattern, graph, issues); - break; - } - } - - private static void ValidateLinearGraph( - PatternDefinitionDto pattern, - PatternGraphDto graph, - List issues) - { - ValidateSystemNodeCounts(graph, ["user-input", "user-output"], issues); - PatternGraphNodeDto? inputNode = GetNodeByKind(graph, "user-input"); - PatternGraphNodeDto? outputNode = GetNodeByKind(graph, "user-output"); - if (inputNode is null || outputNode is null) - { - return; - } - - Dictionary> incoming = BuildIncomingLookup(graph); - Dictionary> outgoing = BuildOutgoingLookup(graph); - List agentNodes = GetAgentNodes(graph); - - if (graph.Edges.Count != pattern.Agents.Count + 1) - { - AddGraphIssue(issues, "Linear orchestration graphs must be a single path from user input through every agent to user output."); - } - - if (incoming.GetValueOrDefault(inputNode.Id, []).Count != 0 || outgoing.GetValueOrDefault(inputNode.Id, []).Count != 1) - { - AddGraphIssue(issues, "User input must start exactly one path."); - } - - if (incoming.GetValueOrDefault(outputNode.Id, []).Count != 1 || outgoing.GetValueOrDefault(outputNode.Id, []).Count != 0) - { - AddGraphIssue(issues, "User output must terminate exactly one path."); - } - - foreach (PatternGraphNodeDto node in agentNodes) - { - if (incoming.GetValueOrDefault(node.Id, []).Count != 1 || outgoing.GetValueOrDefault(node.Id, []).Count != 1) - { - AddGraphIssue(issues, "Each agent in a linear orchestration must have exactly one incoming and one outgoing edge."); - break; - } - } - - HashSet visited = new(StringComparer.Ordinal); - string currentNodeId = inputNode.Id; - while (visited.Add(currentNodeId)) - { - List nextEdges = outgoing.GetValueOrDefault(currentNodeId, []); - if (nextEdges.Count == 0) - { - break; - } - - if (nextEdges.Count != 1) - { - AddGraphIssue(issues, "Linear orchestration nodes may only branch to one next step."); - break; - } - - currentNodeId = nextEdges[0].Target; - if (Comparer.Equals(currentNodeId, outputNode.Id)) - { - visited.Add(currentNodeId); - break; - } - } - - HashSet expectedVisited = new(StringComparer.Ordinal) - { - inputNode.Id, - outputNode.Id - }; - foreach (PatternGraphNodeDto node in agentNodes) - { - expectedVisited.Add(node.Id); - } - - if (!expectedVisited.SetEquals(visited)) - { - AddGraphIssue(issues, "Linear orchestration graphs must visit every agent exactly once."); - } - } - - private static void ValidateConcurrentGraph( - PatternDefinitionDto pattern, - PatternGraphDto graph, - List issues) - { - ValidateSystemNodeCounts(graph, ["user-input", "distributor", "collector", "user-output"], issues); - PatternGraphNodeDto? inputNode = GetNodeByKind(graph, "user-input"); - PatternGraphNodeDto? distributorNode = GetNodeByKind(graph, "distributor"); - PatternGraphNodeDto? collectorNode = GetNodeByKind(graph, "collector"); - PatternGraphNodeDto? outputNode = GetNodeByKind(graph, "user-output"); - if (inputNode is null || distributorNode is null || collectorNode is null || outputNode is null) - { - return; - } - - Dictionary> incoming = BuildIncomingLookup(graph); - Dictionary> outgoing = BuildOutgoingLookup(graph); - List agentNodes = GetAgentNodes(graph); - HashSet distributorTargets = outgoing.GetValueOrDefault(distributorNode.Id, []).Select(edge => edge.Target).ToHashSet(StringComparer.Ordinal); - HashSet collectorSources = incoming.GetValueOrDefault(collectorNode.Id, []).Select(edge => edge.Source).ToHashSet(StringComparer.Ordinal); - - if (graph.Edges.Count != pattern.Agents.Count * 2 + 2) - { - AddGraphIssue(issues, "Concurrent orchestration graphs must fan out from the distributor and fan back into the collector."); - } - - if (incoming.GetValueOrDefault(inputNode.Id, []).Count != 0 || outgoing.GetValueOrDefault(inputNode.Id, []).Count != 1) - { - AddGraphIssue(issues, "User input must connect only to the distributor."); - } - - if (incoming.GetValueOrDefault(distributorNode.Id, []).Count != 1) - { - AddGraphIssue(issues, "Distributor must receive exactly one edge from user input."); - } - - if (outgoing.GetValueOrDefault(collectorNode.Id, []).Count != 1 || incoming.GetValueOrDefault(outputNode.Id, []).Count != 1) - { - AddGraphIssue(issues, "Collector must forward exactly one edge to user output."); - } - - foreach (PatternGraphNodeDto agentNode in agentNodes) - { - if (!distributorTargets.Contains(agentNode.Id)) - { - AddGraphIssue(issues, $"Distributor must connect to agent \"{agentNode.AgentId}\"."); - } - - if (!collectorSources.Contains(agentNode.Id)) - { - AddGraphIssue(issues, $"Agent \"{agentNode.AgentId}\" must connect to the collector."); - } - } - } - - private static void ValidateHandoffGraph( - PatternGraphDto graph, - List issues) - { - ValidateSystemNodeCounts(graph, ["user-input", "user-output"], issues); - PatternGraphNodeDto? inputNode = GetNodeByKind(graph, "user-input"); - PatternGraphNodeDto? outputNode = GetNodeByKind(graph, "user-output"); - if (inputNode is null || outputNode is null) - { - return; - } - - Dictionary> incoming = BuildIncomingLookup(graph); - Dictionary> outgoing = BuildOutgoingLookup(graph); - List agentNodes = GetAgentNodes(graph); - HashSet agentNodeIds = agentNodes.Select(node => node.Id).ToHashSet(StringComparer.Ordinal); - List entryEdges = outgoing.GetValueOrDefault(inputNode.Id, []); - List completionEdges = incoming.GetValueOrDefault(outputNode.Id, []); - - if (entryEdges.Count != 1) - { - AddGraphIssue(issues, "Handoff graphs must connect user input to exactly one entry agent."); - return; - } - - if (!agentNodeIds.Contains(entryEdges[0].Target)) - { - AddGraphIssue(issues, "Handoff entry edges must target an agent node."); - } - - if (completionEdges.Count == 0) - { - AddGraphIssue(issues, "Handoff graphs must allow at least one agent to complete back to user output."); - } - - bool hasAgentToAgentRoute = false; - foreach (PatternGraphEdgeDto edge in graph.Edges) - { - if (Comparer.Equals(edge.Source, inputNode.Id)) - { - continue; - } - - if (Comparer.Equals(edge.Target, outputNode.Id)) - { - if (!agentNodeIds.Contains(edge.Source)) - { - AddGraphIssue(issues, "Only agent nodes may complete to user output."); - } - continue; - } - - if (!agentNodeIds.Contains(edge.Source) || !agentNodeIds.Contains(edge.Target)) - { - AddGraphIssue(issues, "Handoff routes may only connect agents to agents or agents to user output."); - continue; - } - - if (Comparer.Equals(edge.Source, edge.Target)) - { - AddGraphIssue(issues, "Handoff routes cannot target the same agent node."); - } - - hasAgentToAgentRoute = true; - } - - if (!hasAgentToAgentRoute && agentNodes.Count > 1) - { - AddGraphIssue(issues, "Handoff graphs must include at least one agent-to-agent handoff route."); - } - - HashSet reachable = new(StringComparer.Ordinal); - Stack stack = new Stack([entryEdges[0].Target]); - while (stack.Count > 0) - { - string nodeId = stack.Pop(); - if (!reachable.Add(nodeId)) - { - continue; - } - - foreach (PatternGraphEdgeDto edge in outgoing.GetValueOrDefault(nodeId, [])) - { - if (agentNodeIds.Contains(edge.Target) && !reachable.Contains(edge.Target)) - { - stack.Push(edge.Target); - } - } - } - - foreach (PatternGraphNodeDto agentNode in agentNodes) - { - if (!reachable.Contains(agentNode.Id)) - { - AddGraphIssue(issues, $"Handoff entry agent must be able to reach \"{agentNode.AgentId}\"."); - } - } - - if (incoming.GetValueOrDefault(inputNode.Id, []).Count != 0 || outgoing.GetValueOrDefault(outputNode.Id, []).Count != 0) - { - AddGraphIssue(issues, "User input cannot have incoming edges and user output cannot have outgoing edges."); - } - } - - private static void ValidateGroupChatGraph( - PatternDefinitionDto pattern, - PatternGraphDto graph, - List issues) - { - ValidateSystemNodeCounts(graph, ["user-input", "orchestrator", "user-output"], issues); - PatternGraphNodeDto? inputNode = GetNodeByKind(graph, "user-input"); - PatternGraphNodeDto? orchestratorNode = GetNodeByKind(graph, "orchestrator"); - PatternGraphNodeDto? outputNode = GetNodeByKind(graph, "user-output"); - if (inputNode is null || orchestratorNode is null || outputNode is null) - { - return; - } - - Dictionary> incoming = BuildIncomingLookup(graph); - Dictionary> outgoing = BuildOutgoingLookup(graph); - List agentNodes = GetAgentNodes(graph); - HashSet orchestratorTargets = outgoing.GetValueOrDefault(orchestratorNode.Id, []).Select(edge => edge.Target).ToHashSet(StringComparer.Ordinal); - HashSet orchestratorSources = incoming.GetValueOrDefault(orchestratorNode.Id, []).Select(edge => edge.Source).ToHashSet(StringComparer.Ordinal); - - if (graph.Edges.Count != pattern.Agents.Count * 2 + 2) - { - AddGraphIssue(issues, "Group chat graphs must connect the orchestrator to every participant and then back to user output."); - } - - if (outgoing.GetValueOrDefault(inputNode.Id, []).Any(edge => !Comparer.Equals(edge.Target, orchestratorNode.Id))) - { - AddGraphIssue(issues, "User input must only connect to the orchestrator."); - } - - if (!outgoing.GetValueOrDefault(orchestratorNode.Id, []).Any(edge => Comparer.Equals(edge.Target, outputNode.Id))) - { - AddGraphIssue(issues, "Group chat orchestrator must connect to user output."); - } - - foreach (PatternGraphNodeDto agentNode in agentNodes) - { - if (!orchestratorTargets.Contains(agentNode.Id)) - { - AddGraphIssue(issues, $"Orchestrator must connect to agent \"{agentNode.AgentId}\"."); - } - - if (!orchestratorSources.Contains(agentNode.Id)) - { - AddGraphIssue(issues, $"Agent \"{agentNode.AgentId}\" must connect back to the orchestrator."); - } - } - } - - private static void ValidateSystemNodeCounts( - PatternGraphDto graph, - IReadOnlyList expectedKinds, - List issues) - { - Dictionary counts = graph.Nodes - .GroupBy(node => node.Kind, Comparer) - .ToDictionary(group => group.Key, group => group.Count(), Comparer); - HashSet expected = expectedKinds.ToHashSet(Comparer); - - foreach (string kind in expectedKinds) - { - if (counts.GetValueOrDefault(kind, 0) != 1) - { - AddGraphIssue(issues, $"Pattern graph must include exactly one \"{kind}\" node."); - } - } - - foreach ((string kind, int count) in counts) - { - if (Comparer.Equals(kind, "agent")) - { - continue; - } - - if (!expected.Contains(kind) && count > 0) - { - AddGraphIssue(issues, $"Pattern graph does not allow \"{kind}\" nodes in this mode."); - } - } - } - - private static PatternGraphNodeDto? GetNodeByKind(PatternGraphDto graph, string kind) - => graph.Nodes.FirstOrDefault(node => Comparer.Equals(node.Kind, kind)); - - private static List GetAgentNodes(PatternGraphDto graph) - => graph.Nodes.Where(node => Comparer.Equals(node.Kind, "agent")).ToList(); - - private static Dictionary> BuildIncomingLookup(PatternGraphDto graph) - { - Dictionary> incoming = new(StringComparer.Ordinal); - foreach (PatternGraphNodeDto node in graph.Nodes) - { - incoming[node.Id] = []; - } - - foreach (PatternGraphEdgeDto edge in graph.Edges) - { - if (!incoming.TryGetValue(edge.Target, out List? edges)) - { - edges = []; - incoming[edge.Target] = edges; - } - - edges.Add(edge); - } - - return incoming; - } - - private static Dictionary> BuildOutgoingLookup(PatternGraphDto graph) - { - Dictionary> outgoing = new(StringComparer.Ordinal); - foreach (PatternGraphNodeDto node in graph.Nodes) - { - outgoing[node.Id] = []; - } - - foreach (PatternGraphEdgeDto edge in graph.Edges) - { - if (!outgoing.TryGetValue(edge.Source, out List? edges)) - { - edges = []; - outgoing[edge.Source] = edges; - } - - edges.Add(edge); - } - - return outgoing; - } - - private static void AddGraphIssue(List issues, string message) - => issues.Add(new PatternValidationIssueDto - { - Field = "graph", - Message = message, - }); -} diff --git a/sidecar/src/Aryx.AgentHost/Services/SidecarProtocolHost.cs b/sidecar/src/Aryx.AgentHost/Services/SidecarProtocolHost.cs index c6e3069..ef45277 100644 --- a/sidecar/src/Aryx.AgentHost/Services/SidecarProtocolHost.cs +++ b/sidecar/src/Aryx.AgentHost/Services/SidecarProtocolHost.cs @@ -10,7 +10,6 @@ namespace Aryx.AgentHost.Services; public sealed class SidecarProtocolHost { private const string DescribeCapabilitiesCommandType = "describe-capabilities"; - private const string ValidatePatternCommandType = "validate-pattern"; private const string ValidateWorkflowCommandType = "validate-workflow"; private const string RunTurnCommandType = "run-turn"; private const string CancelTurnCommandType = "cancel-turn"; @@ -42,7 +41,6 @@ public sealed class SidecarProtocolHost ]; private readonly Func> _capabilitiesProvider; - private readonly PatternValidator _patternValidator; private readonly WorkflowValidator _workflowValidator; private readonly ITurnWorkflowRunner _workflowRunner; private readonly ICopilotSessionManager _sessionManager; @@ -55,29 +53,26 @@ public sealed class SidecarProtocolHost new(StringComparer.Ordinal); public SidecarProtocolHost() - : this(new PatternValidator(), new WorkflowValidator()) + : this(new WorkflowValidator()) { } public SidecarProtocolHost( - PatternValidator patternValidator, ITurnWorkflowRunner? workflowRunner = null, Func>? capabilitiesProvider = null, ICopilotSessionManager? sessionManager = null) - : this(patternValidator, new WorkflowValidator(), workflowRunner, capabilitiesProvider, sessionManager) + : this(new WorkflowValidator(), workflowRunner, capabilitiesProvider, sessionManager) { } public SidecarProtocolHost( - PatternValidator patternValidator, WorkflowValidator workflowValidator, ITurnWorkflowRunner? workflowRunner = null, Func>? capabilitiesProvider = null, ICopilotSessionManager? sessionManager = null) { - _patternValidator = patternValidator; _workflowValidator = workflowValidator; - _workflowRunner = workflowRunner ?? new CopilotWorkflowRunner(_patternValidator, _workflowValidator); + _workflowRunner = workflowRunner ?? new CopilotWorkflowRunner(_workflowValidator); _capabilitiesProvider = capabilitiesProvider ?? BuildCapabilitiesAsync; _sessionManager = sessionManager ?? new CopilotSessionManager(); _jsonOptions = JsonSerialization.CreateWebOptions(); @@ -86,7 +81,6 @@ public sealed class SidecarProtocolHost _commandHandlers = new Dictionary>(StringComparer.Ordinal) { [DescribeCapabilitiesCommandType] = HandleDescribeCapabilitiesAsync, - [ValidatePatternCommandType] = HandleValidatePatternAsync, [ValidateWorkflowCommandType] = HandleValidateWorkflowAsync, [RunTurnCommandType] = HandleRunTurnAsync, [CancelTurnCommandType] = HandleCancelTurnAsync, @@ -182,18 +176,6 @@ public sealed class SidecarProtocolHost }, context.CancellationToken).ConfigureAwait(false); } - private async Task HandleValidatePatternAsync(CommandContext context) - { - ValidatePatternCommandDto command = DeserializeCommand(context); - - await WriteAsync(context.Output, new PatternValidationEventDto - { - Type = "pattern-validation", - RequestId = context.Envelope.RequestId, - Issues = _patternValidator.Validate(command.Pattern), - }, context.CancellationToken).ConfigureAwait(false); - } - private async Task HandleValidateWorkflowAsync(CommandContext context) { ValidateWorkflowCommandDto command = DeserializeCommand(context); diff --git a/sidecar/src/Aryx.AgentHost/Services/WorkflowDefinitionExtensions.cs b/sidecar/src/Aryx.AgentHost/Services/WorkflowDefinitionExtensions.cs new file mode 100644 index 0000000..bbe8090 --- /dev/null +++ b/sidecar/src/Aryx.AgentHost/Services/WorkflowDefinitionExtensions.cs @@ -0,0 +1,54 @@ +using Aryx.AgentHost.Contracts; + +namespace Aryx.AgentHost.Services; + +internal static class WorkflowDefinitionExtensions +{ + public static IReadOnlyList GetAgentNodes(this WorkflowDefinitionDto workflow) + { + ArgumentNullException.ThrowIfNull(workflow); + + return workflow.Graph.Nodes + .Where(IsAgentNode) + .ToList(); + } + + public static bool IsAgentNode(this WorkflowNodeDto node) + { + ArgumentNullException.ThrowIfNull(node); + return string.Equals(node.Kind, "agent", StringComparison.OrdinalIgnoreCase); + } + + public static string GetAgentId(this WorkflowNodeDto node) + { + ArgumentNullException.ThrowIfNull(node); + return !string.IsNullOrWhiteSpace(node.Config.Id) ? node.Config.Id : node.Id; + } + + public static string GetAgentName(this WorkflowNodeDto node) + { + ArgumentNullException.ThrowIfNull(node); + return FirstNonBlank(node.Config.Name, node.Label, node.Id) ?? "agent"; + } + + public static bool IsOrchestrationMode(this WorkflowDefinitionDto workflow, string mode) + { + ArgumentNullException.ThrowIfNull(workflow); + ArgumentException.ThrowIfNullOrWhiteSpace(mode); + + return string.Equals(workflow.Settings.OrchestrationMode, mode, StringComparison.OrdinalIgnoreCase); + } + + private static string? FirstNonBlank(params string?[] values) + { + foreach (string? value in values) + { + if (!string.IsNullOrWhiteSpace(value)) + { + return value.Trim(); + } + } + + return null; + } +} diff --git a/sidecar/src/Aryx.AgentHost/Services/WorkflowRequestInfoInterpreter.cs b/sidecar/src/Aryx.AgentHost/Services/WorkflowRequestInfoInterpreter.cs index dc79710..f6bb163 100644 --- a/sidecar/src/Aryx.AgentHost/Services/WorkflowRequestInfoInterpreter.cs +++ b/sidecar/src/Aryx.AgentHost/Services/WorkflowRequestInfoInterpreter.cs @@ -20,7 +20,7 @@ internal static class WorkflowRequestInfoInterpreter AgentIdentity? activeAgent, ConcurrentDictionary toolNamesByCallId) { - RequestInterpretation interpretation = InterpretRequest(command.Pattern, requestInfo); + RequestInterpretation interpretation = InterpretRequest(command.Workflow, requestInfo); return interpretation switch { HandoffRequestInterpretation handoff => @@ -35,8 +35,8 @@ internal static class WorkflowRequestInfoInterpreter RunTurnCommandDto command, RequestInfoEvent requestInfo) { - return string.Equals(command.Pattern.Mode, "handoff", StringComparison.OrdinalIgnoreCase) - && InterpretRequest(command.Pattern, requestInfo) is UnknownRequestInterpretation; + return command.Workflow.IsOrchestrationMode("handoff") + && InterpretRequest(command.Workflow, requestInfo) is UnknownRequestInterpretation; } private static AgentActivityEventDto CreateHandoffActivity( @@ -95,10 +95,10 @@ internal static class WorkflowRequestInfoInterpreter } private static RequestInterpretation InterpretRequest( - PatternDefinitionDto pattern, + WorkflowDefinitionDto workflow, RequestInfoEvent requestInfo) { - if (TryGetHandoffTarget(pattern, requestInfo, out AgentIdentity handoffAgent)) + if (TryGetHandoffTarget(workflow, requestInfo, out AgentIdentity handoffAgent)) { return new HandoffRequestInterpretation(handoffAgent); } @@ -109,7 +109,7 @@ internal static class WorkflowRequestInfoInterpreter } private static bool TryGetHandoffTarget( - PatternDefinitionDto pattern, + WorkflowDefinitionDto workflow, RequestInfoEvent requestInfo, out AgentIdentity agent) { @@ -128,7 +128,7 @@ internal static class WorkflowRequestInfoInterpreter } agent = AgentIdentityResolver.ResolveAgentIdentity( - pattern, + workflow, target.Id, target.Name); return !string.IsNullOrWhiteSpace(agent.AgentName); diff --git a/sidecar/src/Aryx.AgentHost/Services/WorkflowRunner.cs b/sidecar/src/Aryx.AgentHost/Services/WorkflowRunner.cs index 8f98c76..515db38 100644 --- a/sidecar/src/Aryx.AgentHost/Services/WorkflowRunner.cs +++ b/sidecar/src/Aryx.AgentHost/Services/WorkflowRunner.cs @@ -8,12 +8,10 @@ internal sealed class WorkflowRunner { public Workflow BuildWorkflow( WorkflowDefinitionDto workflowDefinition, - PatternDefinitionDto patternDefinition, IReadOnlyList agents, IReadOnlyList? workflowLibrary = null) { ArgumentNullException.ThrowIfNull(workflowDefinition); - ArgumentNullException.ThrowIfNull(patternDefinition); ArgumentNullException.ThrowIfNull(agents); Dictionary workflowLibraryMap = workflowLibrary? @@ -22,9 +20,10 @@ internal sealed class WorkflowRunner .ToDictionary(group => group.Key, group => group.Last(), StringComparer.Ordinal) ?? new Dictionary(StringComparer.Ordinal); - Dictionary agentMap = patternDefinition.Agents - .Zip(agents, (definition, agent) => (definition.Id, agent)) - .ToDictionary(pair => pair.Id, pair => pair.agent, StringComparer.Ordinal); + List agentIds = ResolveAgentIds(workflowDefinition, workflowLibraryMap); + Dictionary agentMap = agentIds + .Zip(agents, (agentId, agent) => (agentId, agent)) + .ToDictionary(pair => pair.agentId, pair => pair.agent, StringComparer.Ordinal); return BuildWorkflow(workflowDefinition, agentMap, workflowLibraryMap); } @@ -222,6 +221,47 @@ internal sealed class WorkflowRunner private static string? NormalizeOptionalString(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + private static List ResolveAgentIds( + WorkflowDefinitionDto workflowDefinition, + IReadOnlyDictionary workflowLibrary) + { + List agentIds = []; + CollectAgentIds(workflowDefinition, workflowLibrary, agentIds, new HashSet(StringComparer.Ordinal)); + return agentIds; + } + + private static void CollectAgentIds( + WorkflowDefinitionDto workflowDefinition, + IReadOnlyDictionary workflowLibrary, + List agentIds, + ISet visitedWorkflowIds) + { + string workflowKey = string.IsNullOrWhiteSpace(workflowDefinition.Id) + ? Guid.NewGuid().ToString("N") + : workflowDefinition.Id; + if (!visitedWorkflowIds.Add(workflowKey)) + { + return; + } + + foreach (WorkflowNodeDto node in workflowDefinition.Graph.Nodes) + { + if (string.Equals(node.Kind, "agent", StringComparison.OrdinalIgnoreCase)) + { + agentIds.Add(!string.IsNullOrWhiteSpace(node.Config.Id) ? node.Config.Id : node.Id); + continue; + } + + if (!string.Equals(node.Kind, "sub-workflow", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + WorkflowDefinitionDto subWorkflow = ResolveSubWorkflowDefinition(node, workflowLibrary); + CollectAgentIds(subWorkflow, workflowLibrary, agentIds, visitedWorkflowIds); + } + } + private sealed record WorkflowNodeRoute( ExecutorBinding Entry, ExecutorBinding Exit, diff --git a/sidecar/src/Aryx.AgentHost/Services/WorkflowTranscriptProjector.cs b/sidecar/src/Aryx.AgentHost/Services/WorkflowTranscriptProjector.cs index 11cf656..5a9ac1f 100644 --- a/sidecar/src/Aryx.AgentHost/Services/WorkflowTranscriptProjector.cs +++ b/sidecar/src/Aryx.AgentHost/Services/WorkflowTranscriptProjector.cs @@ -73,7 +73,7 @@ internal static class WorkflowTranscriptProjector List projectedMessages = []; int fallbackOutputIndex = 0; string createdAt = DateTimeOffset.UtcNow.ToString("O"); - List preparedSegments = PrepareSegmentsForProjection(command.Pattern, segments); + List preparedSegments = PrepareSegmentsForProjection(command.Workflow, segments); List remainingSegments = preparedSegments.ToList(); List assistantMessages = newMessages.Where(message => message.Role != ChatRole.User).ToList(); @@ -84,7 +84,7 @@ internal static class WorkflowTranscriptProjector message, remainingSegments, assistantMessages.Count - messageIndex, - command.Pattern, + command.Workflow, fallbackAgent); string content = ResolveProjectedContent(message, matchedSegment); if (string.IsNullOrWhiteSpace(content)) @@ -133,7 +133,7 @@ internal static class WorkflowTranscriptProjector ?? $"{command.RequestId}-final-{fallbackOutputIndex}", Role = message.Role == ChatRole.System ? "system" : "assistant", AuthorName = ResolveProjectedAuthorName( - command.Pattern, + command.Workflow, message.AuthorName, matchedSegment?.AuthorName, fallbackAgent), @@ -180,17 +180,17 @@ internal static class WorkflowTranscriptProjector { Id = segment.MessageId, Role = "assistant", - AuthorName = AgentIdentityResolver.ResolveDisplayAuthorName(command.Pattern, segment.AuthorName), + AuthorName = AgentIdentityResolver.ResolveDisplayAuthorName(command.Workflow, segment.AuthorName), Content = segment.Content, CreatedAt = createdAt, }; } private static List PrepareSegmentsForProjection( - PatternDefinitionDto pattern, + WorkflowDefinitionDto workflow, IReadOnlyList segments) { - if (!string.Equals(pattern.Mode, "concurrent", StringComparison.Ordinal) + if (!workflow.IsOrchestrationMode("concurrent") || segments.Count <= 1) { return segments.ToList(); @@ -205,7 +205,7 @@ internal static class WorkflowTranscriptProjector for (int index = 0; index < segments.Count; index++) { TranscriptSegment segment = segments[index]; - string authorKey = AgentIdentityResolver.ResolveDisplayAuthorName(pattern, segment.AuthorName); + string authorKey = AgentIdentityResolver.ResolveDisplayAuthorName(workflow, segment.AuthorName); latestSegmentByAuthor[authorKey] = (segment, index); } @@ -219,7 +219,7 @@ internal static class WorkflowTranscriptProjector ChatMessage message, IReadOnlyList remainingSegments, int remainingMessageCount, - PatternDefinitionDto pattern, + WorkflowDefinitionDto workflow, AgentIdentity? fallbackAgent) { if (remainingSegments.Count == 0) @@ -231,7 +231,7 @@ internal static class WorkflowTranscriptProjector if (messageText is not null) { string resolvedAuthorName = ResolveProjectedAuthorName( - pattern, + workflow, message.AuthorName, fallbackIdentifier: null, fallbackAgent); @@ -240,7 +240,7 @@ internal static class WorkflowTranscriptProjector remainingSegments, segment => string.Equals(segment.Content, messageText, StringComparison.Ordinal) && string.Equals( - AgentIdentityResolver.ResolveDisplayAuthorName(pattern, segment.AuthorName), + AgentIdentityResolver.ResolveDisplayAuthorName(workflow, segment.AuthorName), resolvedAuthorName, StringComparison.Ordinal), out TranscriptSegment authorMatchedSegment)) @@ -264,7 +264,7 @@ internal static class WorkflowTranscriptProjector && TryFindLastSegment( remainingSegments, segment => string.Equals( - AgentIdentityResolver.ResolveDisplayAuthorName(pattern, segment.AuthorName), + AgentIdentityResolver.ResolveDisplayAuthorName(workflow, segment.AuthorName), fallbackAgent.Value.AgentName, StringComparison.Ordinal), out TranscriptSegment fallbackMatchedSegment)) @@ -382,7 +382,7 @@ internal static class WorkflowTranscriptProjector } private static string ResolveProjectedAuthorName( - PatternDefinitionDto pattern, + WorkflowDefinitionDto workflow, string? primaryIdentifier, string? fallbackIdentifier, AgentIdentity? fallbackAgent) @@ -399,16 +399,17 @@ internal static class WorkflowTranscriptProjector return fallbackAgent.Value.AgentName; } - if (pattern.Agents.Count == 1 + IReadOnlyList agentNodes = workflow.GetAgentNodes(); + if (agentNodes.Count == 1 && string.IsNullOrWhiteSpace(primaryIdentifier) && string.IsNullOrWhiteSpace(fallbackIdentifier)) { - PatternAgentDefinitionDto singleAgent = pattern.Agents[0]; - return AgentIdentityResolver.ResolveDisplayAuthorName(pattern, singleAgent.Id, singleAgent.Name); + WorkflowNodeDto singleAgent = agentNodes[0]; + return AgentIdentityResolver.ResolveDisplayAuthorName(workflow, singleAgent.GetAgentId(), singleAgent.GetAgentName()); } return AgentIdentityResolver.ResolveDisplayAuthorName( - pattern, + workflow, primaryIdentifier, fallbackIdentifier); } diff --git a/sidecar/tests/Aryx.AgentHost.Tests/AgentIdentityResolverTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/AgentIdentityResolverTests.cs index 643f06a..77c2df8 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/AgentIdentityResolverTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/AgentIdentityResolverTests.cs @@ -8,14 +8,14 @@ public sealed class AgentIdentityResolverTests [Fact] public void TryResolveKnownAgentIdentity_MatchesRuntimeExecutorIdentifier() { - PatternDefinitionDto pattern = CreatePattern( + WorkflowDefinitionDto workflow = CreateWorkflow( [ - CreateAgent(id: "agent-concurrent-architect", name: "Architect"), - CreateAgent(id: "agent-concurrent-product", name: "Product"), + CreateAgent("agent-concurrent-architect", "Architect"), + CreateAgent("agent-concurrent-product", "Product"), ]); bool resolved = AgentIdentityResolver.TryResolveKnownAgentIdentity( - pattern, + workflow, "Architect_agent_concurrent_architect", out AgentIdentity agent); @@ -27,14 +27,14 @@ public sealed class AgentIdentityResolverTests [Fact] public void TryResolveKnownAgentIdentity_MatchesSanitizedNameAndId() { - PatternDefinitionDto pattern = CreatePattern( + WorkflowDefinitionDto workflow = CreateWorkflow( [ - CreateAgent(id: "agent-single-primary", name: "Primary Agent"), + CreateAgent("agent-single-primary", "Primary Agent"), ], - mode: "single"); + orchestrationMode: "single"); bool resolved = AgentIdentityResolver.TryResolveKnownAgentIdentity( - pattern, + workflow, "Primary_Agent_agent_single_primary", out AgentIdentity agent); @@ -46,14 +46,14 @@ public sealed class AgentIdentityResolverTests [Fact] public void TryResolveKnownAgentIdentity_MapsAssistantToSingleAgent() { - PatternDefinitionDto pattern = CreatePattern( + WorkflowDefinitionDto workflow = CreateWorkflow( [ - CreateAgent(id: "agent-single-primary", name: "Primary Agent"), + CreateAgent("agent-single-primary", "Primary Agent"), ], - mode: "single"); + orchestrationMode: "single"); bool resolved = AgentIdentityResolver.TryResolveKnownAgentIdentity( - pattern, + workflow, "assistant", out AgentIdentity agent); @@ -63,16 +63,16 @@ public sealed class AgentIdentityResolverTests } [Fact] - public void TryResolveKnownAgentIdentity_DoesNotGuessAssistantForMultiAgentPattern() + public void TryResolveKnownAgentIdentity_DoesNotGuessAssistantForMultiAgentWorkflow() { - PatternDefinitionDto pattern = CreatePattern( + WorkflowDefinitionDto workflow = CreateWorkflow( [ - CreateAgent(id: "agent-concurrent-architect", name: "Architect"), - CreateAgent(id: "agent-concurrent-product", name: "Product"), + CreateAgent("agent-concurrent-architect", "Architect"), + CreateAgent("agent-concurrent-product", "Product"), ]); bool resolved = AgentIdentityResolver.TryResolveKnownAgentIdentity( - pattern, + workflow, "assistant", out _); @@ -82,14 +82,14 @@ public sealed class AgentIdentityResolverTests [Fact] public void ResolveDisplayAuthorName_UsesCanonicalAgentName() { - PatternDefinitionDto pattern = CreatePattern( + WorkflowDefinitionDto workflow = CreateWorkflow( [ - CreateAgent(id: "agent-concurrent-implementer", name: "Implementer"), + CreateAgent("agent-concurrent-implementer", "Implementer"), ], - mode: "single"); + orchestrationMode: "single"); string authorName = AgentIdentityResolver.ResolveDisplayAuthorName( - pattern, + workflow, "Implementer_agent_concurrent_implementer"); Assert.Equal("Implementer", authorName); @@ -98,14 +98,14 @@ public sealed class AgentIdentityResolverTests [Fact] public void TryResolveObservedAgentIdentity_UsesFallbackAgentForGenericAssistant() { - PatternDefinitionDto pattern = CreatePattern( + WorkflowDefinitionDto workflow = CreateWorkflow( [ - CreateAgent(id: "agent-handoff-ux", name: "UX Specialist"), - CreateAgent(id: "agent-handoff-runtime", name: "Runtime Specialist"), + CreateAgent("agent-handoff-ux", "UX Specialist"), + CreateAgent("agent-handoff-runtime", "Runtime Specialist"), ]); bool resolved = AgentIdentityResolver.TryResolveObservedAgentIdentity( - pattern, + workflow, "assistant", new AgentIdentity("agent-handoff-ux", "UX Specialist"), out AgentIdentity agent); @@ -115,28 +115,43 @@ public sealed class AgentIdentityResolverTests Assert.Equal("UX Specialist", agent.AgentName); } - private static PatternDefinitionDto CreatePattern( - IReadOnlyList agents, - string mode = "concurrent") + private static WorkflowDefinitionDto CreateWorkflow( + IReadOnlyList agents, + string orchestrationMode = "concurrent") { - return new PatternDefinitionDto + return new WorkflowDefinitionDto { - Id = $"{mode}-pattern", - Name = "Pattern", - Mode = mode, - Availability = "available", - Agents = agents, + Id = $"{orchestrationMode}-workflow", + Name = "Workflow", + Graph = new WorkflowGraphDto + { + Nodes = + [ + .. agents, + ], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = orchestrationMode, + }, }; } - private static PatternAgentDefinitionDto CreateAgent(string id, string name) + private static WorkflowNodeDto CreateAgent(string id, string name) { - return new PatternAgentDefinitionDto + return new WorkflowNodeDto { Id = id, - Name = name, - Model = "gpt-5.4", - Instructions = "Help with the request.", + Kind = "agent", + Label = name, + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = id, + Name = name, + Model = "gpt-5.4", + Instructions = "Help with the request.", + }, }; } } diff --git a/sidecar/tests/Aryx.AgentHost.Tests/AgentInstructionComposerTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/AgentInstructionComposerTests.cs index 53fd0b9..2a1cf81 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/AgentInstructionComposerTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/AgentInstructionComposerTests.cs @@ -8,19 +8,10 @@ public sealed class AgentInstructionComposerTests [Fact] public void Compose_LeavesNonHandoffInstructionsUnchanged() { - PatternDefinitionDto pattern = new() - { - Id = "pattern-sequential", - Name = "Sequential", - Mode = "sequential", - Availability = "available", - }; - PatternAgentDefinitionDto agent = CreateAgent( - id: "agent-reviewer", - name: "Reviewer", - instructions: "Review the proposal."); + WorkflowDefinitionDto workflow = CreateWorkflow("sequential"); + WorkflowNodeDto agent = CreateAgent("agent-reviewer", "Reviewer", "Review the proposal."); - string instructions = AgentInstructionComposer.Compose(pattern, agent, agentIndex: 0); + string instructions = AgentInstructionComposer.Compose(workflow, agent, agentIndex: 0); Assert.Equal("Review the proposal.", instructions); } @@ -28,24 +19,12 @@ public sealed class AgentInstructionComposerTests [Fact] public void Compose_StrengthensGroupChatCollaborationRoles() { - PatternDefinitionDto pattern = new() - { - Id = "pattern-group-chat", - Name = "Group Chat", - Mode = "group-chat", - Availability = "available", - }; - PatternAgentDefinitionDto writer = CreateAgent( - id: "agent-group-writer", - name: "Writer", - instructions: "Draft an answer."); - PatternAgentDefinitionDto reviewer = CreateAgent( - id: "agent-group-reviewer", - name: "Reviewer", - instructions: "Review the draft."); + WorkflowDefinitionDto workflow = CreateWorkflow("group-chat"); + WorkflowNodeDto writer = CreateAgent("agent-group-writer", "Writer", "Draft an answer."); + WorkflowNodeDto reviewer = CreateAgent("agent-group-reviewer", "Reviewer", "Review the draft."); - string writerInstructions = AgentInstructionComposer.Compose(pattern, writer, agentIndex: 0); - string reviewerInstructions = AgentInstructionComposer.Compose(pattern, reviewer, agentIndex: 1); + string writerInstructions = AgentInstructionComposer.Compose(workflow, writer, agentIndex: 0); + string reviewerInstructions = AgentInstructionComposer.Compose(workflow, reviewer, agentIndex: 1); Assert.Contains("collaborative multi-turn group chat", writerInstructions, StringComparison.OrdinalIgnoreCase); Assert.Contains("refine your earlier draft", writerInstructions, StringComparison.OrdinalIgnoreCase); @@ -56,19 +35,13 @@ public sealed class AgentInstructionComposerTests [Fact] public void Compose_LeavesHandoffTriagePromptFocusedOnAgentInstructions() { - PatternDefinitionDto pattern = new() - { - Id = "pattern-handoff", - Name = "Handoff", - Mode = "handoff", - Availability = "available", - }; - PatternAgentDefinitionDto triage = CreateAgent( - id: "agent-handoff-triage", - name: "Triage", - instructions: "You triage requests and must hand them off to the most appropriate specialist."); + WorkflowDefinitionDto workflow = CreateWorkflow("handoff"); + WorkflowNodeDto triage = CreateAgent( + "agent-handoff-triage", + "Triage", + "You triage requests and must hand them off to the most appropriate specialist."); - string instructions = AgentInstructionComposer.Compose(pattern, triage, agentIndex: 0); + string instructions = AgentInstructionComposer.Compose(workflow, triage, agentIndex: 0); Assert.Equal("You triage requests and must hand them off to the most appropriate specialist.", instructions); Assert.DoesNotContain("routing", instructions, StringComparison.OrdinalIgnoreCase); @@ -78,19 +51,13 @@ public sealed class AgentInstructionComposerTests [Fact] public void Compose_LeavesHandoffSpecialistPromptFocusedOnAgentInstructions() { - PatternDefinitionDto pattern = new() - { - Id = "pattern-handoff", - Name = "Handoff", - Mode = "handoff", - Availability = "available", - }; - PatternAgentDefinitionDto specialist = CreateAgent( - id: "agent-handoff-ux", - name: "UX Specialist", - instructions: "You focus on navigation, UX, and interaction details."); + WorkflowDefinitionDto workflow = CreateWorkflow("handoff"); + WorkflowNodeDto specialist = CreateAgent( + "agent-handoff-ux", + "UX Specialist", + "You focus on navigation, UX, and interaction details."); - string instructions = AgentInstructionComposer.Compose(pattern, specialist, agentIndex: 1); + string instructions = AgentInstructionComposer.Compose(workflow, specialist, agentIndex: 1); Assert.Equal("You focus on navigation, UX, and interaction details.", instructions); Assert.DoesNotContain("triage agent", instructions, StringComparison.OrdinalIgnoreCase); @@ -100,20 +67,11 @@ public sealed class AgentInstructionComposerTests [Fact] public void Compose_AddsScratchpadGuidanceForProjectlessQaSessions() { - PatternDefinitionDto pattern = new() - { - Id = "pattern-single", - Name = "Single", - Mode = "single", - Availability = "available", - }; - PatternAgentDefinitionDto agent = CreateAgent( - id: "agent-primary", - name: "Primary Agent", - instructions: "You are a helpful assistant."); + WorkflowDefinitionDto workflow = CreateWorkflow("single"); + WorkflowNodeDto agent = CreateAgent("agent-primary", "Primary Agent", "You are a helpful assistant."); string instructions = AgentInstructionComposer.Compose( - pattern, + workflow, agent, agentIndex: 0, workspaceKind: "scratchpad"); @@ -127,20 +85,11 @@ public sealed class AgentInstructionComposerTests [Fact] public void Compose_AddsPlanModeGuidanceWhenRequested() { - PatternDefinitionDto pattern = new() - { - Id = "pattern-single", - Name = "Single", - Mode = "single", - Availability = "available", - }; - PatternAgentDefinitionDto agent = CreateAgent( - id: "agent-primary", - name: "Primary Agent", - instructions: "You are a helpful assistant."); + WorkflowDefinitionDto workflow = CreateWorkflow("single"); + WorkflowNodeDto agent = CreateAgent("agent-primary", "Primary Agent", "You are a helpful assistant."); string instructions = AgentInstructionComposer.Compose( - pattern, + workflow, agent, agentIndex: 0, interactionMode: "plan"); @@ -154,20 +103,11 @@ public sealed class AgentInstructionComposerTests [Fact] public void Compose_InsertsProjectInstructionsBetweenBaseAndRuntimeGuidance() { - PatternDefinitionDto pattern = new() - { - Id = "pattern-single", - Name = "Single", - Mode = "single", - Availability = "available", - }; - PatternAgentDefinitionDto agent = CreateAgent( - id: "agent-primary", - name: "Primary Agent", - instructions: "You are a helpful assistant."); + WorkflowDefinitionDto workflow = CreateWorkflow("single"); + WorkflowNodeDto agent = CreateAgent("agent-primary", "Primary Agent", "You are a helpful assistant."); string instructions = AgentInstructionComposer.Compose( - pattern, + workflow, agent, agentIndex: 0, workspaceKind: "scratchpad", @@ -187,20 +127,11 @@ public sealed class AgentInstructionComposerTests [Fact] public void Compose_AppendsPromptInvocationAsATaskDirective() { - PatternDefinitionDto pattern = new() - { - Id = "pattern-single", - Name = "Single", - Mode = "single", - Availability = "available", - }; - PatternAgentDefinitionDto agent = CreateAgent( - id: "agent-primary", - name: "Primary Agent", - instructions: "You are a helpful assistant."); + WorkflowDefinitionDto workflow = CreateWorkflow("single"); + WorkflowNodeDto agent = CreateAgent("agent-primary", "Primary Agent", "You are a helpful assistant."); string instructions = AgentInstructionComposer.Compose( - pattern, + workflow, agent, agentIndex: 0, promptInvocation: new RunTurnPromptInvocationDto @@ -228,14 +159,34 @@ public sealed class AgentInstructionComposerTests StringComparison.Ordinal); } - private static PatternAgentDefinitionDto CreateAgent(string id, string name, string instructions) + private static WorkflowDefinitionDto CreateWorkflow(string orchestrationMode) { - return new PatternAgentDefinitionDto + return new WorkflowDefinitionDto + { + Id = $"{orchestrationMode}-workflow", + Name = "Workflow", + Settings = new WorkflowSettingsDto + { + OrchestrationMode = orchestrationMode, + }, + }; + } + + private static WorkflowNodeDto CreateAgent(string id, string name, string instructions) + { + return new WorkflowNodeDto { Id = id, - Name = name, - Instructions = instructions, - Model = "gpt-5.4", + Kind = "agent", + Label = name, + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = id, + Name = name, + Instructions = instructions, + Model = "gpt-5.4", + }, }; } } diff --git a/sidecar/tests/Aryx.AgentHost.Tests/CopilotAgentBundleTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/CopilotAgentBundleTests.cs index f9571d8..edd1c4c 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/CopilotAgentBundleTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/CopilotAgentBundleTests.cs @@ -158,34 +158,17 @@ public sealed class CopilotAgentBundleTests Assert.Equal(HandoffWorkflowGuidance.CreateWorkflowInstructions(), builder.HandoffInstructions); } - [Theory] - [InlineData("single", 1)] - [InlineData("sequential", 2)] - [InlineData("concurrent", 2)] - [InlineData("group-chat", 2)] - public void BuildWorkflow_ExplicitlyConfiguresAgentHostOptions(string mode, int agentCount) + [Fact] + public void CreateAgentHostOptions_UsesExpectedAryxDefaults() { - CopilotAgentBundle bundle = new(CreateAgents(agentCount), hasConfiguredHooks: false); - PatternDefinitionDto pattern = CreatePattern(mode, agentCount); + AIAgentHostOptions options = CopilotAgentBundle.CreateAgentHostOptions(); - Workflow workflow = bundle.BuildWorkflow(pattern); - - AIAgentBinding[] bindings = workflow.ReflectExecutors().Values - .OfType() - .ToArray(); - - Assert.Equal(agentCount, bindings.Length); - - foreach (AIAgentBinding binding in bindings) - { - AIAgentHostOptions options = Assert.IsType(binding.Options); - Assert.Null(options.EmitAgentUpdateEvents); - Assert.False(options.EmitAgentResponseEvents); - Assert.False(options.InterceptUserInputRequests); - Assert.False(options.InterceptUnterminatedFunctionCalls); - Assert.True(options.ReassignOtherAgentsAsUsers); - Assert.True(options.ForwardIncomingMessages); - } + Assert.Null(options.EmitAgentUpdateEvents); + Assert.False(options.EmitAgentResponseEvents); + Assert.False(options.InterceptUserInputRequests); + Assert.False(options.InterceptUnterminatedFunctionCalls); + Assert.True(options.ReassignOtherAgentsAsUsers); + Assert.True(options.ForwardIncomingMessages); } [Fact] @@ -387,28 +370,12 @@ public sealed class CopilotAgentBundleTests ProjectPath = @"C:\workspace\project", WorkspaceKind = "project", Mode = "interactive", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Pattern", - Mode = "single", - Availability = "available", - Agents = - [ - new PatternAgentDefinitionDto - { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help.", - }, - ], - }, + Workflow = CreateWorkflow("single", 1), }; SessionConfig sessionConfig = CopilotAgentBundle.CreateSessionConfig( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], agentIndex: 0); Assert.Null(sessionConfig.SessionId); @@ -427,28 +394,12 @@ public sealed class CopilotAgentBundleTests WorkspaceKind = "project", Mode = "interactive", ProjectInstructions = "Follow repository guidance.", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Pattern", - Mode = "single", - Availability = "available", - Agents = - [ - new PatternAgentDefinitionDto - { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help.", - }, - ], - }, + Workflow = CreateWorkflow("single", 1), }; SessionConfig sessionConfig = CopilotAgentBundle.CreateSessionConfig( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], agentIndex: 0); Assert.Equal("Help.\n\nFollow repository guidance.", sessionConfig.SystemMessage?.Content); @@ -471,28 +422,12 @@ public sealed class CopilotAgentBundleTests Agent = "designer", ResolvedPrompt = "Review the docs for missing steps.", }, - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Pattern", - Mode = "single", - Availability = "available", - Agents = - [ - new PatternAgentDefinitionDto - { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help.", - }, - ], - }, + Workflow = CreateWorkflow("single", 1), }; SessionConfig sessionConfig = CopilotAgentBundle.CreateSessionConfig( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], agentIndex: 0); Assert.Equal("designer", sessionConfig.Agent); @@ -516,28 +451,12 @@ public sealed class CopilotAgentBundleTests ResolvedPrompt = "Review the docs for missing steps.", Tools = ["view"], }, - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Pattern", - Mode = "single", - Availability = "available", - Agents = - [ - new PatternAgentDefinitionDto - { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help.", - }, - ], - }, + Workflow = CreateWorkflow("single", 1), }; SessionConfig sessionConfig = CopilotAgentBundle.CreateSessionConfig( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], agentIndex: 0); Assert.Equal("agent", sessionConfig.Agent); @@ -550,13 +469,10 @@ public sealed class CopilotAgentBundleTests { RequestId = "turn-1", SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Pattern", - Mode = "single", - Availability = "available", - ApprovalPolicy = new ApprovalPolicyDto + Workflow = CreateWorkflow( + "single", + 1, + new ApprovalPolicyDto { Rules = [ @@ -566,21 +482,10 @@ public sealed class CopilotAgentBundleTests AgentIds = ["agent-1"], }, ], - }, - Agents = - [ - new PatternAgentDefinitionDto - { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help.", - }, - ], - }, + }), }; - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0]); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0]); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput { @@ -630,25 +535,41 @@ public sealed class CopilotAgentBundleTests .Select(index => (AIAgent)CreateChatClientAgent($"agent-{index}", $"Agent {index}")) .ToArray(); - private static PatternDefinitionDto CreatePattern(string mode, int agentCount) + private static WorkflowDefinitionDto CreateWorkflow( + string mode, + int agentCount, + ApprovalPolicyDto? approvalPolicy = null) { - return new PatternDefinitionDto + return new WorkflowDefinitionDto { - Id = $"pattern-{mode}", - Name = $"Pattern {mode}", - Mode = mode, - Availability = "available", - Agents = - [ - .. Enumerable.Range(1, agentCount).Select(index => new PatternAgentDefinitionDto - { - Id = $"agent-{index}", - Name = $"Agent {index}", - Description = $"Agent {index} description.", - Instructions = $"Agent {index} instructions.", - Model = "gpt-5.4", - }), - ], + Id = $"workflow-{mode}", + Name = $"Workflow {mode}", + Graph = new WorkflowGraphDto + { + Nodes = + [ + .. Enumerable.Range(1, agentCount).Select(index => new WorkflowNodeDto + { + Id = $"agent-{index}", + Kind = "agent", + Label = $"Agent {index}", + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = $"agent-{index}", + Name = $"Agent {index}", + Description = $"Agent {index} description.", + Instructions = "Help.", + Model = "gpt-5.4", + }, + }), + ], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = mode, + ApprovalPolicy = approvalPolicy, + }, }; } @@ -697,3 +618,4 @@ public sealed class CopilotAgentBundleTests } } } + diff --git a/sidecar/tests/Aryx.AgentHost.Tests/CopilotExitPlanModeCoordinatorTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/CopilotExitPlanModeCoordinatorTests.cs index cfcd964..7f326dd 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/CopilotExitPlanModeCoordinatorTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/CopilotExitPlanModeCoordinatorTests.cs @@ -14,7 +14,7 @@ public sealed class CopilotExitPlanModeCoordinatorTests ExitPlanModeRequestedEventDto exitPlanEvent = coordinator.RecordExitPlanModeRequest( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new ExitPlanModeRequestedEvent { Data = new ExitPlanModeRequestedData @@ -50,23 +50,36 @@ public sealed class CopilotExitPlanModeCoordinatorTests { RequestId = "turn-1", SessionId = "session-1", - Pattern = new PatternDefinitionDto + Workflow = new WorkflowDefinitionDto { - Id = "pattern-1", - Name = "Plan Mode Pattern", - Mode = "single", - Availability = "available", - Agents = - [ - new PatternAgentDefinitionDto - { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help with the request.", - }, - ], + Id = "workflow-1", + Name = "Plan Mode Workflow", + Graph = new WorkflowGraphDto + { + Nodes = + [ + new WorkflowNodeDto + { + Id = "agent-1", + Kind = "agent", + Label = "Primary", + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = "agent-1", + Name = "Primary", + Model = "gpt-5.4", + Instructions = "Help with the request.", + }, + }, + ], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = "single", + }, }, }; } } + diff --git a/sidecar/tests/Aryx.AgentHost.Tests/CopilotMcpOAuthCoordinatorTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/CopilotMcpOAuthCoordinatorTests.cs index adbbff6..a651e0e 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/CopilotMcpOAuthCoordinatorTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/CopilotMcpOAuthCoordinatorTests.cs @@ -14,7 +14,7 @@ public sealed class CopilotMcpOAuthCoordinatorTests McpOauthRequiredEventDto oauthEvent = coordinator.BuildMcpOauthRequiredEvent( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new McpOauthRequiredEvent { Data = new McpOauthRequiredData @@ -49,23 +49,36 @@ public sealed class CopilotMcpOAuthCoordinatorTests { RequestId = "turn-1", SessionId = "session-1", - Pattern = new PatternDefinitionDto + Workflow = new WorkflowDefinitionDto { - Id = "pattern-1", - Name = "MCP OAuth Pattern", - Mode = "single", - Availability = "available", - Agents = - [ - new PatternAgentDefinitionDto - { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help with the request.", - }, - ], + Id = "workflow-1", + Name = "MCP OAuth Workflow", + Graph = new WorkflowGraphDto + { + Nodes = + [ + new WorkflowNodeDto + { + Id = "agent-1", + Kind = "agent", + Label = "Primary", + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = "agent-1", + Name = "Primary", + Model = "gpt-5.4", + Instructions = "Help with the request.", + }, + }, + ], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = "single", + }, }, }; } } + diff --git a/sidecar/tests/Aryx.AgentHost.Tests/CopilotSessionHooksTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/CopilotSessionHooksTests.cs index d91727a..161e27a 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/CopilotSessionHooksTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/CopilotSessionHooksTests.cs @@ -23,7 +23,7 @@ public sealed class CopilotSessionHooksTests ], }; - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], configuredHooks, runner); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput @@ -64,7 +64,7 @@ public sealed class CopilotSessionHooksTests ], }; - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], configuredHooks, runner); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput @@ -93,7 +93,7 @@ public sealed class CopilotSessionHooksTests ], }; - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], configuredHooks, runner); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput @@ -123,7 +123,7 @@ public sealed class CopilotSessionHooksTests public async Task Create_PreToolUseAutoAllowsInternalOrchestrationTools(string toolName) { RunTurnCommandDto command = CreateCommandWithToolApproval(); - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput @@ -139,7 +139,7 @@ public sealed class CopilotSessionHooksTests public async Task Create_PreToolUseKeepsStoreMemoryUnderApprovalPolicy() { RunTurnCommandDto command = CreateCommandWithToolApproval(); - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput @@ -159,7 +159,7 @@ public sealed class CopilotSessionHooksTests public async Task Create_PreToolUseAutoAllowsWhenCategoryIsApproved(string toolName, string category) { RunTurnCommandDto command = CreateCommandWithAutoApprovedCategory(category); - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput @@ -177,7 +177,7 @@ public sealed class CopilotSessionHooksTests RunTurnCommandDto command = CreateCommandWithConfiguredMcpServers( ["icm-mcp"], ["mcp_server:icm-mcp"]); - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput @@ -193,7 +193,7 @@ public sealed class CopilotSessionHooksTests public async Task Create_PreToolUseRequiresApprovalWhenMcpServerIsNotApproved() { RunTurnCommandDto command = CreateCommandWithConfiguredMcpServers(["icm-mcp"]); - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput @@ -219,7 +219,7 @@ public sealed class CopilotSessionHooksTests ErrorOccurred = [CreateHookCommand("error-hook")], }; - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], configuredHooks, runner); await hooks.OnSessionStart!( new SessionStartHookInput @@ -293,7 +293,7 @@ public sealed class CopilotSessionHooksTests public async Task Create_WithoutConfiguredFileHooksPreservesExistingApprovalBehavior() { RunTurnCommandDto command = CreateCommandWithoutApprovalRules(); - SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); + SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner()); PreToolUseHookOutput? decision = await hooks.OnPreToolUse!( new PreToolUseHookInput @@ -312,34 +312,17 @@ public sealed class CopilotSessionHooksTests RequestId = "turn-1", SessionId = "session-1", ProjectPath = @"C:\workspace\project", - Pattern = new PatternDefinitionDto + Workflow = CreateWorkflow(new ApprovalPolicyDto { - Id = "pattern-1", - Name = "Pattern", - Mode = "single", - Availability = "available", - ApprovalPolicy = new ApprovalPolicyDto - { - Rules = - [ - new ApprovalCheckpointRuleDto - { - Kind = "tool-call", - AgentIds = ["agent-1"], - }, - ], - }, - Agents = + Rules = [ - new PatternAgentDefinitionDto + new ApprovalCheckpointRuleDto { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help.", + Kind = "tool-call", + AgentIds = ["agent-1"], }, ], - }, + }), }; } @@ -351,15 +334,7 @@ public sealed class CopilotSessionHooksTests RequestId = command.RequestId, SessionId = command.SessionId, ProjectPath = command.ProjectPath, - Pattern = new PatternDefinitionDto - { - Id = command.Pattern.Id, - Name = command.Pattern.Name, - Mode = command.Pattern.Mode, - Availability = command.Pattern.Availability, - ApprovalPolicy = new ApprovalPolicyDto(), - Agents = command.Pattern.Agents, - }, + Workflow = CreateWorkflow(new ApprovalPolicyDto()), }; } @@ -370,35 +345,18 @@ public sealed class CopilotSessionHooksTests RequestId = "turn-1", SessionId = "session-1", ProjectPath = @"C:\workspace\project", - Pattern = new PatternDefinitionDto + Workflow = CreateWorkflow(new ApprovalPolicyDto { - Id = "pattern-1", - Name = "Pattern", - Mode = "single", - Availability = "available", - ApprovalPolicy = new ApprovalPolicyDto - { - Rules = - [ - new ApprovalCheckpointRuleDto - { - Kind = "tool-call", - AgentIds = ["agent-1"], - }, - ], - AutoApprovedToolNames = [category], - }, - Agents = + Rules = [ - new PatternAgentDefinitionDto + new ApprovalCheckpointRuleDto { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help.", + Kind = "tool-call", + AgentIds = ["agent-1"], }, ], - }, + AutoApprovedToolNames = [category], + }), }; } @@ -416,18 +374,44 @@ public sealed class CopilotSessionHooksTests { McpServers = [.. serverNames.Select(CreateMcpServerConfig)], }, - Pattern = new PatternDefinitionDto + Workflow = CreateWorkflow(new ApprovalPolicyDto { - Id = command.Pattern.Id, - Name = command.Pattern.Name, - Mode = command.Pattern.Mode, - Availability = command.Pattern.Availability, - ApprovalPolicy = new ApprovalPolicyDto - { - Rules = command.Pattern.ApprovalPolicy?.Rules ?? [], - AutoApprovedToolNames = autoApprovedToolNames ?? [], - }, - Agents = command.Pattern.Agents, + Rules = command.Workflow.Settings.ApprovalPolicy?.Rules ?? [], + AutoApprovedToolNames = autoApprovedToolNames ?? [], + }), + }; + } + + private static WorkflowDefinitionDto CreateWorkflow(ApprovalPolicyDto approvalPolicy) + { + return new WorkflowDefinitionDto + { + Id = "workflow-1", + Name = "Workflow", + Graph = new WorkflowGraphDto + { + Nodes = + [ + new WorkflowNodeDto + { + Id = "agent-1", + Kind = "agent", + Label = "Primary", + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = "agent-1", + Name = "Primary", + Model = "gpt-5.4", + Instructions = "Help.", + }, + }, + ], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = "single", + ApprovalPolicy = approvalPolicy, }, }; } @@ -477,3 +461,4 @@ public sealed class CopilotSessionHooksTests string InputJson, string ProjectPath); } + diff --git a/sidecar/tests/Aryx.AgentHost.Tests/CopilotTurnExecutionStateTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/CopilotTurnExecutionStateTests.cs index 9f4b51f..df0667b 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/CopilotTurnExecutionStateTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/CopilotTurnExecutionStateTests.cs @@ -14,7 +14,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new McpOauthRequiredEvent { Data = new McpOauthRequiredData @@ -37,7 +37,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -66,7 +66,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """{"type":"tool.execution_start","data":{"toolCallId":"tool-call-1","toolName":"view"},"id":"33333333-3333-3333-3333-333333333333","timestamp":"2026-03-27T00:00:00Z"}""")); @@ -85,7 +85,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """{"type":"tool.execution_start","data":{"toolCallId":"tool-call-1","toolName":"handoff_to_specialist"},"id":"1ce9d1dc-68f1-4df5-9728-f97017233279","timestamp":"2026-03-27T00:00:00Z"}""")); @@ -101,7 +101,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -142,7 +142,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -158,7 +158,7 @@ public sealed class CopilotTurnExecutionStateTests _ = state.DrainPendingEvents(); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -172,7 +172,7 @@ public sealed class CopilotTurnExecutionStateTests } """)); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -207,7 +207,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -231,7 +231,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -267,7 +267,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -298,7 +298,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -356,7 +356,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -386,7 +386,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -417,7 +417,7 @@ public sealed class CopilotTurnExecutionStateTests RunTurnCommandDto command = CreateCommand(); CopilotTurnExecutionState state = new(command); - state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookStartEvent()); + state.ObserveSessionEvent(command.Workflow.GetAgentNodes()[0], CreateHookStartEvent()); HookLifecycleEventDto evt = Assert.Single(state.DrainPendingEvents().OfType()); Assert.Equal("start", evt.Phase); @@ -432,7 +432,7 @@ public sealed class CopilotTurnExecutionStateTests RunTurnCommandDto command = CreateCommand(); CopilotTurnExecutionState state = new(command); - state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookEndEvent()); + state.ObserveSessionEvent(command.Workflow.GetAgentNodes()[0], CreateHookEndEvent()); HookLifecycleEventDto evt = Assert.Single(state.DrainPendingEvents().OfType()); Assert.Equal("end", evt.Phase); @@ -450,8 +450,8 @@ public sealed class CopilotTurnExecutionStateTests SuppressHookLifecycleEvents = true, }; - state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookStartEvent()); - state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookEndEvent()); + state.ObserveSessionEvent(command.Workflow.GetAgentNodes()[0], CreateHookStartEvent()); + state.ObserveSessionEvent(command.Workflow.GetAgentNodes()[0], CreateHookEndEvent()); Assert.Empty(state.DrainPendingEvents()); } @@ -463,7 +463,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -526,7 +526,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -561,7 +561,7 @@ public sealed class CopilotTurnExecutionStateTests CopilotTurnExecutionState state = new(command); state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -624,7 +624,7 @@ public sealed class CopilotTurnExecutionStateTests // Simulate assistant message with tool requests → triggers reclassification state.ObserveSessionEvent( - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], SessionEvent.FromJson( """ { @@ -672,23 +672,36 @@ public sealed class CopilotTurnExecutionStateTests { RequestId = "turn-1", SessionId = "session-1", - Pattern = new PatternDefinitionDto + Workflow = new WorkflowDefinitionDto { - Id = "pattern-1", - Name = "MCP OAuth Pattern", - Mode = "single", - Availability = "available", - Agents = - [ - new PatternAgentDefinitionDto - { - Id = "agent-1", - Name = "Primary", - Model = "gpt-5.4", - Instructions = "Help with the request.", - }, - ], + Id = "workflow-1", + Name = "Execution State Workflow", + Graph = new WorkflowGraphDto + { + Nodes = + [ + new WorkflowNodeDto + { + Id = "agent-1", + Kind = "agent", + Label = "Primary", + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = "agent-1", + Name = "Primary", + Model = "gpt-5.4", + Instructions = "Help with the request.", + }, + }, + ], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = "single", + }, }, }; } } + diff --git a/sidecar/tests/Aryx.AgentHost.Tests/CopilotUserInputCoordinatorTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/CopilotUserInputCoordinatorTests.cs index c9e3292..b4fe39f 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/CopilotUserInputCoordinatorTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/CopilotUserInputCoordinatorTests.cs @@ -15,7 +15,7 @@ public sealed class CopilotUserInputCoordinatorTests Task pending = coordinator.RequestUserInputAsync( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new UserInputRequest { Question = "How should I proceed?", @@ -76,33 +76,40 @@ public sealed class CopilotUserInputCoordinatorTests Assert.Contains("is not pending", error.Message); } - private static PatternAgentDefinitionDto CreateAgent(string id, string name) - { - return new PatternAgentDefinitionDto - { - Id = id, - Name = name, - Model = "gpt-5.4", - Instructions = "Help with the request.", - }; - } - private static RunTurnCommandDto CreateUserInputCommand() { return new RunTurnCommandDto { RequestId = "turn-1", SessionId = "session-1", - Pattern = new PatternDefinitionDto + Workflow = new WorkflowDefinitionDto { - Id = "pattern-1", - Name = "User Input Pattern", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent("agent-1", "Primary"), - ], + Id = "workflow-1", + Name = "User Input Workflow", + Graph = new WorkflowGraphDto + { + Nodes = + [ + new WorkflowNodeDto + { + Id = "agent-1", + Kind = "agent", + Label = "Primary", + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = "agent-1", + Name = "Primary", + Model = "gpt-5.4", + Instructions = "Help with the request.", + }, + }, + ], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = "single", + }, }, }; } diff --git a/sidecar/tests/Aryx.AgentHost.Tests/CopilotWorkflowRunnerTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/CopilotWorkflowRunnerTests.cs index 371114e..e42e2e3 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/CopilotWorkflowRunnerTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/CopilotWorkflowRunnerTests.cs @@ -95,23 +95,10 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_FallsBackToStreamingSegmentsWhenWorkflowOutputIsMissing() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-concurrent", - Name = "Concurrent Brainstorm", - Mode = "concurrent", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-concurrent-architect", name: "Architect"), - CreateAgent(id: "agent-concurrent-implementer", name: "Implementer"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "concurrent", + CreateAgent(id: "agent-concurrent-architect", name: "Architect"), + CreateAgent(id: "agent-concurrent-implementer", name: "Implementer")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -140,22 +127,9 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_CanonicalizesWorkflowOutputAuthorNames() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-single", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-single-primary", name: "Primary Agent"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "single", + CreateAgent(id: "agent-single-primary", name: "Primary Agent")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -178,22 +152,9 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_UsesFinalAssistantPayloadWhenStreamingTextIsMissing() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-single", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-single-primary", name: "Primary Agent"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "single", + CreateAgent(id: "agent-single-primary", name: "Primary Agent")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -222,24 +183,11 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_PreservesSequentialConversationHistory() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-sequential", - Name = "Sequential Trio Review", - Mode = "sequential", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-sequential-analyst", name: "Analyst"), - CreateAgent(id: "agent-sequential-builder", name: "Builder"), - CreateAgent(id: "agent-sequential-reviewer", name: "Reviewer"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "sequential", + CreateAgent(id: "agent-sequential-analyst", name: "Analyst"), + CreateAgent(id: "agent-sequential-builder", name: "Builder"), + CreateAgent(id: "agent-sequential-reviewer", name: "Reviewer")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -272,24 +220,11 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_PreservesConcurrentAggregatedResponses() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-concurrent", - Name = "Concurrent Brainstorm", - Mode = "concurrent", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-concurrent-architect", name: "Architect"), - CreateAgent(id: "agent-concurrent-product", name: "Product"), - CreateAgent(id: "agent-concurrent-implementer", name: "Implementer"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "concurrent", + CreateAgent(id: "agent-concurrent-architect", name: "Architect"), + CreateAgent(id: "agent-concurrent-product", name: "Product"), + CreateAgent(id: "agent-concurrent-implementer", name: "Implementer")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -310,24 +245,11 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_ConcurrentUsesLastStreamedMessagePerAgentForGenericOutput() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-concurrent", - Name = "Concurrent Brainstorm", - Mode = "concurrent", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-concurrent-architect", name: "Architect"), - CreateAgent(id: "agent-concurrent-product", name: "Product"), - CreateAgent(id: "agent-concurrent-implementer", name: "Implementer"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "concurrent", + CreateAgent(id: "agent-concurrent-architect", name: "Architect"), + CreateAgent(id: "agent-concurrent-product", name: "Product"), + CreateAgent(id: "agent-concurrent-implementer", name: "Implementer")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -379,23 +301,10 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_PreservesGroupChatConversationHistory() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-group-chat", - Name = "Collaborative Group Chat", - Mode = "group-chat", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-group-writer", name: "Writer"), - CreateAgent(id: "agent-group-reviewer", name: "Reviewer"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "group-chat", + CreateAgent(id: "agent-group-writer", name: "Writer"), + CreateAgent(id: "agent-group-reviewer", name: "Reviewer")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -428,23 +337,10 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_FallsBackToPositionWhenOutputTextDiffers() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-group-chat", - Name = "Collaborative Group Chat", - Mode = "group-chat", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-group-writer", name: "Writer"), - CreateAgent(id: "agent-group-reviewer", name: "Reviewer"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "group-chat", + CreateAgent(id: "agent-group-writer", name: "Writer"), + CreateAgent(id: "agent-group-reviewer", name: "Reviewer")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -482,23 +378,10 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_UsesFallbackAgentForGenericAssistantOutput() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-handoff", - Name = "Handoff Support Flow", - Mode = "handoff", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-handoff-triage", name: "Triage"), - CreateAgent(id: "agent-handoff-ux", name: "UX Specialist"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "handoff", + CreateAgent(id: "agent-handoff-triage", name: "Triage"), + CreateAgent(id: "agent-handoff-ux", name: "UX Specialist")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -519,23 +402,10 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_PrefersContentMatchedStreamingSegmentOverPosition() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-handoff", - Name = "Handoff Support Flow", - Mode = "handoff", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-handoff-triage", name: "Triage"), - CreateAgent(id: "agent-handoff-runtime", name: "Runtime Specialist"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "handoff", + CreateAgent(id: "agent-handoff-triage", name: "Triage"), + CreateAgent(id: "agent-handoff-runtime", name: "Runtime Specialist")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -560,23 +430,10 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_UsesFallbackAgentForSingleGenericAssistantOutputWithMultipleSegments() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-handoff", - Name = "Handoff Support Flow", - Mode = "handoff", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-handoff-triage", name: "Triage"), - CreateAgent(id: "agent-handoff-runtime", name: "Runtime Specialist"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "handoff", + CreateAgent(id: "agent-handoff-triage", name: "Triage"), + CreateAgent(id: "agent-handoff-runtime", name: "Runtime Specialist")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -601,23 +458,10 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public void ProjectCompletedMessages_DropsBlankAssistantOutputMessages() { - RunTurnCommandDto command = new() - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-handoff", - Name = "Handoff Support Flow", - Mode = "handoff", - Availability = "available", - Agents = - [ - CreateAgent(id: "agent-handoff-triage", name: "Triage"), - CreateAgent(id: "agent-handoff-ux", name: "UX Specialist"), - ], - }, - }; + RunTurnCommandDto command = CreateCommand( + "handoff", + CreateAgent(id: "agent-handoff-triage", name: "Triage"), + CreateAgent(id: "agent-handoff-ux", name: "UX Specialist")); IReadOnlyList messages = WorkflowTranscriptProjector.ProjectCompletedMessages( command, @@ -835,7 +679,7 @@ public sealed class CopilotWorkflowRunnerTests [Fact] public async Task RunTurnAsync_RequestPortWorkflowUsesUserInputBridge() { - CopilotWorkflowRunner runner = new(new PatternValidator()); + CopilotWorkflowRunner runner = new(new WorkflowValidator()); List requests = []; IReadOnlyList messages = await runner.RunTurnAsync( @@ -927,6 +771,25 @@ public sealed class CopilotWorkflowRunnerTests public async Task HandleWorkflowEventAsync_EmitsWorkflowCheckpointSavedEvent() { RunTurnCommandDto command = CreateHandoffCommand(); + command = new RunTurnCommandDto + { + RequestId = command.RequestId, + SessionId = command.SessionId, + Workflow = new WorkflowDefinitionDto + { + Id = command.Workflow.Id, + Name = command.Workflow.Name, + Graph = command.Workflow.Graph, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = command.Workflow.Settings.OrchestrationMode, + Checkpointing = new WorkflowCheckpointSettingsDto + { + Enabled = true, + }, + }, + }, + }; CopilotTurnExecutionState state = new(command); List checkpoints = []; @@ -1831,7 +1694,7 @@ public sealed class CopilotWorkflowRunnerTests Task pending = coordinator.RequestApprovalAsync( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new PermissionRequestCustomTool { Kind = "custom tool", @@ -1875,7 +1738,7 @@ public sealed class CopilotWorkflowRunnerTests Task pending = coordinator.RequestApprovalAsync( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new PermissionRequestWrite { Kind = "write", @@ -1938,7 +1801,7 @@ public sealed class CopilotWorkflowRunnerTests PermissionRequestResult result = await coordinator.RequestApprovalAsync( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new PermissionRequestCustomTool { Kind = "custom tool", @@ -1972,7 +1835,7 @@ public sealed class CopilotWorkflowRunnerTests PermissionRequestResult result = await coordinator.RequestApprovalAsync( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new PermissionRequestHook { Kind = "hook", @@ -2007,7 +1870,7 @@ public sealed class CopilotWorkflowRunnerTests Task firstPending = coordinator.RequestApprovalAsync( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new PermissionRequestRead { Kind = "read", @@ -2048,7 +1911,7 @@ public sealed class CopilotWorkflowRunnerTests bool sawSecondApproval = false; PermissionRequestResult secondResult = await coordinator.RequestApprovalAsync( command, - command.Pattern.Agents[0], + command.Workflow.GetAgentNodes()[0], new PermissionRequestRead { Kind = "read", @@ -2084,7 +1947,7 @@ public sealed class CopilotWorkflowRunnerTests Task firstPending = coordinator.RequestApprovalAsync( firstCommand, - firstCommand.Pattern.Agents[0], + firstCommand.Workflow.GetAgentNodes()[0], new PermissionRequestRead { Kind = "read", @@ -2124,7 +1987,7 @@ public sealed class CopilotWorkflowRunnerTests RunTurnCommandDto secondCommand = CreateApprovalCommand(requestId: "turn-2"); Task secondPending = coordinator.RequestApprovalAsync( secondCommand, - secondCommand.Pattern.Agents[0], + secondCommand.Workflow.GetAgentNodes()[0], new PermissionRequestRead { Kind = "read", @@ -2179,38 +2042,56 @@ public sealed class CopilotWorkflowRunnerTests Assert.Contains("is not pending", error.Message); } - private static PatternAgentDefinitionDto CreateAgent(string id, string name) + private static WorkflowNodeDto CreateAgent(string id, string name) { - return new PatternAgentDefinitionDto + return new WorkflowNodeDto { Id = id, - Name = name, - Model = "gpt-5.4", - Instructions = "Help with the request.", + Kind = "agent", + Label = name, + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = id, + Name = name, + Model = "gpt-5.4", + Instructions = "Help with the request.", + }, }; } - private static RunTurnCommandDto CreateHandoffCommand() + private static RunTurnCommandDto CreateCommand( + string orchestrationMode, + params WorkflowNodeDto[] agents) { return new RunTurnCommandDto { RequestId = "turn-1", SessionId = "session-1", - Pattern = new PatternDefinitionDto + Workflow = new WorkflowDefinitionDto { - Id = "pattern-handoff", - Name = "Handoff Flow", - Mode = "handoff", - Availability = "available", - Agents = - [ - CreateAgent("agent-handoff-triage", "Triage"), - CreateAgent("agent-handoff-ux", "UX Specialist"), - ], + Id = $"workflow-{orchestrationMode}", + Name = $"Workflow {orchestrationMode}", + Graph = new WorkflowGraphDto + { + Nodes = [.. agents], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = orchestrationMode, + }, }, }; } + private static RunTurnCommandDto CreateHandoffCommand() + { + return CreateCommand( + "handoff", + CreateAgent("agent-handoff-triage", "Triage"), + CreateAgent("agent-handoff-ux", "UX Specialist")); + } + private static RequestInfoEvent CreateRequestInfoEvent(object payload) { RequestPort port = RequestPort.Create("test-port"); @@ -2253,30 +2134,35 @@ public sealed class CopilotWorkflowRunnerTests { McpServers = [.. mcpServers], }, - Pattern = new PatternDefinitionDto + Workflow = new WorkflowDefinitionDto { - Id = "pattern-1", - Name = "Approval Pattern", - Mode = "single", - Availability = "available", - ApprovalPolicy = new ApprovalPolicyDto + Id = "workflow-1", + Name = "Approval Workflow", + Graph = new WorkflowGraphDto { - Rules = + Nodes = [ - new ApprovalCheckpointRuleDto - { - Kind = "tool-call", - AgentIds = ["agent-1"], - }, + CreateAgent("agent-1", "Primary"), ], - AutoApprovedToolNames = autoApprovedToolNames is null - ? ["web_fetch"] - : [.. autoApprovedToolNames], }, - Agents = - [ - CreateAgent("agent-1", "Primary"), - ], + Settings = new WorkflowSettingsDto + { + OrchestrationMode = "single", + ApprovalPolicy = new ApprovalPolicyDto + { + Rules = + [ + new ApprovalCheckpointRuleDto + { + Kind = "tool-call", + AgentIds = ["agent-1"], + }, + ], + AutoApprovedToolNames = autoApprovedToolNames is null + ? ["web_fetch"] + : [.. autoApprovedToolNames], + }, + }, }, }; } @@ -2288,14 +2174,6 @@ public sealed class CopilotWorkflowRunnerTests RequestId = "turn-request-port", SessionId = "session-request-port", ProjectPath = "c:\\workspace\\personal\\projects\\aryx.worktrees\\copilot-powerful-vulture", - Pattern = new PatternDefinitionDto - { - Id = "pattern-request-port", - Name = "Request Port Pattern", - Mode = "single", - Availability = "available", - Agents = [], - }, Messages = [ new ChatMessageDto @@ -2407,3 +2285,4 @@ public sealed class CopilotWorkflowRunnerTests } } } + diff --git a/sidecar/tests/Aryx.AgentHost.Tests/HandoffWorkflowGuidanceTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/HandoffWorkflowGuidanceTests.cs index ca08a61..e9746b4 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/HandoffWorkflowGuidanceTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/HandoffWorkflowGuidanceTests.cs @@ -23,13 +23,20 @@ public sealed class HandoffWorkflowGuidanceTests [Fact] public void CreateForwardReason_UsesTargetSpecialtyAndOwnership() { - PatternAgentDefinitionDto specialist = new() + WorkflowNodeDto specialist = new() { Id = "agent-handoff-ux", - Name = "UX Specialist", - Description = "Handles user experience questions.", - Instructions = "Focus on UX.", - Model = "claude-opus-4.5", + Kind = "agent", + Label = "UX Specialist", + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = "agent-handoff-ux", + Name = "UX Specialist", + Description = "Handles user experience questions.", + Instructions = "Focus on UX.", + Model = "claude-opus-4.5", + }, }; string reason = HandoffWorkflowGuidance.CreateForwardReason(specialist); @@ -42,13 +49,20 @@ public sealed class HandoffWorkflowGuidanceTests [Fact] public void CreateReturnReason_RestrictsReturnToReroutingCases() { - PatternAgentDefinitionDto triage = new() + WorkflowNodeDto triage = new() { Id = "agent-handoff-triage", - Name = "Triage", - Description = "Routes the request to the right specialist.", - Instructions = "Triages requests.", - Model = "gpt-5.4", + Kind = "agent", + Label = "Triage", + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = "agent-handoff-triage", + Name = "Triage", + Description = "Routes the request to the right specialist.", + Instructions = "Triages requests.", + Model = "gpt-5.4", + }, }; string reason = HandoffWorkflowGuidance.CreateReturnReason(triage); diff --git a/sidecar/tests/Aryx.AgentHost.Tests/PatternGraphResolverTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/PatternGraphResolverTests.cs deleted file mode 100644 index 0108da9..0000000 --- a/sidecar/tests/Aryx.AgentHost.Tests/PatternGraphResolverTests.cs +++ /dev/null @@ -1,127 +0,0 @@ -using Aryx.AgentHost.Contracts; -using Aryx.AgentHost.Services; - -namespace Aryx.AgentHost.Tests; - -public sealed class PatternGraphResolverTests -{ - [Fact] - public void ResolveOrderedAgentIds_UsesSequentialGraphPath() - { - PatternDefinitionDto pattern = CreatePattern( - "sequential", - [ - CreateAgent("agent-1", "Analyst"), - CreateAgent("agent-2", "Builder"), - CreateAgent("agent-3", "Reviewer"), - ], - new PatternGraphDto - { - Nodes = - [ - CreateSystemNode("system-user-input", "user-input"), - CreateAgentNode("agent-1", 0), - CreateAgentNode("agent-2", 1), - CreateAgentNode("agent-3", 2), - CreateSystemNode("system-user-output", "user-output"), - ], - Edges = - [ - CreateEdge("system-user-input", "agent-node-agent-3"), - CreateEdge("agent-node-agent-3", "agent-node-agent-1"), - CreateEdge("agent-node-agent-1", "agent-node-agent-2"), - CreateEdge("agent-node-agent-2", "system-user-output"), - ], - }); - - IReadOnlyList orderedAgentIds = PatternGraphResolver.ResolveOrderedAgentIds(pattern); - - Assert.Equal(["agent-3", "agent-1", "agent-2"], orderedAgentIds); - } - - [Fact] - public void ResolveHandoff_UsesExplicitEntryAndRoutes() - { - PatternDefinitionDto pattern = CreatePattern( - "handoff", - [ - CreateAgent("agent-1", "Triage"), - CreateAgent("agent-2", "UX"), - CreateAgent("agent-3", "Runtime"), - ], - new PatternGraphDto - { - Nodes = - [ - CreateSystemNode("system-user-input", "user-input"), - CreateSystemNode("system-user-output", "user-output"), - CreateAgentNode("agent-1", 0), - CreateAgentNode("agent-2", 1), - CreateAgentNode("agent-3", 2), - ], - Edges = - [ - CreateEdge("system-user-input", "agent-node-agent-3"), - CreateEdge("agent-node-agent-3", "agent-node-agent-2"), - CreateEdge("agent-node-agent-2", "agent-node-agent-1"), - CreateEdge("agent-node-agent-2", "system-user-output"), - ], - }); - - PatternHandoffTopology topology = PatternGraphResolver.ResolveHandoff(pattern); - - Assert.Equal("agent-3", topology.EntryAgentId); - Assert.Contains(new PatternHandoffRoute("agent-3", "agent-2"), topology.Routes); - Assert.Contains(new PatternHandoffRoute("agent-2", "agent-1"), topology.Routes); - Assert.DoesNotContain(new PatternHandoffRoute("agent-1", "agent-2"), topology.Routes); - } - - private static PatternDefinitionDto CreatePattern( - string mode, - IReadOnlyList agents, - PatternGraphDto graph) - => new() - { - Id = $"{mode}-pattern", - Name = "Pattern", - Mode = mode, - Availability = "available", - Agents = agents, - Graph = graph, - }; - - private static PatternAgentDefinitionDto CreateAgent(string id, string name) - => new() - { - Id = id, - Name = name, - Model = "gpt-5.4", - Instructions = "Help with the user's request.", - }; - - private static PatternGraphNodeDto CreateSystemNode(string id, string kind) - => new() - { - Id = id, - Kind = kind, - Position = new PatternGraphPositionDto(), - }; - - private static PatternGraphNodeDto CreateAgentNode(string agentId, int order) - => new() - { - Id = $"agent-node-{agentId}", - Kind = "agent", - AgentId = agentId, - Order = order, - Position = new PatternGraphPositionDto(), - }; - - private static PatternGraphEdgeDto CreateEdge(string source, string target) - => new() - { - Id = $"edge-{source}-to-{target}", - Source = source, - Target = target, - }; -} diff --git a/sidecar/tests/Aryx.AgentHost.Tests/SidecarProtocolHostTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/SidecarProtocolHostTests.cs index b3a10c6..62fc2c0 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/SidecarProtocolHostTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/SidecarProtocolHostTests.cs @@ -62,52 +62,6 @@ public sealed class SidecarProtocolHostTests }); } - [Fact] - public async Task ValidatePatternCommand_ReturnsIssuesAndCompletion() - { - IReadOnlyList events = await RunHostAsync(new ValidatePatternCommandDto - { - Type = "validate-pattern", - RequestId = "validate-1", - Pattern = new PatternDefinitionDto - { - Id = "single-pattern", - Name = "", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(), - CreateAgent(id: "agent-2", name: "Reviewer", model: ""), - ], - }, - }); - - Assert.Collection( - events, - validationEvent => - { - Assert.Equal("pattern-validation", validationEvent.GetProperty("type").GetString()); - Assert.Equal("validate-1", validationEvent.GetProperty("requestId").GetString()); - - JsonElement[] issues = validationEvent.GetProperty("issues").EnumerateArray().ToArray(); - Assert.Contains(issues, issue => - issue.GetProperty("field").GetString() == "name" - && issue.GetProperty("message").GetString() == "Pattern name is required."); - Assert.Contains(issues, issue => - issue.GetProperty("field").GetString() == "agents" - && issue.GetProperty("message").GetString() == "Single-agent chat requires exactly one agent."); - Assert.Contains(issues, issue => - issue.GetProperty("field").GetString() == "agents.model" - && issue.GetProperty("message").GetString() == "Agent \"Reviewer\" requires a model identifier."); - }, - completionEvent => - { - Assert.Equal("command-complete", completionEvent.GetProperty("type").GetString()); - Assert.Equal("validate-1", completionEvent.GetProperty("requestId").GetString()); - }); - } - [Fact] public async Task ValidateWorkflowCommand_ReturnsIssuesAndCompletion() { @@ -182,7 +136,7 @@ public sealed class SidecarProtocolHostTests public async Task RunTurnCommand_ReturnsActivityEventsAndCompletion() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => { await onActivity(new AgentActivityEventDto @@ -230,37 +184,7 @@ public sealed class SidecarProtocolHostTests ]; })); - IReadOnlyList events = await RunHostAsync( - new RunTurnCommandDto - { - Type = "run-turn", - RequestId = "turn-1", - SessionId = "session-1", - ProjectPath = "C:\\workspace\\project", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(name: "Primary"), - ], - }, - Messages = - [ - new ChatMessageDto - { - Id = "user-1", - Role = "user", - AuthorName = "You", - Content = "Hello", - CreatedAt = "2026-01-01T00:00:00.0000000Z", - }, - ], - }, - host); + IReadOnlyList events = await RunHostAsync(CreateRunTurnCommand(), host); Assert.Collection( events, @@ -306,7 +230,7 @@ public sealed class SidecarProtocolHostTests public async Task RunTurnCommand_ReturnsWorkflowDiagnosticEventsAndCompletion() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => { await onActivity(new WorkflowDiagnosticEventDto @@ -327,25 +251,7 @@ public sealed class SidecarProtocolHostTests })); IReadOnlyList events = await RunHostAsync( - new RunTurnCommandDto - { - Type = "run-turn", - RequestId = "turn-diagnostic", - SessionId = "session-1", - ProjectPath = "C:\\workspace\\project", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(name: "Primary"), - ], - }, - Messages = [], - }, + CreateRunTurnCommand(requestId: "turn-diagnostic", messages: []), host); Assert.Collection( @@ -378,7 +284,7 @@ public sealed class SidecarProtocolHostTests { string? capturedMode = null; SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => { capturedMode = command.Mode; @@ -386,25 +292,7 @@ public sealed class SidecarProtocolHostTests })); await RunHostAsync( - new RunTurnCommandDto - { - Type = "run-turn", - RequestId = "turn-plan", - SessionId = "session-1", - ProjectPath = "C:\\workspace\\project", - Mode = "plan", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(name: "Primary"), - ], - }, - }, + CreateRunTurnCommand(requestId: "turn-plan", interactionMode: "plan"), host); Assert.Equal("plan", capturedMode); @@ -414,7 +302,7 @@ public sealed class SidecarProtocolHostTests public async Task RunTurnCommand_ReturnsApprovalEvents() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => { await onApproval(new ApprovalRequestedEventDto @@ -441,24 +329,7 @@ public sealed class SidecarProtocolHostTests })); IReadOnlyList events = await RunHostAsync( - new RunTurnCommandDto - { - Type = "run-turn", - RequestId = "turn-approval", - SessionId = "session-1", - ProjectPath = "C:\\workspace\\project", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(name: "Primary"), - ], - }, - }, + CreateRunTurnCommand(requestId: "turn-approval"), host); Assert.Collection( @@ -492,7 +363,7 @@ public sealed class SidecarProtocolHostTests public async Task RunTurnCommand_ReturnsUserInputEvents() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => { await onUserInput(new UserInputRequestedEventDto @@ -512,24 +383,7 @@ public sealed class SidecarProtocolHostTests })); IReadOnlyList events = await RunHostAsync( - new RunTurnCommandDto - { - Type = "run-turn", - RequestId = "turn-user-input", - SessionId = "session-1", - ProjectPath = "C:\\workspace\\project", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(name: "Primary"), - ], - }, - }, + CreateRunTurnCommand(requestId: "turn-user-input"), host); Assert.Collection( @@ -565,7 +419,7 @@ public sealed class SidecarProtocolHostTests public async Task RunTurnCommand_ReturnsMcpOauthRequiredEvents() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => { await onMcpOAuthRequired(new McpOauthRequiredEventDto @@ -623,7 +477,7 @@ public sealed class SidecarProtocolHostTests public async Task RunTurnCommand_ReturnsExitPlanModeEvents() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => { await onExitPlanMode(new ExitPlanModeRequestedEventDto @@ -644,25 +498,7 @@ public sealed class SidecarProtocolHostTests })); IReadOnlyList events = await RunHostAsync( - new RunTurnCommandDto - { - Type = "run-turn", - RequestId = "turn-plan-mode", - SessionId = "session-1", - ProjectPath = "C:\\workspace\\project", - Mode = "plan", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(name: "Primary"), - ], - }, - }, + CreateRunTurnCommand(requestId: "turn-plan-mode", interactionMode: "plan"), host); Assert.Collection( @@ -698,7 +534,7 @@ public sealed class SidecarProtocolHostTests public async Task CancelTurnCommand_CancelsInProgressTurnAndCompletesBothCommands() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => { await Task.Delay(Timeout.Infinite, cancellationToken); @@ -746,7 +582,7 @@ public sealed class SidecarProtocolHostTests public async Task CancelTurnCommand_AfterTurnCompletion_IsNoOp() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => [])); await RunHostAsync(CreateRunTurnCommand(requestId: "turn-completed"), host); @@ -768,7 +604,7 @@ public sealed class SidecarProtocolHostTests { ResolveApprovalCommandDto? captured = null; SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner( handler: async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => [], resolveApprovalHandler: (command, cancellationToken) => @@ -801,7 +637,7 @@ public sealed class SidecarProtocolHostTests { ResolveUserInputCommandDto? captured = null; SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), new FakeWorkflowRunner( handler: async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => [], resolveUserInputHandler: (command, cancellationToken) => @@ -925,7 +761,7 @@ public sealed class SidecarProtocolHostTests public async Task ListSessionsCommand_ReturnsSessionsListedEvent() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), sessionManager: new FakeSessionManager { Sessions = @@ -972,7 +808,7 @@ public sealed class SidecarProtocolHostTests ], }; SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), sessionManager: sessionManager); IReadOnlyList events = await RunHostAsync( @@ -995,7 +831,7 @@ public sealed class SidecarProtocolHostTests public async Task GetQuotaCommand_ReturnsQuotaResultEvent() { SidecarProtocolHost host = new( - new PatternValidator(), + new WorkflowValidator(), sessionManager: new FakeSessionManager { QuotaSnapshots = new Dictionary(StringComparer.Ordinal) @@ -1037,7 +873,7 @@ public sealed class SidecarProtocolHostTests await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); return []; }); - SidecarProtocolHost host = new(new PatternValidator(), runner); + SidecarProtocolHost host = new(new WorkflowValidator(), runner); IReadOnlyList events = await RunHostAsync( [ @@ -1098,7 +934,7 @@ public sealed class SidecarProtocolHostTests private static SidecarProtocolHost CreateHostForTests() { return new SidecarProtocolHost( - new PatternValidator(), + new WorkflowValidator(), capabilitiesProvider: _ => Task.FromResult(new SidecarCapabilitiesDto { Modes = new Dictionary(StringComparer.OrdinalIgnoreCase) @@ -1176,24 +1012,35 @@ public sealed class SidecarProtocolHostTests return events; } - private static PatternAgentDefinitionDto CreateAgent( + private static WorkflowNodeDto CreateAgent( string id = "agent-1", string name = "Primary", string model = "gpt-5.4", string instructions = "Help with the user's request.") { - return new PatternAgentDefinitionDto + return new WorkflowNodeDto { Id = id, - Name = name, - Model = model, - Instructions = instructions, + Kind = "agent", + Label = name, + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = id, + Name = name, + Model = model, + Instructions = instructions, + }, }; } private static RunTurnCommandDto CreateRunTurnCommand( string requestId = "turn-1", - string sessionId = "session-1") + string sessionId = "session-1", + string mode = "single", + string interactionMode = "interactive", + IReadOnlyList? agents = null, + IReadOnlyList? messages = null) { return new RunTurnCommandDto { @@ -1201,18 +1048,9 @@ public sealed class SidecarProtocolHostTests RequestId = requestId, SessionId = sessionId, ProjectPath = "C:\\workspace\\project", - Pattern = new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent(name: "Primary"), - ], - }, - Messages = + Mode = interactionMode, + Workflow = CreateWorkflow(mode, agents), + Messages = messages ?? [ new ChatMessageDto { @@ -1226,6 +1064,25 @@ public sealed class SidecarProtocolHostTests }; } + private static WorkflowDefinitionDto CreateWorkflow( + string mode = "single", + IReadOnlyList? agents = null) + { + return new WorkflowDefinitionDto + { + Id = $"workflow-{mode}", + Name = "Single Agent", + Graph = new WorkflowGraphDto + { + Nodes = [.. agents ?? [CreateAgent(name: "Primary")]], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = mode, + }, + }; + } + private sealed class FakeWorkflowRunner : ITurnWorkflowRunner { private readonly Func< @@ -1325,3 +1182,4 @@ public sealed class SidecarProtocolHostTests } } } + diff --git a/sidecar/tests/Aryx.AgentHost.Tests/UnitTest1.cs b/sidecar/tests/Aryx.AgentHost.Tests/UnitTest1.cs deleted file mode 100644 index 32299af..0000000 --- a/sidecar/tests/Aryx.AgentHost.Tests/UnitTest1.cs +++ /dev/null @@ -1,169 +0,0 @@ -using Aryx.AgentHost.Contracts; -using Aryx.AgentHost.Services; - -namespace Aryx.AgentHost.Tests; - -public sealed class PatternValidatorTests -{ - private readonly PatternValidator _validator = new(); - - [Fact] - public void SingleAgentPattern_WithExactlyOneAgent_IsValid() - { - IReadOnlyList issues = _validator.Validate( - CreatePattern( - "single", - [CreateAgent()])); - - Assert.Empty(issues); - } - - [Fact] - public void HandoffPattern_WithSingleAgent_IsReportedAsInvalid() - { - IReadOnlyList issues = _validator.Validate( - CreatePattern( - "handoff", - [CreateAgent()])); - - Assert.Contains(issues, issue => - issue.Field == "agents" - && issue.Message == "Handoff orchestration requires at least two agents."); - } - - [Fact] - public void AgentWithoutModel_IsReportedAsInvalid() - { - IReadOnlyList issues = _validator.Validate( - CreatePattern( - "sequential", - [ - CreateAgent(model: ""), - CreateAgent(id: "agent-2", name: "Reviewer"), - ])); - - Assert.Contains(issues, issue => - issue.Field == "agents.model" - && issue.Message == "Agent \"Primary\" requires a model identifier."); - } - - [Fact] - public void MagenticPattern_IsReportedAsUnavailable() - { - IReadOnlyList issues = _validator.Validate( - CreatePattern( - "magentic", - [ - CreateAgent(id: "agent-1", name: "Planner", instructions: "Plan the task."), - CreateAgent( - id: "agent-2", - name: "Specialist", - model: "claude-opus-4.5", - instructions: "Complete the task."), - ], - availability: "unavailable", - unavailabilityReason: "Unsupported in C#.", - name: "Magentic")); - - Assert.Contains(issues, issue => - issue.Field == "availability" - && issue.Message.Contains("Unsupported", StringComparison.OrdinalIgnoreCase)); - Assert.Contains(issues, issue => - issue.Field == "mode" - && issue.Message.Contains("Unsupported", StringComparison.OrdinalIgnoreCase)); - } - - [Fact] - public void SequentialPattern_WithBranchedGraph_IsReportedAsInvalid() - { - IReadOnlyList issues = _validator.Validate( - CreatePattern( - "sequential", - [ - CreateAgent(id: "agent-1", name: "Analyst"), - CreateAgent(id: "agent-2", name: "Builder"), - ], - graph: new PatternGraphDto - { - Nodes = - [ - CreateSystemNode("system-user-input", "user-input"), - CreateAgentNode("agent-1", 0), - CreateAgentNode("agent-2", 1), - CreateSystemNode("system-user-output", "user-output"), - ], - Edges = - [ - CreateEdge("system-user-input", "agent-node-agent-1"), - CreateEdge("system-user-input", "agent-node-agent-2"), - CreateEdge("agent-node-agent-1", "agent-node-agent-2"), - CreateEdge("agent-node-agent-2", "system-user-output"), - ], - })); - - Assert.Contains(issues, issue => - issue.Field == "graph" - && issue.Message.Contains("single path", StringComparison.OrdinalIgnoreCase)); - } - - private static PatternDefinitionDto CreatePattern( - string mode, - IReadOnlyList agents, - string availability = "available", - string? unavailabilityReason = null, - string name = "Pattern", - PatternGraphDto? graph = null) - { - return new PatternDefinitionDto - { - Id = $"{mode}-pattern", - Name = name, - Mode = mode, - Availability = availability, - UnavailabilityReason = unavailabilityReason, - Agents = agents, - Graph = graph, - }; - } - - private static PatternAgentDefinitionDto CreateAgent( - string id = "agent-1", - string name = "Primary", - string model = "gpt-5.4", - string instructions = "Help with the user's request.") - { - return new PatternAgentDefinitionDto - { - Id = id, - Name = name, - Model = model, - Instructions = instructions, - }; - } - - private static PatternGraphNodeDto CreateSystemNode(string id, string kind) - => new() - { - Id = id, - Kind = kind, - Position = new PatternGraphPositionDto(), - }; - - private static PatternGraphNodeDto CreateAgentNode(string agentId, int order) - => new() - { - Id = $"agent-node-{agentId}", - Kind = "agent", - AgentId = agentId, - Order = order, - Position = new PatternGraphPositionDto(), - }; - - private static PatternGraphEdgeDto CreateEdge(string source, string target) - => new() - { - Id = $"edge-{source}-to-{target}", - Source = source, - Target = target, - }; -} diff --git a/sidecar/tests/Aryx.AgentHost.Tests/WorkflowRequestInfoInterpreterTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/WorkflowRequestInfoInterpreterTests.cs index 7a7202a..57c4ed6 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/WorkflowRequestInfoInterpreterTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/WorkflowRequestInfoInterpreterTests.cs @@ -186,54 +186,52 @@ public sealed class WorkflowRequestInfoInterpreterTests } private static RunTurnCommandDto CreateSingleAgentCommand() - { - return new RunTurnCommandDto - { - RequestId = "turn-1", - SessionId = "session-1", - Pattern = new PatternDefinitionDto - { - Id = "pattern-single", - Name = "Single Agent", - Mode = "single", - Availability = "available", - Agents = - [ - CreateAgent("agent-1", "Primary"), - ], - }, - }; - } + => CreateCommand("single", [CreateAgent("agent-1", "Primary")]); private static RunTurnCommandDto CreateHandoffCommand() + => CreateCommand("handoff", + [ + CreateAgent("agent-handoff-triage", "Triage"), + CreateAgent("agent-handoff-ux", "UX Specialist"), + ]); + + private static RunTurnCommandDto CreateCommand(string orchestrationMode, IReadOnlyList agents) { return new RunTurnCommandDto { RequestId = "turn-1", SessionId = "session-1", - Pattern = new PatternDefinitionDto + Workflow = new WorkflowDefinitionDto { - Id = "pattern-handoff", - Name = "Handoff Flow", - Mode = "handoff", - Availability = "available", - Agents = - [ - CreateAgent("agent-handoff-triage", "Triage"), - CreateAgent("agent-handoff-ux", "UX Specialist"), - ], + Id = $"{orchestrationMode}-workflow", + Name = "Workflow", + Graph = new WorkflowGraphDto + { + Nodes = [.. agents], + }, + Settings = new WorkflowSettingsDto + { + OrchestrationMode = orchestrationMode, + }, }, }; } - private static PatternAgentDefinitionDto CreateAgent(string id, string name) + private static WorkflowNodeDto CreateAgent(string id, string name) { - return new PatternAgentDefinitionDto + return new WorkflowNodeDto { Id = id, - Name = name, - Model = "gpt-5.4", - Instructions = "Help with the request.", + Kind = "agent", + Label = name, + Config = new WorkflowNodeConfigDto + { + Kind = "agent", + Id = id, + Name = name, + Model = "gpt-5.4", + Instructions = "Help with the request.", + }, }; } diff --git a/sidecar/tests/Aryx.AgentHost.Tests/WorkflowRunnerTests.cs b/sidecar/tests/Aryx.AgentHost.Tests/WorkflowRunnerTests.cs index c26d080..f99c88d 100644 --- a/sidecar/tests/Aryx.AgentHost.Tests/WorkflowRunnerTests.cs +++ b/sidecar/tests/Aryx.AgentHost.Tests/WorkflowRunnerTests.cs @@ -15,7 +15,6 @@ public sealed class WorkflowRunnerTests WorkflowRunner runner = new(); Workflow workflow = runner.BuildWorkflow( CreateSubworkflowParent(inlineWorkflow: CreateAgentWorkflow("child-inline", "agent-child")), - CreatePattern("agent-child"), [CreateChatClientAgent("agent-child", "Child Agent")]); ProtocolDescriptor descriptor = await workflow.DescribeProtocolAsync(); @@ -30,7 +29,6 @@ public sealed class WorkflowRunnerTests WorkflowDefinitionDto childWorkflow = CreateAgentWorkflow("child-ref", "agent-child"); Workflow workflow = runner.BuildWorkflow( CreateSubworkflowParent(workflowId: childWorkflow.Id), - CreatePattern("agent-child"), [CreateChatClientAgent("agent-child", "Child Agent")], [childWorkflow]); @@ -46,7 +44,6 @@ public sealed class WorkflowRunnerTests InvalidOperationException error = Assert.Throws(() => runner.BuildWorkflow( CreateSubworkflowParent(workflowId: "missing-child"), - CreatePattern("agent-child"), [CreateChatClientAgent("agent-child", "Child Agent")], [])); @@ -65,7 +62,6 @@ public sealed class WorkflowRunnerTests Kind = "code-executor", Implementation = "return-text:done", }), - CreateEmptyPattern(), []); List output = await RunWorkflowToOutputAsync(workflow); @@ -81,7 +77,6 @@ public sealed class WorkflowRunnerTests WorkflowRunner runner = new(); Workflow workflow = runner.BuildWorkflow( CreateStatefulFunctionWorkflow(), - CreateEmptyPattern(), []); List output = await RunWorkflowToOutputAsync(workflow); @@ -105,7 +100,6 @@ public sealed class WorkflowRunnerTests ResponseType = "string", Prompt = "Approve the workflow?", }), - CreateEmptyPattern(), []); ChatMessage[] input = @@ -153,33 +147,11 @@ public sealed class WorkflowRunnerTests Kind = "function-executor", FunctionRef = "missing-function", }), - CreateEmptyPattern(), [])); Assert.Contains("unsupported functionRef", error.Message, StringComparison.OrdinalIgnoreCase); } - private static PatternDefinitionDto CreatePattern(string agentId) - { - return new PatternDefinitionDto - { - Id = "pattern-1", - Name = "Workflow Pattern", - Mode = "single", - Availability = "available", - Agents = - [ - new PatternAgentDefinitionDto - { - Id = agentId, - Name = "Child Agent", - Instructions = "Help with the request.", - Model = "gpt-5.4", - }, - ], - }; - } - private static WorkflowDefinitionDto CreateAgentWorkflow(string id, string agentId) { return new WorkflowDefinitionDto @@ -243,18 +215,6 @@ public sealed class WorkflowRunnerTests }; } - private static PatternDefinitionDto CreateEmptyPattern() - { - return new PatternDefinitionDto - { - Id = "pattern-empty", - Name = "Workflow Pattern", - Mode = "single", - Availability = "available", - Agents = [], - }; - } - private static WorkflowDefinitionDto CreateSubworkflowParent( string? workflowId = null, WorkflowDefinitionDto? inlineWorkflow = null) diff --git a/src/main/AryxAppService.ts b/src/main/AryxAppService.ts index b7f3a5a..0b553c4 100644 --- a/src/main/AryxAppService.ts +++ b/src/main/AryxAppService.ts @@ -26,20 +26,16 @@ import { buildAvailableModelCatalog, findModel, findModelByReference, - normalizePatternModels, + normalizeWorkflowModels, resolveReasoningEffort, } from '@shared/domain/models'; import { + buildWorkflowExecutionDefinition, isReasoningEffort, - syncPatternGraph, - type PatternDefinition, - type ReasoningEffort, - validatePatternDefinition, -} from '@shared/domain/pattern'; -import { - buildWorkflowExecutionPattern, normalizeWorkflowDefinition, + resolveWorkflowAgentNodes, validateWorkflowDefinition, + type ReasoningEffort, type WorkflowDefinition, type WorkflowReference, } from '@shared/domain/workflow'; @@ -51,7 +47,6 @@ import { } from '@shared/domain/workflowSerialization'; import { applyWorkflowTemplate, - buildWorkflowFromPattern, createWorkflowTemplateFromWorkflow, normalizeWorkflowTemplateDefinition, type WorkflowTemplateCategory, @@ -59,7 +54,7 @@ import { } from '@shared/domain/workflowTemplate'; import { normalizeWorkspaceAgentDefinition, - resolvePatternAgents, + resolveWorkflowAgents as resolveWorkspaceWorkflowAgents, type WorkspaceAgentDefinition, } from '@shared/domain/workspaceAgent'; import { @@ -82,6 +77,7 @@ import { type ProjectCustomizationState, } from '@shared/domain/projectCustomization'; import { + applyDefaultToolApprovalPolicy, approvalPolicyRequiresCheckpoint, dequeuePendingApprovalState, enqueuePendingApprovalState, @@ -138,6 +134,7 @@ import { upsertRunApprovalEvent, upsertRunMessageEvent, upsertSessionRunRecord, + type CreateSessionRunRecordInput, type RunTimelineEventRecord, type SessionRunRecord, } from '@shared/domain/runTimeline'; @@ -217,10 +214,6 @@ type WorkflowCheckpointRecoveryState = { type DiscoveredToolingResolution = 'accept' | 'dismiss'; -function isBuiltinPattern(patternId: string): boolean { - return patternId.startsWith('pattern-'); -} - function equalStringArrays(left?: readonly string[], right?: readonly string[]): boolean { const normalizedLeft = left ?? []; const normalizedRight = right ?? []; @@ -613,37 +606,6 @@ export class AryxAppService extends EventEmitter { return result; } - async savePattern(pattern: PatternDefinition): Promise { - const workspace = await this.loadWorkspace(); - const knownApprovalToolNames = await this.listKnownApprovalToolNames(workspace); - const synchronizedPattern = pattern.graph ? pattern : syncPatternGraph(pattern); - const issues = validatePatternDefinition( - synchronizedPattern, - knownApprovalToolNames, - ).filter((issue) => issue.level === 'error'); - if (issues.length > 0) { - throw new Error(issues[0].message); - } - - const existingIndex = workspace.patterns.findIndex((current) => current.id === pattern.id); - const candidate: PatternDefinition = { - ...synchronizedPattern, - approvalPolicy: normalizeApprovalPolicy(synchronizedPattern.approvalPolicy), - isFavorite: pattern.isFavorite ?? workspace.patterns[existingIndex]?.isFavorite, - createdAt: existingIndex >= 0 ? workspace.patterns[existingIndex].createdAt : nowIso(), - updatedAt: nowIso(), - }; - - if (existingIndex >= 0) { - workspace.patterns[existingIndex] = candidate; - } else { - workspace.patterns.push(candidate); - } - - workspace.selectedPatternId = candidate.id; - return this.persistAndBroadcast(workspace); - } - async saveWorkflow(workflow: WorkflowDefinition): Promise { const workspace = await this.loadWorkspace(); const normalizedWorkflow = normalizeWorkflowDefinition(workflow); @@ -747,48 +709,6 @@ export class AryxAppService extends EventEmitter { }; } - async upgradePatternToWorkflow( - patternId: string, - options?: { - workflowId?: string; - name?: string; - description?: string; - save?: boolean; - }, - ): Promise<{ workflow: WorkflowDefinition; workspace?: WorkspaceState }> { - const workspace = await this.loadWorkspace(); - const pattern = this.requirePattern(workspace, patternId); - const baseWorkflow = buildWorkflowFromPattern(pattern); - const workflowId = options?.workflowId?.trim() - || this.createUniqueWorkflowId(workspace, baseWorkflow.id); - const workflow = normalizeWorkflowDefinition({ - ...baseWorkflow, - id: workflowId, - name: options?.name?.trim() || baseWorkflow.name, - description: options?.description?.trim() ?? baseWorkflow.description, - createdAt: nowIso(), - updatedAt: nowIso(), - }); - - if (!options?.save) { - return { workflow }; - } - - const savedWorkspace = await this.saveWorkflow(workflow); - return { - workflow, - workspace: savedWorkspace, - }; - } - - async setPatternFavorite(patternId: string, isFavorite: boolean): Promise { - const workspace = await this.loadWorkspace(); - const pattern = this.requirePattern(workspace, patternId); - pattern.isFavorite = isFavorite; - pattern.updatedAt = nowIso(); - return this.persistAndBroadcast(workspace); - } - async setTheme(theme: AppearanceTheme): Promise { const workspace = await this.loadWorkspace(); workspace.settings.theme = normalizeTheme(theme); @@ -867,23 +787,6 @@ export class AryxAppService extends EventEmitter { this.ptyManager.resize(cols, rows); } - async deletePattern(patternId: string): Promise { - const workspace = await this.loadWorkspace(); - workspace.patterns = workspace.patterns.filter((pattern) => pattern.id !== patternId); - - if (isBuiltinPattern(patternId)) { - const deletedIds = new Set(workspace.deletedBuiltinPatternIds ?? []); - deletedIds.add(patternId); - workspace.deletedBuiltinPatternIds = [...deletedIds]; - } - - if (workspace.selectedPatternId === patternId) { - workspace.selectedPatternId = workspace.patterns[0]?.id; - } - - return this.persistAndBroadcast(workspace); - } - async deleteWorkflow(workflowId: string): Promise { const workspace = await this.loadWorkspace(); const workflow = this.requireWorkflow(workspace, workflowId); @@ -1038,50 +941,19 @@ export class AryxAppService extends EventEmitter { return this.persistAndBroadcast(workspace); } - async createSession(projectId: string, patternId: string): Promise { - const workspace = await this.loadWorkspace(); - const project = this.requireProject(workspace, projectId); - const pattern = this.requirePattern(workspace, patternId); - const modelCatalog = await this.loadAvailableModelCatalog(); - const normalizedPattern = normalizePatternModels(pattern, modelCatalog); - - const session: SessionRecord = { - id: createId('session'), - projectId: project.id, - patternId: pattern.id, - title: pattern.name, - titleSource: 'auto', - createdAt: nowIso(), - updatedAt: nowIso(), - status: 'idle', - messages: [], - sessionModelConfig: normalizedPattern.agents.length === 1 - ? createSessionModelConfig(normalizedPattern) - : undefined, - tooling: createSessionToolingSelection(), - runs: [], - }; - - await this.ensureScratchpadSessionDirectory(session); - workspace.sessions.unshift(session); - workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; - workspace.selectedWorkflowId = undefined; - workspace.selectedSessionId = session.id; - return this.persistAndBroadcast(workspace); - } - - async createWorkflowSession(projectId: string, workflowId: string): Promise { + async createSession(projectId: string, workflowId: string): Promise { const workspace = await this.loadWorkspace(); const project = this.requireProject(workspace, projectId); const workflow = this.requireWorkflow(workspace, workflowId); const modelCatalog = await this.loadAvailableModelCatalog(); - const executionPattern = normalizePatternModels(this.buildResolvedWorkflowExecutionPattern(workspace, workflow), modelCatalog); + const executionWorkflow = normalizeWorkflowModels( + this.buildResolvedExecutionWorkflow(workspace, workflow), + modelCatalog, + ); const session: SessionRecord = { id: createId('session'), projectId: project.id, - patternId: workflow.id, workflowId: workflow.id, title: workflow.name, titleSource: 'auto', @@ -1089,9 +961,10 @@ export class AryxAppService extends EventEmitter { updatedAt: nowIso(), status: 'idle', messages: [], - sessionModelConfig: executionPattern.agents.length === 1 - ? createSessionModelConfig(executionPattern) - : undefined, + sessionModelConfig: createSessionModelConfig( + executionWorkflow, + this.createWorkflowResolutionOptions(workspace), + ), tooling: createSessionToolingSelection(), runs: [], }; @@ -1099,12 +972,15 @@ export class AryxAppService extends EventEmitter { await this.ensureScratchpadSessionDirectory(session); workspace.sessions.unshift(session); workspace.selectedProjectId = project.id; - workspace.selectedPatternId = undefined; workspace.selectedWorkflowId = workflow.id; workspace.selectedSessionId = session.id; return this.persistAndBroadcast(workspace); } + async createWorkflowSession(projectId: string, workflowId: string): Promise { + return this.createSession(projectId, workflowId); + } + async duplicateSession(sessionId: string): Promise { const workspace = await this.loadWorkspace(); const session = this.requireSession(workspace, sessionId); @@ -1116,7 +992,7 @@ export class AryxAppService extends EventEmitter { await this.ensureScratchpadSessionDirectory(duplicate); workspace.sessions.unshift(duplicate); workspace.selectedProjectId = duplicate.projectId; - workspace.selectedPatternId = duplicate.patternId; + workspace.selectedWorkflowId = duplicate.workflowId; workspace.selectedSessionId = duplicate.id; return this.persistAndBroadcast(workspace); } @@ -1124,8 +1000,8 @@ export class AryxAppService extends EventEmitter { async branchSession(sessionId: string, messageId: string): Promise { const workspace = await this.loadWorkspace(); const session = this.requireSession(workspace, sessionId); - const pattern = this.requirePattern(workspace, session.patternId); - const branch = branchSessionRecord(session, pattern, createId('session'), messageId, nowIso()); + const workflow = this.requireWorkflow(workspace, session.workflowId); + const branch = branchSessionRecord(session, workflow, createId('session'), messageId, nowIso()); if (isScratchpadProject(branch.projectId)) { branch.cwd = undefined; } @@ -1133,7 +1009,7 @@ export class AryxAppService extends EventEmitter { await this.ensureScratchpadSessionDirectory(branch); workspace.sessions.unshift(branch); workspace.selectedProjectId = branch.projectId; - workspace.selectedPatternId = branch.patternId; + workspace.selectedWorkflowId = branch.workflowId; workspace.selectedSessionId = branch.id; return this.persistAndBroadcast(workspace); } @@ -1213,16 +1089,16 @@ export class AryxAppService extends EventEmitter { } const project = this.requireProject(workspace, session.projectId); - const { pattern, workflow } = this.resolveSessionExecutionDefinition(workspace, session); - const effectivePattern = this.applyProjectCustomizationToPattern( - await this.buildEffectivePattern(pattern, session, workspace.settings.agents ?? []), + const workflow = this.resolveSessionWorkflow(workspace, session); + const effectiveWorkflow = this.applyProjectCustomizationToWorkflow( + await this.buildEffectiveWorkflow(workflow, session, workspace.settings.agents ?? []), project, ); const projectInstructions = resolveProjectInstructionsContent(project.customization); const occurredAt = nowIso(); const regeneratedSession = regenerateSessionRecord( session, - effectivePattern, + effectiveWorkflow, createId('session'), messageId, occurredAt, @@ -1234,7 +1110,7 @@ export class AryxAppService extends EventEmitter { await this.ensureScratchpadSessionDirectory(regeneratedSession); workspace.sessions.unshift(regeneratedSession); workspace.selectedProjectId = regeneratedSession.projectId; - workspace.selectedPatternId = regeneratedSession.patternId; + workspace.selectedWorkflowId = regeneratedSession.workflowId; workspace.selectedSessionId = regeneratedSession.id; const triggerMessage = regeneratedSession.messages.at(-1); @@ -1246,14 +1122,13 @@ export class AryxAppService extends EventEmitter { workspace, regeneratedSession, project, - effectivePattern, + effectiveWorkflow, projectInstructions, { occurredAt, requestId: createId('turn'), triggerMessageId: triggerMessage.id, }, - workflow, ); } @@ -1280,9 +1155,9 @@ export class AryxAppService extends EventEmitter { } const project = this.requireProject(workspace, session.projectId); - const { pattern, workflow } = this.resolveSessionExecutionDefinition(workspace, session); - const effectivePattern = this.applyProjectCustomizationToPattern( - await this.buildEffectivePattern(pattern, session, workspace.settings.agents ?? []), + const workflow = this.resolveSessionWorkflow(workspace, session); + const effectiveWorkflow = this.applyProjectCustomizationToWorkflow( + await this.buildEffectiveWorkflow(workflow, session, workspace.settings.agents ?? []), project, ); const projectInstructions = resolveProjectInstructionsContent(project.customization); @@ -1290,7 +1165,7 @@ export class AryxAppService extends EventEmitter { const nextAttachments = attachments === undefined ? sourceMessage.attachments : attachments; const editedSession = editAndResendSessionRecord( session, - effectivePattern, + effectiveWorkflow, createId('session'), messageId, preparedContent, @@ -1304,7 +1179,7 @@ export class AryxAppService extends EventEmitter { await this.ensureScratchpadSessionDirectory(editedSession); workspace.sessions.unshift(editedSession); workspace.selectedProjectId = editedSession.projectId; - workspace.selectedPatternId = editedSession.patternId; + workspace.selectedWorkflowId = editedSession.workflowId; workspace.selectedSessionId = editedSession.id; const triggerMessage = editedSession.messages.at(-1); @@ -1316,14 +1191,13 @@ export class AryxAppService extends EventEmitter { workspace, editedSession, project, - effectivePattern, + effectiveWorkflow, projectInstructions, { occurredAt, requestId: createId('turn'), triggerMessageId: triggerMessage.id, }, - workflow, ); } @@ -1342,9 +1216,9 @@ export class AryxAppService extends EventEmitter { throw new Error('Wait for the current response or approval checkpoint to finish before sending another message.'); } const project = this.requireProject(workspace, session.projectId); - const { pattern, workflow } = this.resolveSessionExecutionDefinition(workspace, session); - const effectivePattern = this.applyProjectCustomizationToPattern( - await this.buildEffectivePattern(pattern, session, workspace.settings.agents ?? []), + const workflow = this.resolveSessionWorkflow(workspace, session); + const effectiveWorkflow = this.applyProjectCustomizationToWorkflow( + await this.buildEffectiveWorkflow(workflow, session, workspace.settings.agents ?? []), project, ); const projectInstructions = resolveProjectInstructionsContent(project.customization); @@ -1375,7 +1249,7 @@ export class AryxAppService extends EventEmitter { workspace, session, project, - effectivePattern, + effectiveWorkflow, projectInstructions, { occurredAt, @@ -1384,7 +1258,6 @@ export class AryxAppService extends EventEmitter { messageMode, attachments, }, - workflow, ); } @@ -1572,10 +1445,13 @@ export class AryxAppService extends EventEmitter { const session = this.requireSession(workspace, sessionId); const project = this.requireProject(workspace, session.projectId); const modelCatalog = await this.loadAvailableModelCatalog(); - const { pattern } = this.resolveSessionExecutionDefinition(workspace, session); - const effectivePattern = normalizePatternModels(pattern, modelCatalog); + const workflow = normalizeWorkflowModels( + this.buildResolvedExecutionWorkflow(workspace, this.requireWorkflow(workspace, session.workflowId)), + modelCatalog, + ); + const agentNodes = resolveWorkflowAgentNodes(workflow); - if (effectivePattern.agents.length !== 1) { + if (agentNodes.length !== 1) { throw new Error('Model override is only supported for single-agent sessions.'); } @@ -1732,7 +1608,7 @@ export class AryxAppService extends EventEmitter { workspace: WorkspaceState, session: SessionRecord, project: ProjectRecord, - effectivePattern: PatternDefinition, + effectiveWorkflow: WorkflowDefinition, projectInstructions: string | undefined, options: { occurredAt: string; @@ -1741,12 +1617,11 @@ export class AryxAppService extends EventEmitter { messageMode?: MessageMode; attachments?: ChatMessageAttachment[]; }, - effectiveWorkflow?: WorkflowDefinition, ): Promise { const workspaceKind = isScratchpadProject(project) ? 'scratchpad' : 'project'; const { occurredAt, requestId, triggerMessageId, messageMode, attachments } = options; const promptInvocation = this.resolveRunTurnPromptInvocation(session, triggerMessageId); - const patternForTurn = await this.applyPromptInvocationToPattern(effectivePattern, promptInvocation); + const workflowForTurn = await this.applyPromptInvocationToWorkflow(effectiveWorkflow, promptInvocation); const interactionMode: InteractionMode = isPlanPromptInvocation(promptInvocation) ? 'plan' : session.interactionMode ?? 'interactive'; @@ -1761,7 +1636,7 @@ export class AryxAppService extends EventEmitter { console.warn(`[aryx git] Failed to capture pre-run git snapshot for project "${project.id}".`); } - session.title = resolveSessionTitle(session, patternForTurn, session.messages); + session.title = resolveSessionTitle(session, workflowForTurn, session.messages); session.status = 'running'; session.lastError = undefined; session.pendingPlanReview = undefined; @@ -1773,8 +1648,7 @@ export class AryxAppService extends EventEmitter { project, workingDirectory: runWorkingDirectory, workspaceKind, - pattern: patternForTurn, - workflow: effectiveWorkflow ? { id: effectiveWorkflow.id, name: effectiveWorkflow.name } : undefined, + workflow: workflowForTurn, triggerMessageId, startedAt: occurredAt, preRunGitSnapshot, @@ -1803,9 +1677,8 @@ export class AryxAppService extends EventEmitter { mode: interactionMode, messageMode, projectInstructions, - pattern: patternForTurn, - workflow: effectiveWorkflow, - workflowLibrary: effectiveWorkflow ? workspace.workflows : undefined, + workflow: workflowForTurn, + workflowLibrary: workspace.workflows, messages: session.messages, attachments: attachments?.length ? attachments : undefined, promptInvocation, @@ -1846,7 +1719,7 @@ export class AryxAppService extends EventEmitter { }, ); - await this.awaitFinalResponseApproval(workspace, session.id, requestId, effectivePattern, responseMessages); + await this.awaitFinalResponseApproval(workspace, session.id, requestId, workflowForTurn, responseMessages); this.finalizeTurn(workspace, session.id, requestId, responseMessages); if (workspaceKind === 'project') { const completedRun = await this.refreshSessionRunGitSummary(session, project, requestId, nowIso()); @@ -2194,13 +2067,6 @@ export class AryxAppService extends EventEmitter { return this.persistAndBroadcast(workspace); } - async selectPattern(patternId?: string): Promise { - const workspace = await this.loadWorkspace(); - workspace.selectedPatternId = patternId; - workspace.selectedSessionId = workspace.selectedSessionId; - return this.persistAndBroadcast(workspace); - } - async selectSession(sessionId?: string): Promise { const workspace = await this.loadWorkspace(); if (sessionId) { @@ -2365,15 +2231,6 @@ export class AryxAppService extends EventEmitter { } } - private requirePattern(workspace: WorkspaceState, patternId: string): PatternDefinition { - const pattern = workspace.patterns.find((current) => current.id === patternId); - if (!pattern) { - throw new Error(`Pattern "${patternId}" was not found.`); - } - - return pattern; - } - private requireWorkflowTemplate(workspace: WorkspaceState, templateId: string): WorkflowTemplateDefinition { const template = workspace.workflowTemplates.find((current) => current.id === templateId); if (!template) { @@ -2417,32 +2274,32 @@ export class AryxAppService extends EventEmitter { return normalized || createId(fallbackPrefix); } - private resolveSessionExecutionDefinition( + private resolveSessionWorkflow( workspace: WorkspaceState, session: SessionRecord, - ): { pattern: PatternDefinition; workflow?: WorkflowDefinition } { - if (session.workflowId) { - const workflow = this.requireWorkflow(workspace, session.workflowId); - return { - workflow, - pattern: this.buildResolvedWorkflowExecutionPattern(workspace, workflow), - }; - } - - return { - pattern: this.requirePattern(workspace, session.patternId), - }; + ): WorkflowDefinition { + return this.requireWorkflow(workspace, session.workflowId); } - private buildResolvedWorkflowExecutionPattern( + private buildResolvedExecutionWorkflow( workspace: WorkspaceState, workflow: WorkflowDefinition, - ): PatternDefinition { - return buildWorkflowExecutionPattern(workflow, { - resolveWorkflow: (workflowId) => workspace.workflows.find((candidate) => candidate.id === workflowId), + ): WorkflowDefinition { + return normalizeWorkflowDefinition({ + ...workflow, + settings: { + ...workflow.settings, + approvalPolicy: applyDefaultToolApprovalPolicy(workflow.settings.approvalPolicy), + }, }); } + private createWorkflowResolutionOptions(workspace: WorkspaceState) { + return { + resolveWorkflow: (workflowId: string) => workspace.workflows.find((candidate) => candidate.id === workflowId), + }; + } + private validateWorkflowReferences( workspace: WorkspaceState, workflow: WorkflowDefinition, @@ -2712,15 +2569,19 @@ export class AryxAppService extends EventEmitter { private emitCompletedActivity( sessionId: string, - pattern: PatternDefinition, + workflow: WorkflowDefinition, message: ChatMessageRecord, ): void { if (message.role !== 'assistant') { return; } - const agent = pattern.agents.find((candidate) => - candidate.id === message.authorName || candidate.name === message.authorName); + const agentNode = resolveWorkflowAgentNodes(workflow) + .find((candidate) => + candidate.config.kind === 'agent' + && (candidate.config.id === message.authorName || candidate.config.name === message.authorName)) + ; + const agent = agentNode?.config.kind === 'agent' ? agentNode.config : undefined; if (!agent) { return; } @@ -2742,7 +2603,7 @@ export class AryxAppService extends EventEmitter { messages: ChatMessageRecord[], ): void { const session = this.requireSession(workspace, sessionId); - const { pattern } = this.resolveSessionExecutionDefinition(workspace, session); + const workflow = this.resolveSessionWorkflow(workspace, session); const incomingIds = new Set(messages.map((message) => message.id)); // Messages that were streamed during the turn already exist in session.messages @@ -2807,7 +2668,7 @@ export class AryxAppService extends EventEmitter { this.emitRunUpdated(sessionId, occurredAt, nextRun); } - this.emitCompletedActivity(sessionId, pattern, message); + this.emitCompletedActivity(sessionId, workflow, message); } for (const message of session.messages) { @@ -3275,10 +3136,10 @@ export class AryxAppService extends EventEmitter { workspace: WorkspaceState, sessionId: string, requestId: string, - pattern: PatternDefinition, + workflow: WorkflowDefinition, messages: ChatMessageRecord[], ): Promise { - const pendingApproval = this.buildFinalResponseApproval(pattern, messages); + const pendingApproval = this.buildFinalResponseApproval(workflow, messages); if (!pendingApproval) { return; } @@ -3305,7 +3166,7 @@ export class AryxAppService extends EventEmitter { } private buildFinalResponseApproval( - pattern: PatternDefinition, + workflow: WorkflowDefinition, messages: ChatMessageRecord[], ): PendingApprovalRecord | undefined { const assistantMessages = messages.filter((message) => message.role === 'assistant'); @@ -3325,9 +3186,13 @@ export class AryxAppService extends EventEmitter { continue; } - const agent = pattern.agents.find((candidate) => - candidate.id === message.authorName || candidate.name === message.authorName); - if (!approvalPolicyRequiresCheckpoint(pattern.approvalPolicy, 'final-response', agent?.id)) { + const agentNode = resolveWorkflowAgentNodes(workflow) + .find((candidate) => + candidate.config.kind === 'agent' + && (candidate.config.id === message.authorName || candidate.config.name === message.authorName)) + ; + const agent = agentNode?.config.kind === 'agent' ? agentNode.config : undefined; + if (!approvalPolicyRequiresCheckpoint(workflow.settings.approvalPolicy, 'final-response', agent?.id)) { continue; } @@ -3363,28 +3228,28 @@ export class AryxAppService extends EventEmitter { } } - private async buildEffectivePattern( - pattern: PatternDefinition, + private async buildEffectiveWorkflow( + workflow: WorkflowDefinition, session: SessionRecord, workspaceAgents: ReadonlyArray, - ): Promise { - const resolvedPattern = resolvePatternAgents(pattern, workspaceAgents); - const patternWithSessionConfig = session.sessionModelConfig - ? applySessionModelConfig(resolvedPattern, session) - : resolvedPattern; - const patternWithApprovalSettings = applySessionApprovalSettings(patternWithSessionConfig, session); + ): Promise { + const resolvedWorkflow = resolveWorkspaceWorkflowAgents(workflow, workspaceAgents); + const workflowWithSessionConfig = session.sessionModelConfig + ? applySessionModelConfig(resolvedWorkflow, session) + : resolvedWorkflow; + const workflowWithApprovalSettings = applySessionApprovalSettings(workflowWithSessionConfig, session); const modelCatalog = await this.loadAvailableModelCatalog(); - return normalizePatternModels(patternWithApprovalSettings, modelCatalog); + return normalizeWorkflowModels(workflowWithApprovalSettings, modelCatalog); } - private async applyPromptInvocationToPattern( - pattern: PatternDefinition, + private async applyPromptInvocationToWorkflow( + workflow: WorkflowDefinition, promptInvocation?: ProjectPromptInvocation, - ): Promise { + ): Promise { const requestedModel = promptInvocation?.model?.trim(); if (!requestedModel) { - return pattern; + return workflow; } const modelCatalog = await this.loadAvailableModelCatalog(); @@ -3392,7 +3257,12 @@ export class AryxAppService extends EventEmitter { const effectiveModelId = resolvedModel?.id ?? requestedModel; let didChange = false; - const agents = pattern.agents.map((agent) => { + const nodes = workflow.graph.nodes.map((node) => { + if (node.kind !== 'agent' || node.config.kind !== 'agent') { + return node; + } + + const agent = node.config; // When overriding the model, re-normalize reasoning effort for the target model. // If the target model's reasoning capabilities are unknown (supportedReasoningEfforts // is undefined — common for dynamically-discovered models), strip reasoning effort @@ -3405,39 +3275,50 @@ export class AryxAppService extends EventEmitter { } if (agent.model === effectiveModelId && agent.reasoningEffort === reasoningEffort) { - return agent; + return node; } didChange = true; return { - ...agent, - model: effectiveModelId, - reasoningEffort, + ...node, + config: { + ...agent, + model: effectiveModelId, + reasoningEffort, + }, }; }); - return didChange ? { ...pattern, agents } : pattern; + return didChange + ? { + ...workflow, + graph: { + ...workflow.graph, + nodes, + }, + } + : workflow; } - private applyProjectCustomizationToPattern( - pattern: PatternDefinition, + private applyProjectCustomizationToWorkflow( + workflow: WorkflowDefinition, project: ProjectRecord, - ): PatternDefinition { + ): WorkflowDefinition { if (isScratchpadProject(project)) { - return pattern; + return workflow; } const projectCustomAgents = this.buildProjectCustomAgents(project.customization); if (projectCustomAgents.length === 0) { - return pattern; + return workflow; } - const [primaryAgent, ...remainingAgents] = pattern.agents; - if (!primaryAgent) { - return pattern; + const primaryAgentNode = resolveWorkflowAgentNodes(workflow)[0]; + if (!primaryAgentNode || primaryAgentNode.config.kind !== 'agent') { + return workflow; } - const existingCustomAgents = primaryAgent.copilot?.customAgents ?? []; + const existingCustomAgents = primaryAgentNode.config.copilot?.customAgents ?? []; const existingAgentNames = new Set(existingCustomAgents.map((agent) => agent.name.toLowerCase())); const mergedCustomAgents = [ ...existingCustomAgents, @@ -3445,17 +3326,26 @@ export class AryxAppService extends EventEmitter { ]; return { - ...pattern, - agents: [ - { - ...primaryAgent, - copilot: { - ...primaryAgent.copilot, - customAgents: mergedCustomAgents, - }, - }, - ...remainingAgents, - ], + ...workflow, + graph: { + ...workflow.graph, + nodes: workflow.graph.nodes.map((node) => { + if (node.id !== primaryAgentNode.id || node.kind !== 'agent' || node.config.kind !== 'agent') { + return node; + } + + return { + ...node, + config: { + ...node.config, + copilot: { + ...node.config.copilot, + customAgents: mergedCustomAgents, + }, + }, + }; + }), + }, }; } @@ -3511,13 +3401,13 @@ export class AryxAppService extends EventEmitter { ); let changed = false; - for (const pattern of workspace.patterns) { - const nextPolicy = pruneApprovalPolicyTools(pattern.approvalPolicy, workspaceKnownToolNames); + for (const workflow of workspace.workflows) { + const nextPolicy = pruneApprovalPolicyTools(workflow.settings.approvalPolicy, workspaceKnownToolNames); if (!equalStringArrays( - pattern.approvalPolicy?.autoApprovedToolNames, + workflow.settings.approvalPolicy?.autoApprovedToolNames, nextPolicy?.autoApprovedToolNames, )) { - pattern.approvalPolicy = nextPolicy; + workflow.settings.approvalPolicy = nextPolicy; changed = true; } } diff --git a/src/main/ipc/registerIpcHandlers.ts b/src/main/ipc/registerIpcHandlers.ts index e00ff51..251bd30 100644 --- a/src/main/ipc/registerIpcHandlers.ts +++ b/src/main/ipc/registerIpcHandlers.ts @@ -37,12 +37,10 @@ import type { ResolveSessionUserInputInput, SaveLspProfileInput, SaveMcpServerInput, - SavePatternInput, SaveWorkflowInput, SaveWorkflowTemplateInput, SaveWorkspaceAgentInput, SendSessionMessageInput, - SetPatternFavoriteInput, SetProjectAgentProfileEnabledInput, SetSessionArchivedInput, SetSessionInteractionModeInput, @@ -53,7 +51,6 @@ import type { UpdateSessionModelConfigInput, UpdateSessionApprovalSettingsInput, UpdateSessionToolingInput, - UpgradePatternToWorkflowInput, } from '@shared/contracts/ipc'; import type { QuerySessionsInput } from '@shared/domain/sessionLibrary'; import type { AppearanceTheme } from '@shared/domain/tooling'; @@ -114,11 +111,6 @@ export function registerIpcHandlers( (_event, input: SetProjectAgentProfileEnabledInput) => service.setProjectAgentProfileEnabled(input.projectId, input.agentProfileId, input.enabled), ); - ipcMain.handle(ipcChannels.savePattern, (_event, input: SavePatternInput) => service.savePattern(input.pattern)); - ipcMain.handle(ipcChannels.deletePattern, (_event, patternId: string) => service.deletePattern(patternId)); - ipcMain.handle(ipcChannels.setPatternFavorite, (_event, input: SetPatternFavoriteInput) => - service.setPatternFavorite(input.patternId, input.isFavorite), - ); ipcMain.handle(ipcChannels.saveWorkflow, (_event, input: SaveWorkflowInput) => service.saveWorkflow(input.workflow)); ipcMain.handle(ipcChannels.saveWorkflowTemplate, (_event, input: SaveWorkflowTemplateInput) => service.saveWorkflowTemplate(input.workflowId, input.options), @@ -136,9 +128,6 @@ export function registerIpcHandlers( ipcMain.handle(ipcChannels.importWorkflow, (_event, input: ImportWorkflowInput) => service.importWorkflow(input.content, input.format, input.options), ); - ipcMain.handle(ipcChannels.upgradePatternToWorkflow, (_event, input: UpgradePatternToWorkflowInput) => - service.upgradePatternToWorkflow(input.patternId, input.options), - ); ipcMain.handle(ipcChannels.setTheme, async (_event, theme: AppearanceTheme) => { const result = await service.setTheme(theme); applyTitleBarTheme(window, theme); @@ -205,7 +194,7 @@ export function registerIpcHandlers( service.updateSessionApprovalSettings(input.sessionId, input.autoApprovedToolNames), ); ipcMain.handle(ipcChannels.createSession, (_event, input: CreateSessionInput) => - service.createSession(input.projectId, input.patternId), + service.createSession(input.projectId, input.workflowId), ); ipcMain.handle(ipcChannels.createWorkflowSession, (_event, input: CreateWorkflowSessionInput) => service.createWorkflowSession(input.projectId, input.workflowId), @@ -321,7 +310,6 @@ export function registerIpcHandlers( ); ipcMain.handle(ipcChannels.querySessions, (_event, input: QuerySessionsInput) => service.querySessions(input)); ipcMain.handle(ipcChannels.selectProject, (_event, projectId?: string) => service.selectProject(projectId)); - ipcMain.handle(ipcChannels.selectPattern, (_event, patternId?: string) => service.selectPattern(patternId)); ipcMain.handle(ipcChannels.selectSession, (_event, sessionId?: string) => service.selectSession(sessionId)); ipcMain.handle(ipcChannels.openAppDataFolder, () => service.openAppDataFolder()); ipcMain.handle(ipcChannels.resetLocalWorkspace, () => service.resetLocalWorkspace()); diff --git a/src/main/persistence/workspaceRepository.ts b/src/main/persistence/workspaceRepository.ts index c91da70..b39178e 100644 --- a/src/main/persistence/workspaceRepository.ts +++ b/src/main/persistence/workspaceRepository.ts @@ -1,8 +1,5 @@ import { mkdir } from 'node:fs/promises'; -import { createBuiltinPatterns, resolvePatternGraph } from '@shared/domain/pattern'; -import type { PatternDefinition } from '@shared/domain/pattern'; -import { isScratchpadProject, mergeScratchpadProject } from '@shared/domain/project'; import { normalizeDiscoveredToolingState } from '@shared/domain/discoveredTooling'; import { normalizeProjectCustomizationState } from '@shared/domain/projectCustomization'; import { normalizeSessionRunRecords } from '@shared/domain/runTimeline'; @@ -20,13 +17,18 @@ import { normalizeWorkflowTemplateDefinition, type WorkflowTemplateDefinition, } from '@shared/domain/workflowTemplate'; -import { normalizeWorkflowDefinition } from '@shared/domain/workflow'; +import { + createBuiltinWorkflows, + normalizeWorkflowDefinition, + type WorkflowDefinition, +} from '@shared/domain/workflow'; import { applyDefaultToolApprovalPolicy, normalizePendingApprovalState, normalizeSessionApprovalSettings, } from '@shared/domain/approval'; import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace'; +import { isScratchpadProject, mergeScratchpadProject } from '@shared/domain/project'; import { nowIso } from '@shared/utils/ids'; import { @@ -36,31 +38,31 @@ import { } from '@main/persistence/appPaths'; import { readJsonFile, writeJsonFile } from '@main/persistence/jsonStore'; -function mergePatterns(existingPatterns: PatternDefinition[], deletedBuiltinIds: string[]): PatternDefinition[] { - const builtinTimestamp = nowIso(); - const builtinPatterns = createBuiltinPatterns(builtinTimestamp); - const builtinIds = new Set(builtinPatterns.map((pattern) => pattern.id)); - const deletedSet = new Set(deletedBuiltinIds); - const existingMap = new Map(existingPatterns.map((pattern) => [pattern.id, pattern])); +function mergeBuiltinWorkflows(existingWorkflows: WorkflowDefinition[]): WorkflowDefinition[] { + const builtinWorkflows = createBuiltinWorkflows(nowIso()); + const builtinIds = new Set(builtinWorkflows.map((workflow) => workflow.id)); + const existingMap = new Map(existingWorkflows.map((workflow) => [workflow.id, workflow])); - const mergedBuiltins = builtinPatterns - .filter((builtin) => !deletedSet.has(builtin.id)) - .map((builtin) => { + const mergedBuiltins = builtinWorkflows.map((builtin) => { const existing = existingMap.get(builtin.id); if (!existing) { return builtin; } - return { + return normalizeWorkflowDefinition({ ...existing, - availability: builtin.availability, - unavailabilityReason: builtin.unavailabilityReason, - mode: builtin.mode, - }; + settings: { + ...existing.settings, + orchestrationMode: builtin.settings.orchestrationMode, + }, + }); }); - const customPatterns = existingPatterns.filter((pattern) => !builtinIds.has(pattern.id)); - return [...mergedBuiltins, ...customPatterns]; + const customWorkflows = existingWorkflows + .filter((workflow) => !builtinIds.has(workflow.id)) + .map(normalizeWorkflowDefinition); + + return [...mergedBuiltins, ...customWorkflows]; } function mergeWorkflowTemplates(existingTemplates: WorkflowTemplateDefinition[]): WorkflowTemplateDefinition[] { @@ -73,6 +75,28 @@ function mergeWorkflowTemplates(existingTemplates: WorkflowTemplateDefinition[]) return [...builtinTemplates, ...customTemplates]; } +function migrateLegacySessions( + sessions: SessionRecord[], + workflows: WorkflowDefinition[], +): SessionRecord[] { + const workflowIds = new Set(workflows.map((workflow) => workflow.id)); + const fallbackWorkflowId = workflows[0]?.id; + + return sessions.flatMap((session) => { + const workflowId = session.workflowId && workflowIds.has(session.workflowId) + ? session.workflowId + : fallbackWorkflowId; + if (!workflowId) { + return []; + } + + return [{ + ...session, + workflowId, + }]; + }); +} + export class WorkspaceRepository { readonly filePath = getWorkspaceFilePath(); readonly scratchpadPath = getScratchpadDirectoryPath(); @@ -80,7 +104,7 @@ export class WorkspaceRepository { async load(): Promise { await mkdir(this.scratchpadPath, { recursive: true }); - const stored = await readJsonFile(this.filePath); + const stored = await readJsonFile(this.filePath); if (!stored) { const seededBase = createWorkspaceSeed(); const projects = mergeScratchpadProject([], this.scratchpadPath); @@ -101,50 +125,58 @@ export class WorkspaceRepository { })), this.scratchpadPath, ); - const sessions = await Promise.all((stored.sessions ?? []).map(async (session): Promise => { - const normalizedSession: SessionRecord = { - ...session, - messages: (session.messages ?? []).map(normalizeChatMessageRecord), - branchOrigin: normalizeSessionBranchOrigin(session.branchOrigin), - runs: normalizeSessionRunRecords(session.runs), - tooling: normalizeSessionToolingSelection(session.tooling), - approvalSettings: normalizeSessionApprovalSettings(session.approvalSettings), - ...normalizePendingApprovalState({ - pendingApproval: session.pendingApproval, - pendingApprovalQueue: session.pendingApprovalQueue, - }), - }; - if (!isScratchpadProject(normalizedSession.projectId)) { - return normalizedSession; - } - const cwd = normalizedSession.cwd ?? getScratchpadSessionPath(normalizedSession.id); - await mkdir(cwd, { recursive: true }); - return { - ...normalizedSession, - cwd, - }; - })); + const workflows = mergeBuiltinWorkflows((stored.workflows ?? []).map(normalizeWorkflowDefinition)) + .map((workflow) => ({ + ...workflow, + settings: { + ...workflow.settings, + approvalPolicy: applyDefaultToolApprovalPolicy(workflow.settings.approvalPolicy), + }, + })); + + const sessions = migrateLegacySessions( + await Promise.all((stored.sessions ?? []).map(async (session): Promise => { + const normalizedSession: SessionRecord = { + ...session, + messages: (session.messages ?? []).map(normalizeChatMessageRecord), + branchOrigin: normalizeSessionBranchOrigin(session.branchOrigin), + runs: normalizeSessionRunRecords(session.runs), + tooling: normalizeSessionToolingSelection(session.tooling), + approvalSettings: normalizeSessionApprovalSettings(session.approvalSettings), + ...normalizePendingApprovalState({ + pendingApproval: session.pendingApproval, + pendingApprovalQueue: session.pendingApprovalQueue, + }), + }; + if (!isScratchpadProject(normalizedSession.projectId)) { + return normalizedSession; + } + + const cwd = normalizedSession.cwd ?? getScratchpadSessionPath(normalizedSession.id); + await mkdir(cwd, { recursive: true }); + return { + ...normalizedSession, + cwd, + }; + })), + workflows, + ); + const settings = normalizeWorkspaceSettings(stored.settings); - - const deletedBuiltinPatternIds = stored.deletedBuiltinPatternIds ?? []; - const workspace: WorkspaceState = { ...stored, - patterns: mergePatterns(stored.patterns ?? [], deletedBuiltinPatternIds).map((pattern) => ({ - ...pattern, - approvalPolicy: applyDefaultToolApprovalPolicy(pattern.approvalPolicy), - graph: resolvePatternGraph(pattern), - })), - workflows: (stored.workflows ?? []).map(normalizeWorkflowDefinition), + workflows, workflowTemplates: mergeWorkflowTemplates(stored.workflowTemplates ?? []), projects, sessions, settings, - deletedBuiltinPatternIds, selectedProjectId: projects.some((project) => project.id === stored.selectedProjectId) ? stored.selectedProjectId : projects[0]?.id, + selectedWorkflowId: workflows.some((workflow) => workflow.id === stored.selectedWorkflowId) + ? stored.selectedWorkflowId + : workflows[0]?.id, lastUpdatedAt: stored.lastUpdatedAt ?? nowIso(), }; diff --git a/src/main/sidecar/sidecarProcess.ts b/src/main/sidecar/sidecarProcess.ts index 05917d3..168cd9e 100644 --- a/src/main/sidecar/sidecarProcess.ts +++ b/src/main/sidecar/sidecarProcess.ts @@ -13,7 +13,6 @@ import type { UserInputRequestedEvent, McpOauthRequiredEvent, ExitPlanModeRequestedEvent, - ValidatePatternCommand, ValidateWorkflowCommand, RunTurnCommand, CopilotSessionListFilter, @@ -41,12 +40,6 @@ type PendingCommand = resolve: (capabilities: SidecarCapabilities) => void; reject: (error: Error) => void; }) - | ({ - processId: number; - kind: 'validate-pattern'; - resolve: (issues: ValidatePatternCommand['pattern'] extends never ? never : unknown) => void; - reject: (error: Error) => void; - }) | ({ processId: number; kind: 'validate-workflow'; @@ -126,14 +119,6 @@ export class SidecarClient { return command; } - async validatePattern(pattern: ValidatePatternCommand['pattern']): Promise { - return this.dispatch({ - type: 'validate-pattern', - requestId: `validate-${Date.now()}`, - pattern, - }); - } - async validateWorkflow( workflow: ValidateWorkflowCommand['workflow'], workflowLibrary?: ValidateWorkflowCommand['workflowLibrary'], @@ -329,13 +314,6 @@ export class SidecarClient { onTurnScopedEvent: onTurnScopedEvent ?? (() => undefined), errored: false, }); - } else if (command.type === 'validate-pattern') { - this.pending.set(command.requestId, { - processId: state.id, - kind: 'validate-pattern', - resolve: resolve as (issues: unknown) => void, - reject, - }); } else if (command.type === 'validate-workflow') { this.pending.set(command.requestId, { processId: state.id, @@ -433,12 +411,6 @@ export class SidecarClient { this.pending.delete(event.requestId); } return; - case 'pattern-validation': - if (pending.kind === 'validate-pattern') { - pending.resolve(event.issues); - this.pending.delete(event.requestId); - } - return; case 'workflow-validation': if (pending.kind === 'validate-workflow') { pending.resolve(event.issues); diff --git a/src/preload/index.ts b/src/preload/index.ts index b49f96e..fb480b8 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -23,9 +23,6 @@ const api: ElectronApi = { ipcRenderer.invoke(ipcChannels.resolveProjectDiscoveredTooling, input), setProjectAgentProfileEnabled: (input) => ipcRenderer.invoke(ipcChannels.setProjectAgentProfileEnabled, input), - savePattern: (input) => ipcRenderer.invoke(ipcChannels.savePattern, input), - deletePattern: (patternId) => ipcRenderer.invoke(ipcChannels.deletePattern, patternId), - setPatternFavorite: (input) => ipcRenderer.invoke(ipcChannels.setPatternFavorite, input), saveWorkflow: (input) => ipcRenderer.invoke(ipcChannels.saveWorkflow, input), saveWorkflowTemplate: (input) => ipcRenderer.invoke(ipcChannels.saveWorkflowTemplate, input), deleteWorkflow: (workflowId) => ipcRenderer.invoke(ipcChannels.deleteWorkflow, workflowId), @@ -33,7 +30,6 @@ const api: ElectronApi = { createWorkflowFromTemplate: (input) => ipcRenderer.invoke(ipcChannels.createWorkflowFromTemplate, input), exportWorkflow: (input) => ipcRenderer.invoke(ipcChannels.exportWorkflow, input), importWorkflow: (input) => ipcRenderer.invoke(ipcChannels.importWorkflow, input), - upgradePatternToWorkflow: (input) => ipcRenderer.invoke(ipcChannels.upgradePatternToWorkflow, input), createWorkflowSession: (input) => ipcRenderer.invoke(ipcChannels.createWorkflowSession, input), setTheme: (theme) => ipcRenderer.invoke(ipcChannels.setTheme, theme), setTerminalHeight: (input) => ipcRenderer.invoke(ipcChannels.setTerminalHeight, input), @@ -94,7 +90,6 @@ const api: ElectronApi = { switchProjectGitBranch: (input) => ipcRenderer.invoke(ipcChannels.switchProjectGitBranch, input), deleteProjectGitBranch: (input) => ipcRenderer.invoke(ipcChannels.deleteProjectGitBranch, input), selectProject: (projectId) => ipcRenderer.invoke(ipcChannels.selectProject, projectId), - selectPattern: (patternId) => ipcRenderer.invoke(ipcChannels.selectPattern, patternId), selectSession: (sessionId) => ipcRenderer.invoke(ipcChannels.selectSession, sessionId), openAppDataFolder: () => ipcRenderer.invoke(ipcChannels.openAppDataFolder), resetLocalWorkspace: () => ipcRenderer.invoke(ipcChannels.resetLocalWorkspace), diff --git a/src/renderer/components/chat/InlinePills.tsx b/src/renderer/components/chat/InlinePills.tsx index d927ebf..6b3f233 100644 --- a/src/renderer/components/chat/InlinePills.tsx +++ b/src/renderer/components/chat/InlinePills.tsx @@ -556,7 +556,7 @@ export function InlineApprovalPill({ {open && !disabled && (
- {/* Header: session override / pattern defaults */} + {/* Header: session override / workflow defaults */}
void; @@ -29,10 +29,10 @@ export function WorkspaceAgentEditor({ onSave: () => Promise; onDelete?: () => Promise; availableModels: ReadonlyArray; - patterns: PatternDefinition[]; + workflows: WorkflowDefinition[]; }) { const validationError = validateWorkspaceAgent(agent); - const usages = findWorkspaceAgentUsages(agent.id, patterns); + const usages = findWorkspaceAgentUsages(agent.id, workflows); return ( (
- {usage.patternName} + {usage.workflowName}
))}

- Referenced by {usages.length} pattern{usages.length === 1 ? '' : 's'}. - Changes to this agent will affect all linked patterns. -

- - )} + Referenced by {usages.length} workflow{usages.length === 1 ? '' : 's'}. + Changes to this agent will affect all linked workflows. +

+ + )} ); } diff --git a/src/shared/contracts/channels.ts b/src/shared/contracts/channels.ts index b78adf8..1be4e4e 100644 --- a/src/shared/contracts/channels.ts +++ b/src/shared/contracts/channels.ts @@ -12,9 +12,6 @@ export const ipcChannels = { rescanProjectCustomization: 'project:rescan-customization', resolveProjectDiscoveredTooling: 'project:resolve-discovered-tooling', setProjectAgentProfileEnabled: 'project:set-agent-profile-enabled', - savePattern: 'patterns:save', - deletePattern: 'patterns:delete', - setPatternFavorite: 'patterns:set-favorite', saveWorkflow: 'workflows:save', saveWorkflowTemplate: 'workflows:save-template', deleteWorkflow: 'workflows:delete', @@ -22,7 +19,6 @@ export const ipcChannels = { createWorkflowFromTemplate: 'workflows:create-from-template', exportWorkflow: 'workflows:export', importWorkflow: 'workflows:import', - upgradePatternToWorkflow: 'workflows:upgrade-pattern', createWorkflowSession: 'workflows:create-session', setTheme: 'settings:set-theme', setTerminalHeight: 'settings:set-terminal-height', @@ -77,7 +73,6 @@ export const ipcChannels = { switchProjectGitBranch: 'git:switch-branch', deleteProjectGitBranch: 'git:delete-branch', selectProject: 'selection:project', - selectPattern: 'selection:pattern', selectSession: 'selection:session', openAppDataFolder: 'troubleshooting:open-app-data-folder', resetLocalWorkspace: 'troubleshooting:reset-local-workspace', diff --git a/src/shared/contracts/ipc.ts b/src/shared/contracts/ipc.ts index cf745db..6e3bd83 100644 --- a/src/shared/contracts/ipc.ts +++ b/src/shared/contracts/ipc.ts @@ -1,9 +1,8 @@ import type { ApprovalDecision } from '@shared/domain/approval'; import type { SidecarCapabilities, InteractionMode, MessageMode, QuotaSnapshot } from '@shared/contracts/sidecar'; -import type { PatternDefinition, ReasoningEffort } from '@shared/domain/pattern'; import type { WorkflowExportFormat, WorkflowExportResult } from '@shared/domain/workflowSerialization'; import type { WorkflowTemplateCategory } from '@shared/domain/workflowTemplate'; -import type { WorkflowDefinition, WorkflowReference } from '@shared/domain/workflow'; +import type { ReasoningEffort, WorkflowDefinition, WorkflowReference } from '@shared/domain/workflow'; import type { ProjectGitBranchSummary, ProjectGitCommitMessageSuggestion, @@ -27,18 +26,11 @@ import type { ProjectPromptInvocation } from '@shared/domain/projectCustomizatio import type { WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent'; export interface CreateSessionInput { - projectId: string; - patternId: string; -} - -export interface CreateWorkflowSessionInput { projectId: string; workflowId: string; } -export interface SavePatternInput { - pattern: PatternDefinition; -} +export type CreateWorkflowSessionInput = CreateSessionInput; export interface SaveWorkflowInput { workflow: WorkflowDefinition; @@ -76,16 +68,6 @@ export interface ImportWorkflowInput { }; } -export interface UpgradePatternToWorkflowInput { - patternId: string; - options?: { - workflowId?: string; - name?: string; - description?: string; - save?: boolean; - }; -} - export interface ImportWorkflowResult { workflow: WorkflowDefinition; workspace?: WorkspaceState; @@ -165,11 +147,6 @@ export interface SetSessionArchivedInput { isArchived: boolean; } -export interface SetPatternFavoriteInput { - patternId: string; - isFavorite: boolean; -} - export interface SaveMcpServerInput { server: McpServerDefinition; } @@ -331,8 +308,6 @@ export interface ElectronApi { rescanProjectCustomization(input: RescanProjectCustomizationInput): Promise; resolveProjectDiscoveredTooling(input: ResolveProjectDiscoveredToolingInput): Promise; setProjectAgentProfileEnabled(input: SetProjectAgentProfileEnabledInput): Promise; - savePattern(input: SavePatternInput): Promise; - deletePattern(patternId: string): Promise; saveWorkflow(input: SaveWorkflowInput): Promise; saveWorkflowTemplate(input: SaveWorkflowTemplateInput): Promise; deleteWorkflow(workflowId: string): Promise; @@ -340,7 +315,6 @@ export interface ElectronApi { createWorkflowFromTemplate(input: CreateWorkflowFromTemplateInput): Promise; exportWorkflow(input: ExportWorkflowInput): Promise; importWorkflow(input: ImportWorkflowInput): Promise; - upgradePatternToWorkflow(input: UpgradePatternToWorkflowInput): Promise; saveMcpServer(input: SaveMcpServerInput): Promise; deleteMcpServer(serverId: string): Promise; saveLspProfile(input: SaveLspProfileInput): Promise; @@ -371,9 +345,7 @@ export interface ElectronApi { updateSessionModelConfig(input: UpdateSessionModelConfigInput): Promise; querySessions(input: QuerySessionsInput): Promise; selectProject(projectId?: string): Promise; - selectPattern(patternId?: string): Promise; selectSession(sessionId?: string): Promise; - setPatternFavorite(input: SetPatternFavoriteInput): Promise; setTheme(theme: AppearanceTheme): Promise; setTerminalHeight(input: SetTerminalHeightInput): Promise; setNotificationsEnabled(enabled: boolean): Promise; @@ -413,5 +385,5 @@ export interface ElectronApi { export interface RendererSelectionState { selectedProject?: ProjectRecord; - selectedPattern?: PatternDefinition; + selectedWorkflow?: WorkflowDefinition; } diff --git a/src/shared/contracts/sidecar.ts b/src/shared/contracts/sidecar.ts index 3d296a8..26f8aef 100644 --- a/src/shared/contracts/sidecar.ts +++ b/src/shared/contracts/sidecar.ts @@ -1,10 +1,14 @@ -import type { PatternDefinition, PatternValidationIssue, ReasoningEffort } from '@shared/domain/pattern'; import type { ApprovalCheckpointKind, ApprovalDecision } from '@shared/domain/approval'; import type { ChatMessageRecord } from '@shared/domain/session'; import type { RuntimeToolDefinition } from '@shared/domain/tooling'; import type { ChatMessageAttachment } from '@shared/domain/attachment'; import type { ProjectPromptInvocation } from '@shared/domain/projectCustomization'; -import type { WorkflowDefinition, WorkflowValidationIssue } from '@shared/domain/workflow'; +import type { + ReasoningEffort, + WorkflowDefinition, + WorkflowOrchestrationMode, + WorkflowValidationIssue, +} from '@shared/domain/workflow'; export interface SidecarModeCapability { available: boolean; @@ -54,7 +58,7 @@ export interface SidecarModelCapability { export interface SidecarCapabilities { runtime: 'dotnet-maf'; - modes: Record; + modes: Record; models: SidecarModelCapability[]; runtimeTools: RuntimeToolDefinition[]; connection: SidecarConnectionDiagnostics; @@ -65,12 +69,6 @@ export interface DescribeCapabilitiesCommand { requestId: string; } -export interface ValidatePatternCommand { - type: 'validate-pattern'; - requestId: string; - pattern: PatternDefinition; -} - export interface ValidateWorkflowCommand { type: 'validate-workflow'; requestId: string; @@ -96,8 +94,7 @@ export interface RunTurnCommand { mode?: InteractionMode; messageMode?: MessageMode; projectInstructions?: string; - pattern: PatternDefinition; - workflow?: WorkflowDefinition; + workflow: WorkflowDefinition; workflowLibrary?: WorkflowDefinition[]; messages: ChatMessageRecord[]; attachments?: ChatMessageAttachment[]; @@ -156,7 +153,6 @@ export interface CopilotSessionListFilter { export type SidecarCommand = | DescribeCapabilitiesCommand - | ValidatePatternCommand | ValidateWorkflowCommand | RunTurnCommand | CancelTurnCommand @@ -235,12 +231,6 @@ export interface CapabilitiesEvent { capabilities: SidecarCapabilities; } -export interface PatternValidationEvent { - type: 'pattern-validation'; - requestId: string; - issues: PatternValidationIssue[]; -} - export interface WorkflowValidationEvent { type: 'workflow-validation'; requestId: string; @@ -608,7 +598,6 @@ export interface CommandCompleteEvent { export type SidecarEvent = | CapabilitiesEvent - | PatternValidationEvent | WorkflowValidationEvent | TurnDeltaEvent | TurnCompleteEvent diff --git a/src/shared/domain/models.ts b/src/shared/domain/models.ts index 544bdb5..b1caa09 100644 --- a/src/shared/domain/models.ts +++ b/src/shared/domain/models.ts @@ -1,5 +1,5 @@ import type { SidecarModelCapability } from '@shared/contracts/sidecar'; -import type { PatternDefinition, ReasoningEffort } from '@shared/domain/pattern'; +import type { ReasoningEffort, WorkflowDefinition } from '@shared/domain/workflow'; export type ModelProvider = 'openai' | 'anthropic' | 'google'; @@ -270,17 +270,31 @@ export function resolveReasoningEffort( return supported[0]; } -export function normalizePatternModels( - pattern: PatternDefinition, +export function normalizeWorkflowModels( + workflow: WorkflowDefinition, models: ReadonlyArray, -): PatternDefinition { +): WorkflowDefinition { return { - ...pattern, - agents: pattern.agents.map((agent) => { - const model = findModel(agent.model, models); - const reasoningEffort = resolveReasoningEffort(model, agent.reasoningEffort); + ...workflow, + graph: { + ...workflow.graph, + nodes: workflow.graph.nodes.map((node) => { + if (node.kind !== 'agent' || node.config.kind !== 'agent') { + return node; + } - return reasoningEffort === agent.reasoningEffort ? agent : { ...agent, reasoningEffort }; - }), + const model = findModel(node.config.model, models); + const reasoningEffort = resolveReasoningEffort(model, node.config.reasoningEffort); + return reasoningEffort === node.config.reasoningEffort + ? node + : { + ...node, + config: { + ...node.config, + reasoningEffort, + }, + }; + }), + }, }; } diff --git a/src/shared/domain/runTimeline.ts b/src/shared/domain/runTimeline.ts index b8cbe20..2dff5e7 100644 --- a/src/shared/domain/runTimeline.ts +++ b/src/shared/domain/runTimeline.ts @@ -4,7 +4,6 @@ import type { PendingApprovalRecord, } from '@shared/domain/approval'; import type { ToolCallFileChangePreview } from '@shared/contracts/sidecar'; -import type { PatternDefinition, ReasoningEffort } from '@shared/domain/pattern'; import type { ProjectGitBaselineFile, ProjectGitChangeSummary, @@ -17,7 +16,13 @@ import type { ProjectGitWorkingTreeSnapshot, ProjectRecord, } from '@shared/domain/project'; -import type { WorkflowDefinition } from '@shared/domain/workflow'; +import type { + AgentNodeConfig, + ReasoningEffort, + WorkflowDefinition, + WorkflowOrchestrationMode, +} from '@shared/domain/workflow'; +import { resolveWorkflowAgents } from '@shared/domain/workflow'; import { createId } from '@shared/utils/ids'; export type SessionRunStatus = 'running' | 'completed' | 'cancelled' | 'error'; @@ -74,11 +79,9 @@ export interface SessionRunRecord { projectPath: string; workingDirectory?: string; workspaceKind: SessionRunWorkspaceKind; - patternId: string; - patternName: string; - patternMode: PatternDefinition['mode']; - workflowId?: string; - workflowName?: string; + workflowId: string; + workflowName: string; + workflowMode: WorkflowOrchestrationMode; triggerMessageId: string; startedAt: string; completedAt?: string; @@ -90,13 +93,18 @@ export interface SessionRunRecord { postRunGitSummary?: ProjectGitRunChangeSummary; } +export type SessionRunWorkflowInput = + | WorkflowDefinition + | (Pick & { + agents: Pick[]; + }); + export interface CreateSessionRunRecordInput { requestId: string; project: Pick; workingDirectory?: string; workspaceKind: SessionRunWorkspaceKind; - pattern: Pick; - workflow?: Pick; + workflow: SessionRunWorkflowInput; triggerMessageId: string; startedAt: string; preRunGitSnapshot?: ProjectGitWorkingTreeSnapshot; @@ -603,7 +611,23 @@ function settleOpenMessageEvents( }; } +function resolveSessionRunWorkflowAgents( + workflow: SessionRunWorkflowInput, +): ReadonlyArray> { + if ('graph' in workflow) { + return resolveWorkflowAgents(workflow).map((agent) => ({ + id: agent.id, + name: agent.name, + model: agent.model, + reasoningEffort: agent.reasoningEffort, + })); + } + + return workflow.agents; +} + export function createSessionRunRecord(input: CreateSessionRunRecordInput): SessionRunRecord { + const agents = resolveSessionRunWorkflowAgents(input.workflow); return { id: createId('run'), requestId: input.requestId, @@ -611,11 +635,9 @@ export function createSessionRunRecord(input: CreateSessionRunRecordInput): Sess projectPath: input.project.path, workingDirectory: normalizeOptionalString(input.workingDirectory), workspaceKind: input.workspaceKind, - patternId: input.pattern.id, - patternName: input.pattern.name, - patternMode: input.pattern.mode, - workflowId: normalizeOptionalString(input.workflow?.id), - workflowName: normalizeOptionalString(input.workflow?.name), + workflowId: input.workflow.id, + workflowName: input.workflow.name, + workflowMode: input.workflow.settings.orchestrationMode ?? 'single', triggerMessageId: input.triggerMessageId, startedAt: input.startedAt, status: 'running', @@ -623,7 +645,7 @@ export function createSessionRunRecord(input: CreateSessionRunRecordInput): Sess preRunGitSnapshot: normalizeWorkingTreeSnapshot(input.preRunGitSnapshot), preRunGitBaselineFiles: normalizeGitBaselineFiles(input.preRunGitBaselineFiles), postRunGitSummary: undefined, - agents: input.pattern.agents + agents: agents .map((agent): RunTimelineAgentRecord => ({ agentId: agent.id, agentName: agent.name, @@ -659,13 +681,11 @@ export function normalizeSessionRunRecords( const projectId = normalizeOptionalString(run.projectId); const projectPath = normalizeOptionalString(run.projectPath); const workingDirectory = normalizeOptionalString(run.workingDirectory); - const patternId = normalizeOptionalString(run.patternId); - const patternName = normalizeOptionalString(run.patternName); const workflowId = normalizeOptionalString(run.workflowId); const workflowName = normalizeOptionalString(run.workflowName); const triggerMessageId = normalizeOptionalString(run.triggerMessageId); const startedAt = normalizeOptionalString(run.startedAt); - if (!id || !requestId || !projectId || !projectPath || !patternId || !patternName || !triggerMessageId || !startedAt) { + if (!id || !requestId || !projectId || !projectPath || !workflowId || !workflowName || !triggerMessageId || !startedAt) { return []; } @@ -677,11 +697,14 @@ export function normalizeSessionRunRecords( projectPath, workingDirectory, workspaceKind: run.workspaceKind === 'scratchpad' ? 'scratchpad' : 'project', - patternId, - patternName, - patternMode: run.patternMode, workflowId, workflowName, + workflowMode: run.workflowMode === 'concurrent' + || run.workflowMode === 'handoff' + || run.workflowMode === 'group-chat' + || run.workflowMode === 'single' + ? run.workflowMode + : 'sequential', triggerMessageId, startedAt, completedAt: normalizeOptionalString(run.completedAt), diff --git a/src/shared/domain/session.ts b/src/shared/domain/session.ts index 2bd8c9a..dde0f51 100644 --- a/src/shared/domain/session.ts +++ b/src/shared/domain/session.ts @@ -1,25 +1,32 @@ -import { buildSessionTitle, type PatternDefinition, type ReasoningEffort } from '@shared/domain/pattern'; -import { - createSessionToolingSelection, - normalizeSessionToolingSelection, - type SessionToolingSelection, -} from '@shared/domain/tooling'; import { normalizeSessionApprovalSettings, resolveEffectiveApprovalPolicy, type PendingApprovalRecord, type SessionApprovalSettings, } from '@shared/domain/approval'; -import type { SessionRunRecord } from '@shared/domain/runTimeline'; -import type { PendingUserInputRecord } from '@shared/domain/userInput'; -import type { PendingPlanReviewRecord } from '@shared/domain/planReview'; -import type { PendingMcpAuthRecord } from '@shared/domain/mcpAuth'; import type { ChatMessageAttachment } from '@shared/domain/attachment'; -import type { InteractionMode } from '@shared/contracts/sidecar'; +import type { PendingMcpAuthRecord } from '@shared/domain/mcpAuth'; +import type { PendingPlanReviewRecord } from '@shared/domain/planReview'; import { normalizeProjectPromptInvocation, type ProjectPromptInvocation, } from '@shared/domain/projectCustomization'; +import type { SessionRunRecord } from '@shared/domain/runTimeline'; +import { + createSessionToolingSelection, + normalizeSessionToolingSelection, + type SessionToolingSelection, +} from '@shared/domain/tooling'; +import type { PendingUserInputRecord } from '@shared/domain/userInput'; +import { + buildWorkflowExecutionDefinition, + resolveWorkflowAgentNodes, + type ReasoningEffort, + type WorkflowDefinition, + type WorkflowResolutionOptions, +} from '@shared/domain/workflow'; +import type { InteractionMode } from '@shared/contracts/sidecar'; +import { buildMarkdownExcerpt } from '@shared/utils/markdownText'; export type ChatRole = 'system' | 'user' | 'assistant'; export type ChatMessageKind = 'response' | 'thinking'; @@ -56,8 +63,7 @@ export interface SessionBranchOrigin { export interface SessionRecord { id: string; projectId: string; - patternId: string; - workflowId?: string; + workflowId: string; title: string; titleSource?: SessionTitleSource; createdAt: string; @@ -120,20 +126,26 @@ export function normalizeSessionBranchOrigin( export function resolveSessionTitle( session: Pick, - pattern: PatternDefinition, + workflow: Pick, messages: ChatMessageRecord[], ): string { if (session.titleSource === 'manual') { return session.title; } - return buildSessionTitle(pattern, messages); + const firstUserMessage = messages.find((message) => message.role === 'user'); + if (!firstUserMessage) { + return workflow.name; + } + + return buildMarkdownExcerpt(firstUserMessage.content, 48) ?? workflow.name; } export function createSessionModelConfig( - pattern: PatternDefinition, + workflow: WorkflowDefinition, + options?: WorkflowResolutionOptions, ): SessionModelConfig | undefined { - const primaryAgent = pattern.agents[0]; + const primaryAgent = buildWorkflowExecutionDefinition(workflow, options).agents[0]; if (!primaryAgent) { return undefined; } @@ -158,9 +170,9 @@ export function resolveSessionApprovalSettings( export function resolveSessionModelConfig( session: SessionRecord, - pattern: PatternDefinition, + workflow: WorkflowDefinition, ): SessionModelConfig | undefined { - const defaults = createSessionModelConfig(pattern); + const defaults = createSessionModelConfig(workflow); if (!defaults) { return undefined; } @@ -187,38 +199,56 @@ export function normalizeChatMessageRecord(message: ChatMessageRecord): ChatMess } export function applySessionModelConfig( - pattern: PatternDefinition, + workflow: WorkflowDefinition, session: SessionRecord, -): PatternDefinition { - const config = resolveSessionModelConfig(session, pattern); - const primaryAgent = pattern.agents[0]; - if (!config || !primaryAgent) { - return pattern; +): WorkflowDefinition { + const config = resolveSessionModelConfig(session, workflow); + if (!config) { + return workflow; } - return { - ...pattern, - agents: [ - { - ...primaryAgent, + let applied = false; + const nodes = workflow.graph.nodes.map((node, index) => { + if (applied || node.kind !== 'agent' || node.config.kind !== 'agent') { + return node; + } + + applied = true; + return { + ...node, + config: { + ...node.config, model: config.model, reasoningEffort: config.reasoningEffort, }, - ...pattern.agents.slice(1), - ], - }; + }; + }); + + return applied + ? { + ...workflow, + graph: { + ...workflow.graph, + nodes, + }, + } + : workflow; } export function applySessionApprovalSettings( - pattern: PatternDefinition, + workflow: WorkflowDefinition, session: Pick, -): PatternDefinition { +): WorkflowDefinition { if (session.approvalSettings === undefined) { - return pattern; + return workflow; } + const execution = buildWorkflowExecutionDefinition(workflow); return { - ...pattern, - approvalPolicy: resolveEffectiveApprovalPolicy(pattern.approvalPolicy, session.approvalSettings), + ...workflow, + settings: { + ...workflow.settings, + approvalPolicy: resolveEffectiveApprovalPolicy(execution.approvalPolicy, session.approvalSettings), + }, }; } diff --git a/src/shared/domain/sessionLibrary.ts b/src/shared/domain/sessionLibrary.ts index 508c6eb..bf1ddd4 100644 --- a/src/shared/domain/sessionLibrary.ts +++ b/src/shared/domain/sessionLibrary.ts @@ -1,4 +1,3 @@ -import type { PatternDefinition } from '@shared/domain/pattern'; import { isScratchpadProject, type ProjectRecord } from '@shared/domain/project'; import type { ChatMessageAttachment } from '@shared/domain/attachment'; import { @@ -14,16 +13,16 @@ import { type SessionStatus, } from '@shared/domain/session'; import type { WorkspaceState } from '@shared/domain/workspace'; -import { buildWorkflowExecutionPattern } from '@shared/domain/workflow'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; -export type SessionQueryMatchField = 'title' | 'message' | 'project' | 'pattern'; +export type SessionQueryMatchField = 'title' | 'message' | 'project' | 'workflow'; export type SessionWorkspaceKind = 'project' | 'scratchpad'; export interface QuerySessionsInput { searchText?: string; statuses?: SessionStatus[]; projectIds?: string[]; - patternIds?: string[]; + workflowIds?: string[]; workspaceKinds?: SessionWorkspaceKind[]; includeArchived?: boolean; onlyPinned?: boolean; @@ -38,17 +37,17 @@ export interface SessionQueryResult { const fieldWeights: Record = { title: 12, project: 8, - pattern: 7, + workflow: 7, message: 4, }; -const orderedMatchFields: SessionQueryMatchField[] = ['title', 'message', 'project', 'pattern']; +const orderedMatchFields: SessionQueryMatchField[] = ['title', 'message', 'project', 'workflow']; interface SessionSearchFields { title: string; message: string; project: string; - pattern: string; + workflow: string; } function normalizeSearchText(value: string): string { @@ -68,18 +67,21 @@ function tokenizeSearchText(value?: string): string[] { function buildSearchFields( session: SessionRecord, project?: ProjectRecord, - pattern?: PatternDefinition, + workflow?: WorkflowDefinition, ): SessionSearchFields { return { title: normalizeSearchText(session.title), message: normalizeSearchText(session.messages.map((message) => message.content).join('\n')), project: normalizeSearchText([project?.name, project?.path].filter(Boolean).join('\n')), - pattern: normalizeSearchText( + workflow: normalizeSearchText( [ - pattern?.name, - pattern?.description, - pattern?.mode, - ...(pattern?.agents.flatMap((agent) => [agent.name, agent.description]) ?? []), + workflow?.name, + workflow?.description, + workflow?.settings.orchestrationMode, + ...(workflow?.graph.nodes.flatMap((node) => + node.kind === 'agent' && node.config.kind === 'agent' + ? [node.config.name, node.config.description] + : []) ?? []), ] .filter(Boolean) .join('\n'), @@ -146,7 +148,7 @@ function matchesFilters( return false; } - if (input.patternIds && input.patternIds.length > 0 && !input.patternIds.includes(session.patternId)) { + if (input.workflowIds && input.workflowIds.length > 0 && !input.workflowIds.includes(session.workflowId)) { return false; } @@ -280,7 +282,7 @@ export function duplicateSessionRecord( export function branchSessionRecord( session: SessionRecord, - pattern: PatternDefinition, + workflow: WorkflowDefinition, sessionId: string, messageId: string, branchedAt: string, @@ -299,7 +301,7 @@ export function branchSessionRecord( return { ...createDerivedSessionRecord(session, sessionId, branchedAt), - title: resolveSessionTitle(session, pattern, branchedMessages), + title: resolveSessionTitle(session, workflow, branchedMessages), messages: branchedMessages, branchOrigin: createBranchOrigin(session, messageId, sourceMessageIndex, branchedAt, 'branch'), }; @@ -338,7 +340,7 @@ export function setSessionMessagePinnedRecord( export function regenerateSessionRecord( session: SessionRecord, - pattern: PatternDefinition, + workflow: WorkflowDefinition, sessionId: string, messageId: string, regeneratedAt: string, @@ -373,7 +375,7 @@ export function regenerateSessionRecord( return { ...createDerivedSessionRecord(session, sessionId, regeneratedAt), - title: resolveSessionTitle(session, pattern, regeneratedMessages), + title: resolveSessionTitle(session, workflow, regeneratedMessages), messages: regeneratedMessages, branchOrigin: createBranchOrigin(session, messageId, sourceMessageIndex, regeneratedAt, 'regenerate'), }; @@ -381,7 +383,7 @@ export function regenerateSessionRecord( export function editAndResendSessionRecord( session: SessionRecord, - pattern: PatternDefinition, + workflow: WorkflowDefinition, sessionId: string, messageId: string, content: string, @@ -410,7 +412,7 @@ export function editAndResendSessionRecord( return { ...createDerivedSessionRecord(session, sessionId, editedAt), - title: resolveSessionTitle(session, pattern, editedMessages), + title: resolveSessionTitle(session, workflow, editedMessages), messages: editedMessages, branchOrigin: createBranchOrigin(session, messageId, sourceMessageIndex, editedAt, 'edit-and-resend'), }; @@ -456,7 +458,6 @@ export function listPinnedMessages(workspace: WorkspaceState): PinnedMessageHit[ export function querySessions(workspace: WorkspaceState, input: QuerySessionsInput): SessionQueryResult[] { const projectsById = new Map(workspace.projects.map((project) => [project.id, project])); - const patternsById = new Map(workspace.patterns.map((pattern) => [pattern.id, pattern])); const workflowsById = new Map(workspace.workflows.map((workflow) => [workflow.id, workflow])); const searchTokens = tokenizeSearchText(input.searchText); @@ -471,13 +472,7 @@ export function querySessions(workspace: WorkspaceState, input: QuerySessionsInp buildSearchFields( session, projectsById.get(session.projectId), - patternsById.get(session.patternId) - ?? (session.workflowId - ? (() => { - const workflow = workflowsById.get(session.workflowId); - return workflow ? buildWorkflowExecutionPattern(workflow) : undefined; - })() - : undefined), + workflowsById.get(session.workflowId), ), searchTokens, ); diff --git a/src/shared/domain/workflow.ts b/src/shared/domain/workflow.ts index 695d28d..fdf61c7 100644 --- a/src/shared/domain/workflow.ts +++ b/src/shared/domain/workflow.ts @@ -1,10 +1,23 @@ +import type { PatternAgentCopilotConfig } from '@shared/contracts/sidecar'; import type { ApprovalPolicy } from '@shared/domain/approval'; -import { - syncPatternGraph, - type PatternDefinition, - type PatternGraph, - type PatternAgentDefinition, -} from '@shared/domain/pattern'; + +export type ReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh'; +export type WorkflowOrchestrationMode = 'single' | 'sequential' | 'concurrent' | 'handoff' | 'group-chat'; + +export interface WorkflowAgentOverrides { + name?: string; + description?: string; + instructions?: string; + model?: string; + reasoningEffort?: ReasoningEffort; +} + +export const reasoningEffortOptions: ReadonlyArray<{ value: ReasoningEffort; label: string }> = [ + { value: 'low', label: 'Low' }, + { value: 'medium', label: 'Medium' }, + { value: 'high', label: 'High' }, + { value: 'xhigh', label: 'Very High' }, +]; export type WorkflowNodeKind = | 'start' @@ -40,6 +53,7 @@ export interface WorkflowStateScope { export interface WorkflowSettings { checkpointing: WorkflowCheckpointSettings; executionMode: WorkflowExecutionMode; + orchestrationMode?: WorkflowOrchestrationMode; maxIterations?: number; approvalPolicy?: ApprovalPolicy; stateScopes?: WorkflowStateScope[]; @@ -56,8 +70,17 @@ export interface EndNodeConfig { outputType?: string; } -export interface AgentNodeConfig extends PatternAgentDefinition { +export interface AgentNodeConfig { kind: 'agent'; + id: string; + name: string; + description: string; + instructions: string; + model: string; + reasoningEffort?: ReasoningEffort; + copilot?: PatternAgentCopilotConfig; + workspaceAgentId?: string; + overrides?: WorkflowAgentOverrides; } export interface InvokeFunctionConfig { @@ -163,6 +186,16 @@ export interface WorkflowResolutionOptions { resolveWorkflow?: (workflowId: string) => WorkflowDefinition | undefined; } +export interface WorkflowExecutionDefinition { + id: string; + name: string; + description: string; + orchestrationMode: WorkflowOrchestrationMode; + maxIterations: number; + approvalPolicy?: ApprovalPolicy; + agents: AgentNodeConfig[]; +} + const executableNodeKinds = new Set([ 'start', 'end', @@ -177,6 +210,25 @@ function normalizeOptionalString(value?: string): string | undefined { return trimmed ? trimmed : undefined; } +function normalizeWorkflowOrchestrationMode( + mode?: WorkflowOrchestrationMode, +): WorkflowOrchestrationMode | undefined { + switch (mode) { + case 'single': + case 'sequential': + case 'concurrent': + case 'handoff': + case 'group-chat': + return mode; + default: + return undefined; + } +} + +export function isReasoningEffort(value: string | undefined): value is ReasoningEffort { + return reasoningEffortOptions.some((option) => option.value === value); +} + function normalizePosition(position?: Partial): WorkflowPosition { return { x: typeof position?.x === 'number' && Number.isFinite(position.x) ? position.x : 0, @@ -311,6 +363,7 @@ export function normalizeWorkflowDefinition(workflow: WorkflowDefinition): Workf enabled: workflow.settings?.checkpointing?.enabled ?? false, }, executionMode: workflow.settings?.executionMode === 'lockstep' ? 'lockstep' : 'off-thread', + orchestrationMode: normalizeWorkflowOrchestrationMode(workflow.settings?.orchestrationMode), maxIterations: typeof workflow.settings?.maxIterations === 'number' && workflow.settings.maxIterations > 0 ? Math.round(workflow.settings.maxIterations) @@ -346,13 +399,14 @@ export function resolveWorkflowAgentNodes(workflow: WorkflowDefinition): Workflo }); } -export function resolveWorkflowAgents(workflow: WorkflowDefinition): PatternAgentDefinition[] { +export function resolveWorkflowAgents(workflow: WorkflowDefinition): AgentNodeConfig[] { return resolveWorkflowAgentNodes(workflow).flatMap((node) => { if (node.config.kind !== 'agent') { return []; } return [{ + kind: 'agent', id: node.config.id || node.id, name: node.config.name, description: node.config.description, @@ -410,7 +464,7 @@ function resolveWorkflowExecutionAgents( options?: WorkflowResolutionOptions, visitedReferencedWorkflowIds = new Set([workflow.id]), visitedInlineWorkflows = new Set(), -): PatternAgentDefinition[] { +): AgentNodeConfig[] { const agents = [...resolveWorkflowAgents(workflow)]; for (const node of workflow.graph.nodes) { @@ -448,10 +502,15 @@ function resolveWorkflowExecutionAgents( return agents; } -function inferWorkflowPatternMode( +export function inferWorkflowOrchestrationMode( workflow: WorkflowDefinition, options?: WorkflowResolutionOptions, -): PatternDefinition['mode'] { +): WorkflowOrchestrationMode { + const configuredMode = normalizeWorkflowOrchestrationMode(workflow.settings?.orchestrationMode); + if (configuredMode) { + return configuredMode; + } + const hasFanEdges = hasWorkflowExecutionFanEdges(workflow, options); const agentCount = resolveWorkflowExecutionAgents(workflow, options).length; if (hasFanEdges) { @@ -461,30 +520,366 @@ function inferWorkflowPatternMode( return agentCount <= 1 ? 'single' : 'sequential'; } -export function buildWorkflowExecutionPattern( +export function buildWorkflowExecutionDefinition( workflow: WorkflowDefinition, options?: WorkflowResolutionOptions, -): PatternDefinition { +): WorkflowExecutionDefinition { const agents = resolveWorkflowExecutionAgents(workflow, options); - const pattern: PatternDefinition = { + + return { id: workflow.id, name: workflow.name, description: workflow.description, - mode: inferWorkflowPatternMode(workflow, options), - availability: 'available', + orchestrationMode: inferWorkflowOrchestrationMode(workflow, options), maxIterations: workflow.settings.maxIterations ?? 5, approvalPolicy: workflow.settings.approvalPolicy, agents, - createdAt: workflow.createdAt, - updatedAt: workflow.updatedAt, }; +} +const builtinWorkflowModels = { + claude: 'claude-opus-4.5', + gpt54: 'gpt-5.4', + gpt53: 'gpt-5.3-codex', +} as const; + +function createStartNode(x: number, y: number): WorkflowNode { + return { id: 'start', kind: 'start', label: 'Start', position: { x, y }, config: { kind: 'start' } }; +} + +function createEndNode(x: number, y: number): WorkflowNode { + return { id: 'end', kind: 'end', label: 'End', position: { x, y }, config: { kind: 'end' } }; +} + +function createAgentNode( + id: string, + label: string, + description: string, + instructions: string, + model: string, + reasoningEffort: ReasoningEffort | undefined, + x: number, + y: number, + order: number, +): WorkflowNode { return { - ...pattern, - graph: syncPatternGraph(pattern).graph as PatternGraph, + id, + kind: 'agent', + label, + position: { x, y }, + order, + config: { + kind: 'agent', + id, + name: label, + description, + instructions, + model, + reasoningEffort, + }, }; } +function createWorkflowEdge( + id: string, + source: string, + target: string, + kind: WorkflowEdgeKind = 'direct', + overrides?: Partial>, +): WorkflowEdge { + return { + id, + source, + target, + kind, + ...overrides, + }; +} + +function createBuiltinWorkflow( + workflow: Omit, + timestamp: string, +): WorkflowDefinition { + return normalizeWorkflowDefinition({ + ...workflow, + createdAt: timestamp, + updatedAt: timestamp, + }); +} + +export function createBuiltinWorkflows(timestamp: string): WorkflowDefinition[] { + return [ + createBuiltinWorkflow({ + id: 'workflow-single-chat', + name: '1-on-1 Copilot Chat', + description: 'Direct human-agent conversation for a selected project.', + graph: { + nodes: [ + createStartNode(0, 0), + createAgentNode( + 'agent-single-primary', + 'Primary Agent', + 'General-purpose project assistant.', + 'You are a helpful coding assistant working inside the selected project.', + builtinWorkflowModels.gpt54, + 'high', + 220, + 0, + 0, + ), + createEndNode(440, 0), + ], + edges: [ + createWorkflowEdge('edge-start-to-agent-single-primary', 'start', 'agent-single-primary'), + createWorkflowEdge('edge-agent-single-primary-to-end', 'agent-single-primary', 'end'), + ], + }, + settings: { + checkpointing: { enabled: false }, + executionMode: 'off-thread', + orchestrationMode: 'single', + maxIterations: 1, + }, + }, timestamp), + createBuiltinWorkflow({ + id: 'workflow-sequential-review', + name: 'Sequential Trio Review', + description: 'Agents execute in order, each seeing the full conversation and appending to a shared transcript.', + graph: { + nodes: [ + createStartNode(0, 0), + createAgentNode( + 'agent-sequential-analyst', + 'Analyst', + 'Breaks the task down and captures risks.', + 'Analyze the request, identify constraints, and produce a short working plan.', + builtinWorkflowModels.gpt54, + 'high', + 220, + 0, + 0, + ), + createAgentNode( + 'agent-sequential-builder', + 'Builder', + 'Translates the plan into a practical implementation.', + 'Use the prior context to propose a concrete implementation.', + builtinWorkflowModels.gpt53, + 'medium', + 440, + 0, + 1, + ), + createAgentNode( + 'agent-sequential-reviewer', + 'Reviewer', + 'Checks the proposal for gaps and edge cases.', + 'Review the previous answer, tighten it, and call out any missing edge cases.', + builtinWorkflowModels.claude, + 'medium', + 660, + 0, + 2, + ), + createEndNode(880, 0), + ], + edges: [ + createWorkflowEdge('edge-start-to-agent-sequential-analyst', 'start', 'agent-sequential-analyst'), + createWorkflowEdge('edge-agent-sequential-analyst-to-agent-sequential-builder', 'agent-sequential-analyst', 'agent-sequential-builder'), + createWorkflowEdge('edge-agent-sequential-builder-to-agent-sequential-reviewer', 'agent-sequential-builder', 'agent-sequential-reviewer'), + createWorkflowEdge('edge-agent-sequential-reviewer-to-end', 'agent-sequential-reviewer', 'end'), + ], + }, + settings: { + checkpointing: { enabled: false }, + executionMode: 'off-thread', + orchestrationMode: 'sequential', + maxIterations: 1, + }, + }, timestamp), + createBuiltinWorkflow({ + id: 'workflow-concurrent-brainstorm', + name: 'Concurrent Brainstorm', + description: 'Agents work independently in parallel and the final conversation aggregates every response.', + graph: { + nodes: [ + createStartNode(0, 120), + createAgentNode( + 'agent-concurrent-architect', + 'Architect', + 'Focuses on architecture and boundaries.', + 'Answer from an architecture-first perspective.', + builtinWorkflowModels.gpt54, + 'high', + 260, + 0, + 0, + ), + createAgentNode( + 'agent-concurrent-product', + 'Product', + 'Focuses on UX and scope.', + 'Answer from a product and UX perspective.', + builtinWorkflowModels.claude, + 'medium', + 260, + 120, + 1, + ), + createAgentNode( + 'agent-concurrent-implementer', + 'Implementer', + 'Focuses on practical delivery.', + 'Answer from an implementation and testing perspective.', + builtinWorkflowModels.gpt53, + 'medium', + 260, + 240, + 2, + ), + createEndNode(520, 120), + ], + edges: [ + createWorkflowEdge('edge-start-to-agent-concurrent-architect', 'start', 'agent-concurrent-architect', 'fan-out', { fanOutConfig: { strategy: 'broadcast' } }), + createWorkflowEdge('edge-start-to-agent-concurrent-product', 'start', 'agent-concurrent-product', 'fan-out', { fanOutConfig: { strategy: 'broadcast' } }), + createWorkflowEdge('edge-start-to-agent-concurrent-implementer', 'start', 'agent-concurrent-implementer', 'fan-out', { fanOutConfig: { strategy: 'broadcast' } }), + createWorkflowEdge('edge-agent-concurrent-architect-to-end', 'agent-concurrent-architect', 'end', 'fan-in'), + createWorkflowEdge('edge-agent-concurrent-product-to-end', 'agent-concurrent-product', 'end', 'fan-in'), + createWorkflowEdge('edge-agent-concurrent-implementer-to-end', 'agent-concurrent-implementer', 'end', 'fan-in'), + ], + }, + settings: { + checkpointing: { enabled: false }, + executionMode: 'off-thread', + orchestrationMode: 'concurrent', + maxIterations: 1, + }, + }, timestamp), + createBuiltinWorkflow({ + id: 'workflow-handoff-support', + name: 'Handoff Support Flow', + description: 'A triage agent routes work to specialists, and the next user turn continues when more input is needed.', + graph: { + nodes: [ + createStartNode(0, 120), + createAgentNode( + 'agent-handoff-triage', + 'Triage', + 'Routes the request to the right specialist.', + 'You triage requests and must hand them off to the most appropriate specialist. For any substantive task, hand off before inspecting files, calling tools, or drafting the implementation yourself. Do not claim that you delegated unless you actually executed the handoff.', + builtinWorkflowModels.gpt54, + 'medium', + 240, + 120, + 0, + ), + createAgentNode( + 'agent-handoff-ux', + 'UX Specialist', + 'Handles user experience questions.', + 'You focus on navigation, UX, and interaction details. Once triage hands work to you, you own the substantive answer.', + builtinWorkflowModels.claude, + 'medium', + 520, + 0, + 1, + ), + createAgentNode( + 'agent-handoff-runtime', + 'Runtime Specialist', + 'Handles backend and execution details.', + 'You focus on runtime, orchestration, and backend integration details. Once triage hands work to you, you own the substantive answer.', + builtinWorkflowModels.gpt53, + 'medium', + 520, + 240, + 2, + ), + createEndNode(800, 120), + ], + edges: [ + createWorkflowEdge('edge-start-to-agent-handoff-triage', 'start', 'agent-handoff-triage'), + createWorkflowEdge('edge-agent-handoff-triage-to-end', 'agent-handoff-triage', 'end'), + createWorkflowEdge('edge-agent-handoff-triage-to-agent-handoff-ux', 'agent-handoff-triage', 'agent-handoff-ux'), + createWorkflowEdge('edge-agent-handoff-triage-to-agent-handoff-runtime', 'agent-handoff-triage', 'agent-handoff-runtime'), + createWorkflowEdge('edge-agent-handoff-ux-to-agent-handoff-triage', 'agent-handoff-ux', 'agent-handoff-triage', 'direct', { + isLoop: true, + maxIterations: 4, + condition: { type: 'always' }, + }), + createWorkflowEdge('edge-agent-handoff-runtime-to-agent-handoff-triage', 'agent-handoff-runtime', 'agent-handoff-triage', 'direct', { + isLoop: true, + maxIterations: 4, + condition: { type: 'always' }, + }), + createWorkflowEdge('edge-agent-handoff-ux-to-end', 'agent-handoff-ux', 'end'), + createWorkflowEdge('edge-agent-handoff-runtime-to-end', 'agent-handoff-runtime', 'end'), + ], + }, + settings: { + checkpointing: { enabled: true }, + executionMode: 'off-thread', + orchestrationMode: 'handoff', + maxIterations: 4, + }, + }, timestamp), + createBuiltinWorkflow({ + id: 'workflow-group-chat', + name: 'Collaborative Group Chat', + description: 'Agents take turns under a round-robin manager, iteratively refining a shared conversation.', + graph: { + nodes: [ + createStartNode(0, 0), + createAgentNode( + 'agent-group-writer', + 'Writer', + 'Produces candidate answers.', + 'You draft a concise, useful answer for the task. On later turns, refine your earlier draft based on peer feedback rather than restarting.', + builtinWorkflowModels.gpt54, + 'medium', + 240, + 0, + 0, + ), + createAgentNode( + 'agent-group-reviewer', + 'Reviewer', + 'Critiques and refines the answer.', + 'You review the latest draft and offer specific improvements. Focus on critique and refinement instead of restarting the conversation.', + builtinWorkflowModels.claude, + 'medium', + 480, + 0, + 1, + ), + createEndNode(720, 0), + ], + edges: [ + createWorkflowEdge('edge-start-to-agent-group-writer', 'start', 'agent-group-writer'), + createWorkflowEdge('edge-agent-group-writer-to-agent-group-reviewer', 'agent-group-writer', 'agent-group-reviewer', 'direct', { + isLoop: true, + maxIterations: 5, + condition: { type: 'always' }, + }), + createWorkflowEdge('edge-agent-group-reviewer-to-agent-group-writer', 'agent-group-reviewer', 'agent-group-writer', 'direct', { + isLoop: true, + maxIterations: 5, + condition: { type: 'always' }, + label: 'Loop', + }), + createWorkflowEdge('edge-agent-group-reviewer-to-end', 'agent-group-reviewer', 'end'), + ], + }, + settings: { + checkpointing: { enabled: false }, + executionMode: 'off-thread', + orchestrationMode: 'group-chat', + maxIterations: 5, + }, + }, timestamp), + ]; +} + function addIssue( issues: WorkflowValidationIssue[], issue: WorkflowValidationIssue, @@ -1091,3 +1486,4 @@ export function validateWorkflowDefinition(workflow: WorkflowDefinition): Workfl return issues; } + diff --git a/src/shared/domain/workflowTemplate.ts b/src/shared/domain/workflowTemplate.ts index 9f27551..79348f1 100644 --- a/src/shared/domain/workflowTemplate.ts +++ b/src/shared/domain/workflowTemplate.ts @@ -1,9 +1,3 @@ -import { - resolvePatternGraph, - type PatternAgentDefinition, - type PatternDefinition, - type PatternGraphNode, -} from '@shared/domain/pattern'; import { normalizeWorkflowDefinition, type WorkflowDefinition, @@ -45,47 +39,6 @@ function normalizeRequiredString(value: string | undefined, fallback: string): s return normalizeOptionalString(value) ?? fallback; } -function toWorkflowIdFromPatternId(patternId: string): string { - const trimmed = patternId.trim(); - return trimmed.startsWith('pattern-') - ? `workflow-${trimmed.slice('pattern-'.length)}` - : `${trimmed}-workflow`; -} - -function createWorkflowEdge( - source: string, - target: string, - kind: WorkflowEdge['kind'], - overrides?: Partial, -): WorkflowEdge { - return { - id: overrides?.id?.trim() || `workflow-edge-${source}-to-${target}`, - source, - target, - kind, - label: normalizeOptionalString(overrides?.label), - condition: overrides?.condition, - fanOutConfig: overrides?.fanOutConfig, - isLoop: overrides?.isLoop, - maxIterations: overrides?.maxIterations, - }; -} - -function sortAgentNodes(nodes: ReadonlyArray): PatternGraphNode[] { - return nodes - .filter((node) => node.kind === 'agent' && node.agentId) - .slice() - .sort((left, right) => { - const leftOrder = left.order ?? Number.MAX_SAFE_INTEGER; - const rightOrder = right.order ?? Number.MAX_SAFE_INTEGER; - if (leftOrder !== rightOrder) { - return leftOrder - rightOrder; - } - - return left.id.localeCompare(right.id); - }); -} - function normalizeTemplateWorkflow( workflow: WorkflowDefinition | Partial | undefined, ): WorkflowDefinition { @@ -115,115 +68,6 @@ function normalizeTemplateWorkflow( }); } -function createWorkflowAgentNode( - patternNode: PatternGraphNode, - agent: PatternAgentDefinition, - fallbackOrder: number, -): WorkflowNode { - return { - id: patternNode.id.trim(), - kind: 'agent', - label: normalizeRequiredString(agent.name, `Agent ${fallbackOrder + 1}`), - position: { - x: patternNode.position.x, - y: patternNode.position.y, - }, - order: patternNode.order ?? fallbackOrder, - config: { - kind: 'agent', - ...agent, - }, - }; -} - -function mapPatternNodeId(node: PatternGraphNode | undefined): string | undefined { - if (!node) { - return undefined; - } - - switch (node.kind) { - case 'user-input': - return 'start'; - case 'user-output': - return 'end'; - case 'agent': - return node.id.trim(); - default: - return undefined; - } -} - -function buildWorkflowAdjacency( - edges: ReadonlyArray, - excludedEdgeId?: string, -): Map { - const adjacency = new Map(); - for (const edge of edges) { - if (edge.id === excludedEdgeId) { - continue; - } - - const next = adjacency.get(edge.source); - if (next) { - next.push(edge.target); - } else { - adjacency.set(edge.source, [edge.target]); - } - } - - return adjacency; -} - -function canReachWorkflowNode( - edges: ReadonlyArray, - startNodeId: string, - targetNodeId: string, - excludedEdgeId?: string, -): boolean { - if (startNodeId === targetNodeId) { - return true; - } - - const adjacency = buildWorkflowAdjacency(edges, excludedEdgeId); - const queue = [startNodeId]; - const visited = new Set(); - while (queue.length > 0) { - const current = queue.shift()!; - if (visited.has(current)) { - continue; - } - - visited.add(current); - for (const candidate of adjacency.get(current) ?? []) { - if (candidate === targetNodeId) { - return true; - } - - queue.push(candidate); - } - } - - return false; -} - -function markLoopEdges( - edges: ReadonlyArray, - maxIterations: number, -): WorkflowEdge[] { - return edges.map((edge) => { - const participatesInCycle = canReachWorkflowNode(edges, edge.target, edge.source, edge.id); - if (!participatesInCycle) { - return edge; - } - - return { - ...edge, - isLoop: true, - maxIterations, - condition: edge.condition ?? { type: 'always' }, - }; - }); -} export function normalizeWorkflowTemplateDefinition(template: WorkflowTemplateDefinition): WorkflowTemplateDefinition { const workflow = normalizeTemplateWorkflow(template.workflow); @@ -240,141 +84,6 @@ export function normalizeWorkflowTemplateDefinition(template: WorkflowTemplateDe }; } -export function buildWorkflowFromPattern(pattern: PatternDefinition): WorkflowDefinition { - const resolvedGraph = resolvePatternGraph(pattern); - const patternNodesById = new Map(resolvedGraph.nodes.map((node) => [node.id, node])); - const agentsById = new Map(pattern.agents.map((agent) => [agent.id, agent])); - const orderedAgentNodes = sortAgentNodes(resolvedGraph.nodes); - const startPosition = patternNodesById.get('system-user-input')?.position ?? { x: 0, y: 0 }; - const endPosition = patternNodesById.get('system-user-output')?.position ?? { x: 500, y: 0 }; - const workflowNodes: WorkflowNode[] = [ - { - id: 'start', - kind: 'start', - label: 'Start', - position: { x: startPosition.x, y: startPosition.y }, - config: { kind: 'start' }, - }, - ...orderedAgentNodes.map((node, index) => { - const agent = node.agentId ? agentsById.get(node.agentId) : undefined; - if (!agent) { - throw new Error(`Pattern "${pattern.id}" references missing agent "${node.agentId ?? node.id}".`); - } - - return createWorkflowAgentNode(node, agent, index); - }), - { - id: 'end', - kind: 'end', - label: 'End', - position: { x: endPosition.x, y: endPosition.y }, - config: { kind: 'end' }, - }, - ]; - - const orderedAgentIds = workflowNodes.filter((node) => node.kind === 'agent').map((node) => node.id); - const edges: WorkflowEdge[] = []; - const seenEdges = new Set(); - const pushEdge = (edge: WorkflowEdge) => { - const dedupeKey = `${edge.source}:${edge.target}:${edge.kind}:${edge.isLoop === true ? 'loop' : 'plain'}`; - if (seenEdges.has(dedupeKey)) { - return; - } - - seenEdges.add(dedupeKey); - edges.push(edge); - }; - - switch (pattern.mode) { - case 'single': - case 'sequential': - case 'magentic': { - const path = ['start', ...orderedAgentIds, 'end']; - for (let index = 0; index < path.length - 1; index += 1) { - pushEdge(createWorkflowEdge(path[index]!, path[index + 1]!, 'direct')); - } - break; - } - case 'concurrent': { - for (const agentId of orderedAgentIds) { - pushEdge(createWorkflowEdge('start', agentId, 'fan-out', { - fanOutConfig: { strategy: 'broadcast' }, - })); - pushEdge(createWorkflowEdge(agentId, 'end', 'fan-in')); - } - break; - } - case 'handoff': { - for (const patternEdge of resolvedGraph.edges) { - const sourceNode = patternNodesById.get(patternEdge.source); - const targetNode = patternNodesById.get(patternEdge.target); - const source = mapPatternNodeId(sourceNode); - const target = mapPatternNodeId(targetNode); - if (!source || !target) { - continue; - } - - pushEdge(createWorkflowEdge(source, target, 'direct', { - id: `workflow-${patternEdge.id.trim()}`, - })); - } - break; - } - case 'group-chat': { - const path = ['start', ...orderedAgentIds, 'end']; - for (let index = 0; index < path.length - 1; index += 1) { - const source = path[index]!; - const target = path[index + 1]!; - pushEdge(createWorkflowEdge(source, target, 'direct', source !== 'start' && target !== 'end' - ? { - isLoop: true, - maxIterations: pattern.maxIterations, - condition: { type: 'always' }, - } - : undefined)); - } - - if (orderedAgentIds.length > 0) { - pushEdge(createWorkflowEdge( - orderedAgentIds[orderedAgentIds.length - 1]!, - orderedAgentIds[0]!, - 'direct', - { - id: `workflow-edge-${orderedAgentIds[orderedAgentIds.length - 1]}-loop-${orderedAgentIds[0]}`, - isLoop: true, - maxIterations: pattern.maxIterations, - condition: { type: 'always' }, - label: 'Loop', - }, - )); - } - break; - } - } - - const finalizedEdges = pattern.mode === 'handoff' - ? markLoopEdges(edges, Math.max(pattern.maxIterations, 1)) - : edges; - - return normalizeWorkflowDefinition({ - id: toWorkflowIdFromPatternId(pattern.id), - name: pattern.name, - description: pattern.description, - graph: { - nodes: workflowNodes, - edges: finalizedEdges, - }, - settings: { - checkpointing: { enabled: false }, - executionMode: 'off-thread', - maxIterations: pattern.maxIterations, - approvalPolicy: pattern.approvalPolicy, - }, - createdAt: pattern.createdAt, - updatedAt: pattern.updatedAt, - }); -} - export function createBuiltinWorkflowTemplates(timestamp: string): WorkflowTemplateDefinition[] { return [ createCodeReviewPipeline(timestamp), diff --git a/src/shared/domain/workspace.ts b/src/shared/domain/workspace.ts index d01dd41..339d9a6 100644 --- a/src/shared/domain/workspace.ts +++ b/src/shared/domain/workspace.ts @@ -1,5 +1,3 @@ -import type { PatternDefinition } from '@shared/domain/pattern'; -import { createBuiltinPatterns } from '@shared/domain/pattern'; import type { ProjectRecord } from '@shared/domain/project'; import type { SessionRecord } from '@shared/domain/session'; import { createWorkspaceSettings, type WorkspaceSettings } from '@shared/domain/tooling'; @@ -7,22 +5,18 @@ import { createBuiltinWorkflowTemplates, type WorkflowTemplateDefinition, } from '@shared/domain/workflowTemplate'; -import type { WorkflowDefinition } from '@shared/domain/workflow'; +import { createBuiltinWorkflows, type WorkflowDefinition } from '@shared/domain/workflow'; import { nowIso } from '@shared/utils/ids'; export interface WorkspaceState { projects: ProjectRecord[]; - patterns: PatternDefinition[]; workflows: WorkflowDefinition[]; workflowTemplates: WorkflowTemplateDefinition[]; sessions: SessionRecord[]; settings: WorkspaceSettings; - /** IDs of built-in patterns the user has deleted. Prevents re-adding on load. */ - deletedBuiltinPatternIds?: string[]; /** Runtime-only MCP probe progress for live UI updates. */ mcpProbingServerIds?: string[]; selectedProjectId?: string; - selectedPatternId?: string; selectedWorkflowId?: string; selectedSessionId?: string; lastUpdatedAt: string; @@ -32,8 +26,7 @@ export function createWorkspaceSeed(): WorkspaceState { const timestamp = nowIso(); return { projects: [], - patterns: createBuiltinPatterns(timestamp), - workflows: [], + workflows: createBuiltinWorkflows(timestamp), workflowTemplates: createBuiltinWorkflowTemplates(timestamp), sessions: [], settings: createWorkspaceSettings(), diff --git a/src/shared/domain/workspaceAgent.ts b/src/shared/domain/workspaceAgent.ts index a99a64f..00b1287 100644 --- a/src/shared/domain/workspaceAgent.ts +++ b/src/shared/domain/workspaceAgent.ts @@ -1,5 +1,9 @@ import type { PatternAgentCopilotConfig } from '@shared/contracts/sidecar'; -import type { PatternAgentDefinition, PatternDefinition, ReasoningEffort } from '@shared/domain/pattern'; +import type { + AgentNodeConfig, + ReasoningEffort, + WorkflowDefinition, +} from '@shared/domain/workflow'; export interface WorkspaceAgentDefinition { id: string; @@ -13,38 +17,32 @@ export interface WorkspaceAgentDefinition { updatedAt: string; } -export interface PatternAgentOverrides { - name?: string; - description?: string; - instructions?: string; - model?: string; - reasoningEffort?: ReasoningEffort; +export interface WorkflowAgentUsage { + workflowId: string; + workflowName: string; } -export interface WorkspaceAgentUsage { - patternId: string; - patternName: string; +function normalizeOptionalString(value?: string): string | undefined { + const trimmed = value?.trim(); + return trimmed ? trimmed : undefined; } -/** - * Resolves a single pattern agent by merging its workspace agent base with - * per-pattern overrides. Returns the agent unchanged if it is inline. - */ -export function resolvePatternAgent( - agent: PatternAgentDefinition, +export function resolveWorkflowAgentNode( + agent: AgentNodeConfig, workspaceAgents: ReadonlyArray, -): PatternAgentDefinition { +): AgentNodeConfig { if (!agent.workspaceAgentId) { return agent; } - const base = workspaceAgents.find((wa) => wa.id === agent.workspaceAgentId); + const base = workspaceAgents.find((workspaceAgent) => workspaceAgent.id === agent.workspaceAgentId); if (!base) { return agent; } const overrides = agent.overrides ?? {}; return { + ...agent, id: agent.id, name: overrides.name ?? base.name, description: overrides.description ?? base.description, @@ -57,40 +55,45 @@ export function resolvePatternAgent( }; } -/** - * Resolves all agents in a pattern, producing a new pattern whose agents - * have workspace-agent references merged with their base definitions. - */ -export function resolvePatternAgents( - pattern: PatternDefinition, +export function resolveWorkflowAgents( + workflow: WorkflowDefinition, workspaceAgents: ReadonlyArray, -): PatternDefinition { +): WorkflowDefinition { return { - ...pattern, - agents: pattern.agents.map((agent) => resolvePatternAgent(agent, workspaceAgents)), + ...workflow, + graph: { + ...workflow.graph, + nodes: workflow.graph.nodes.map((node) => { + if (node.kind !== 'agent' || node.config.kind !== 'agent') { + return node; + } + + return { + ...node, + config: resolveWorkflowAgentNode(node.config, workspaceAgents), + }; + }), + }, }; } -/** - * Returns every pattern that references the given workspace agent. - */ export function findWorkspaceAgentUsages( agentId: string, - patterns: ReadonlyArray, -): WorkspaceAgentUsage[] { - const usages: WorkspaceAgentUsage[] = []; - for (const pattern of patterns) { - if (pattern.agents.some((a) => a.workspaceAgentId === agentId)) { - usages.push({ patternId: pattern.id, patternName: pattern.name }); + workflows: ReadonlyArray, +): WorkflowAgentUsage[] { + const usages: WorkflowAgentUsage[] = []; + for (const workflow of workflows) { + if (workflow.graph.nodes.some((node) => + node.kind === 'agent' + && node.config.kind === 'agent' + && node.config.workspaceAgentId === agentId)) { + usages.push({ workflowId: workflow.id, workflowName: workflow.name }); } } + return usages; } -/** - * Normalizes a workspace agent definition, trimming string fields and - * ensuring consistent shape. - */ export function normalizeWorkspaceAgentDefinition( agent: WorkspaceAgentDefinition, ): WorkspaceAgentDefinition { @@ -100,5 +103,6 @@ export function normalizeWorkspaceAgentDefinition( description: agent.description.trim(), instructions: agent.instructions.trim(), model: agent.model.trim(), + reasoningEffort: normalizeOptionalString(agent.reasoningEffort) as ReasoningEffort | undefined, }; } diff --git a/tests/main/appServiceDiscoveredTooling.test.ts b/tests/main/appServiceDiscoveredTooling.test.ts index ee4e931..c98bdbc 100644 --- a/tests/main/appServiceDiscoveredTooling.test.ts +++ b/tests/main/appServiceDiscoveredTooling.test.ts @@ -1,7 +1,7 @@ import { describe, expect, mock, test } from 'bun:test'; import type { RunTurnCommand } from '@shared/contracts/sidecar'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; import type { ProjectRecord } from '@shared/domain/project'; import type { SessionRecord } from '@shared/domain/session'; import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace'; @@ -49,11 +49,11 @@ function createProject(overrides?: Partial): ProjectRecord { }; } -function createSession(projectId: string, patternId: string, overrides?: Partial): SessionRecord { +function createSession(projectId: string, workflowId: string, overrides?: Partial): SessionRecord { return { id: 'session-alpha', projectId, - patternId, + workflowId, title: 'Alpha session', createdAt: TIMESTAMP, updatedAt: TIMESTAMP, @@ -66,7 +66,7 @@ function createSession(projectId: string, patternId: string, overrides?: Partial function createService( workspace: WorkspaceState, - pattern: PatternDefinition, + pattern: WorkflowDefinition, options?: { captureRunTurn?: (command: RunTurnCommand) => void; }, @@ -107,7 +107,7 @@ function createService( describe('AryxAppService discovered tooling', () => { test('allows project-discovered MCP servers to be accepted and used in project sessions', async () => { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); + const pattern = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); if (!pattern) { throw new Error('Expected a single-agent pattern in the workspace seed.'); } @@ -139,7 +139,7 @@ describe('AryxAppService discovered tooling', () => { workspace.projects = [project]; workspace.sessions = [session]; workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = pattern.id; workspace.selectedSessionId = session.id; let command: RunTurnCommand | undefined; @@ -168,7 +168,7 @@ describe('AryxAppService discovered tooling', () => { test('allows accepted user-discovered MCP servers to be used across projects', async () => { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); + const pattern = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); if (!pattern) { throw new Error('Expected a single-agent pattern in the workspace seed.'); } @@ -199,7 +199,7 @@ describe('AryxAppService discovered tooling', () => { workspace.projects = [project]; workspace.sessions = [session]; workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = pattern.id; workspace.selectedSessionId = session.id; let command: RunTurnCommand | undefined; @@ -234,7 +234,7 @@ describe('AryxAppService discovered tooling', () => { test('selecting a session also selects that session project', async () => { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); + const pattern = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); if (!pattern) { throw new Error('Expected a single-agent pattern in the workspace seed.'); } diff --git a/tests/main/appServiceGitRefresh.test.ts b/tests/main/appServiceGitRefresh.test.ts index 2c61b18..32d4068 100644 --- a/tests/main/appServiceGitRefresh.test.ts +++ b/tests/main/appServiceGitRefresh.test.ts @@ -1,7 +1,7 @@ import { describe, expect, mock, test } from 'bun:test'; import type { RunTurnCommand } from '@shared/contracts/sidecar'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; import type { ProjectGitRunChangeSummary, ProjectGitWorkingTreeSnapshot, @@ -68,11 +68,11 @@ function createProject(overrides?: Partial): ProjectRecord { }; } -function createSession(projectId: string, patternId: string, overrides?: Partial): SessionRecord { +function createSession(projectId: string, workflowId: string, overrides?: Partial): SessionRecord { return { id: 'session-alpha', projectId, - patternId, + workflowId, title: 'Alpha session', createdAt: TIMESTAMP, updatedAt: TIMESTAMP, @@ -88,12 +88,12 @@ function createFixture(overrides?: { session?: Partial; }): { workspace: WorkspaceState; - pattern: PatternDefinition; + pattern: WorkflowDefinition; project: ProjectRecord; session: SessionRecord; } { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); + const pattern = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); if (!pattern) { throw new Error('Expected the workspace seed to include a single-agent pattern.'); } @@ -104,7 +104,7 @@ function createFixture(overrides?: { workspace.projects = [project]; workspace.sessions = [session]; workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = pattern.id; workspace.selectedSessionId = session.id; return { workspace, pattern, project, session }; @@ -173,7 +173,7 @@ function createRunSummary(): ProjectGitRunChangeSummary { function createService( workspace: WorkspaceState, - pattern: PatternDefinition, + pattern: WorkflowDefinition, options?: { snapshot?: ProjectGitWorkingTreeSnapshot; runSummary?: ProjectGitRunChangeSummary; diff --git a/tests/main/appServiceInterruptedSessions.test.ts b/tests/main/appServiceInterruptedSessions.test.ts index 7d17cca..ed44a3a 100644 --- a/tests/main/appServiceInterruptedSessions.test.ts +++ b/tests/main/appServiceInterruptedSessions.test.ts @@ -2,12 +2,12 @@ import { describe, expect, mock, test } from 'bun:test'; import type { PendingApprovalRecord } from '@shared/domain/approval'; import type { PendingMcpAuthRecord } from '@shared/domain/mcpAuth'; -import type { PatternDefinition } from '@shared/domain/pattern'; import type { PendingPlanReviewRecord } from '@shared/domain/planReview'; import type { SessionRunRecord } from '@shared/domain/runTimeline'; import type { SessionRecord } from '@shared/domain/session'; import type { PendingUserInputRecord } from '@shared/domain/userInput'; import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; const TIMESTAMP = '2026-03-28T00:00:00.000Z'; const INTERRUPTED_RUN_ERROR = @@ -44,20 +44,20 @@ mock.module('keytar', () => ({ const { AryxAppService } = await import('@main/AryxAppService'); -function requireSinglePattern(workspace: WorkspaceState): PatternDefinition { - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); - if (!pattern) { - throw new Error('Expected the workspace seed to include a single-agent pattern.'); +function requireSingleWorkflow(workspace: WorkspaceState): WorkflowDefinition { + const workflow = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); + if (!workflow) { + throw new Error('Expected the workspace seed to include a single-agent workflow.'); } - return pattern; + return workflow; } -function createSession(patternId: string, overrides?: Partial): SessionRecord { +function createSession(workflowId: string, overrides?: Partial): SessionRecord { return { id: 'session-1', projectId: 'project-1', - patternId, + workflowId, title: 'Session', createdAt: TIMESTAMP, updatedAt: TIMESTAMP, @@ -69,7 +69,7 @@ function createSession(patternId: string, overrides?: Partial): S } function createRun( - pattern: PatternDefinition, + workflow: WorkflowDefinition, overrides?: Partial, ): SessionRunRecord { return { @@ -78,9 +78,9 @@ function createRun( projectId: 'project-1', projectPath: 'C:\\workspace\\personal\\repositories\\aryx', workspaceKind: 'project', - patternId: pattern.id, - patternName: pattern.name, - patternMode: pattern.mode, + workflowId: workflow.id, + workflowName: workflow.name, + workflowMode: workflow.settings.orchestrationMode ?? 'single', triggerMessageId: 'message-1', startedAt: TIMESTAMP, status: 'running', @@ -171,9 +171,9 @@ function createService( describe('AryxAppService interrupted session cleanup', () => { test('clears stale approvals and user input, then fails the interrupted run on load', async () => { const workspace = createWorkspaceSeed(); - const pattern = requireSinglePattern(workspace); - const runningRun = createRun(pattern); - const session = createSession(pattern.id, { + const workflow = requireSingleWorkflow(workspace); + const runningRun = createRun(workflow); + const session = createSession(workflow.id, { status: 'running', pendingApproval: createPendingApproval('approval-1', 'Approve reading the repo'), pendingApprovalQueue: [createPendingApproval('approval-2', 'Approve writing the repo')], @@ -212,10 +212,10 @@ describe('AryxAppService interrupted session cleanup', () => { test('fails sessions that were left in running state even without pending interaction records', async () => { const workspace = createWorkspaceSeed(); - const pattern = requireSinglePattern(workspace); - const session = createSession(pattern.id, { + const workflow = requireSingleWorkflow(workspace); + const session = createSession(workflow.id, { status: 'running', - runs: [createRun(pattern)], + runs: [createRun(workflow)], }); workspace.sessions = [session]; @@ -235,10 +235,10 @@ describe('AryxAppService interrupted session cleanup', () => { test('preserves restart-safe plan review and MCP auth prompts', async () => { const workspace = createWorkspaceSeed(); - const pattern = requireSinglePattern(workspace); + const workflow = requireSingleWorkflow(workspace); const planReview = createPendingPlanReview(); const mcpAuth = createPendingMcpAuth(); - const session = createSession(pattern.id, { + const session = createSession(workflow.id, { pendingPlanReview: planReview, pendingMcpAuth: mcpAuth, }); diff --git a/tests/main/appServiceMessageActions.test.ts b/tests/main/appServiceMessageActions.test.ts index 8f3e02d..1a30c67 100644 --- a/tests/main/appServiceMessageActions.test.ts +++ b/tests/main/appServiceMessageActions.test.ts @@ -1,7 +1,7 @@ import { describe, expect, mock, test } from 'bun:test'; import type { RunTurnCommand } from '@shared/contracts/sidecar'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; import type { ProjectRecord } from '@shared/domain/project'; import type { SessionRecord } from '@shared/domain/session'; import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace'; @@ -49,11 +49,11 @@ function createProject(overrides?: Partial): ProjectRecord { }; } -function createSession(projectId: string, patternId: string, overrides?: Partial): SessionRecord { +function createSession(projectId: string, workflowId: string, overrides?: Partial): SessionRecord { return { id: 'session-alpha', projectId, - patternId, + workflowId, title: 'Alpha session', createdAt: TIMESTAMP, updatedAt: TIMESTAMP, @@ -102,12 +102,12 @@ function createSession(projectId: string, patternId: string, overrides?: Partial function createFixture(): { workspace: WorkspaceState; - pattern: PatternDefinition; + pattern: WorkflowDefinition; project: ProjectRecord; session: SessionRecord; } { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); + const pattern = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); if (!pattern) { throw new Error('Expected the workspace seed to include a single-agent pattern.'); } @@ -118,7 +118,7 @@ function createFixture(): { workspace.projects = [project]; workspace.sessions = [session]; workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = pattern.id; workspace.selectedSessionId = session.id; return { workspace, pattern, project, session }; @@ -126,7 +126,7 @@ function createFixture(): { function createService( workspace: WorkspaceState, - pattern: PatternDefinition, + pattern: WorkflowDefinition, options?: { captureRunTurn?: (command: RunTurnCommand) => void; }, diff --git a/tests/main/appServicePattern.test.ts b/tests/main/appServicePattern.test.ts deleted file mode 100644 index 511a995..0000000 --- a/tests/main/appServicePattern.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { describe, expect, mock, test } from 'bun:test'; - -import type { PatternDefinition } from '@shared/domain/pattern'; -import { resolvePatternGraph } from '@shared/domain/pattern'; -import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace'; - -const TIMESTAMP = '2026-03-27T00:00:00.000Z'; - -mock.module('electron', () => { - const electronMock = { - app: { - isPackaged: false, - getAppPath: () => 'C:\\workspace\\personal\\repositories\\aryx', - getPath: () => 'C:\\workspace\\personal\\repositories\\aryx\\tests\\fixtures', - }, - dialog: { - showOpenDialog: async () => ({ canceled: true, filePaths: [] }), - }, - shell: { - openPath: async () => '', - }, - }; - - return { - ...electronMock, - default: electronMock, - }; -}); - -mock.module('keytar', () => ({ - default: { - getPassword: async () => null, - setPassword: async () => undefined, - deletePassword: async () => false, - }, -})); - -const { AryxAppService } = await import('@main/AryxAppService'); - -function createService( - workspace: WorkspaceState, - options?: { knownApprovalToolNames?: string[] }, -): InstanceType { - const service = new AryxAppService(); - const internals = service as unknown as Record; - internals.loadWorkspace = async () => workspace; - internals.persistAndBroadcast = async (nextWorkspace: WorkspaceState) => nextWorkspace; - internals.listKnownApprovalToolNames = async () => options?.knownApprovalToolNames ?? ['read', 'write', 'shell']; - - return service; -} - -function requirePattern(workspace: WorkspaceState, mode: PatternDefinition['mode']): PatternDefinition { - const pattern = workspace.patterns.find((candidate) => candidate.mode === mode); - if (!pattern) { - throw new Error(`Expected workspace seed to include a ${mode} pattern.`); - } - - return pattern; -} - -describe('AryxAppService deletePattern', () => { - test('deletes a built-in pattern and tracks its ID', async () => { - const workspace = createWorkspaceSeed(); - const builtinPattern = requirePattern(workspace, 'sequential'); - const service = createService(workspace); - - const result = await service.deletePattern(builtinPattern.id); - - expect(result.patterns.find((p) => p.id === builtinPattern.id)).toBeUndefined(); - expect(result.deletedBuiltinPatternIds).toContain(builtinPattern.id); - }); - - test('deletes a custom pattern without tracking its ID', async () => { - const workspace = createWorkspaceSeed(); - const customPattern: PatternDefinition = { - ...requirePattern(workspace, 'single'), - id: 'custom-pattern', - name: 'My Custom Pattern', - }; - workspace.patterns.push(customPattern); - const service = createService(workspace); - - const result = await service.deletePattern('custom-pattern'); - - expect(result.patterns.find((p) => p.id === 'custom-pattern')).toBeUndefined(); - expect(result.deletedBuiltinPatternIds ?? []).not.toContain('custom-pattern'); - }); - - test('selects first remaining pattern when the active pattern is deleted', async () => { - const workspace = createWorkspaceSeed(); - const targetPattern = requirePattern(workspace, 'single'); - workspace.selectedPatternId = targetPattern.id; - const service = createService(workspace); - - const result = await service.deletePattern(targetPattern.id); - - expect(result.selectedPatternId).toBe(result.patterns[0]?.id); - expect(result.selectedPatternId).not.toBe(targetPattern.id); - }); -}); - -describe('AryxAppService savePattern', () => { - test('preserves a provided custom graph instead of re-syncing it', async () => { - const workspace = createWorkspaceSeed(); - const pattern = requirePattern(workspace, 'sequential'); - const baseGraph = resolvePatternGraph(pattern); - const customGraph = { - ...baseGraph, - nodes: baseGraph.nodes.map((node, index) => ({ - ...node, - position: { - x: node.position.x + 37 + index, - y: node.position.y + 19 + index * 7, - }, - })), - }; - const service = createService(workspace); - - const result = await service.savePattern({ - ...pattern, - graph: customGraph, - updatedAt: TIMESTAMP, - }); - - const savedPattern = requirePattern(result, 'sequential'); - expect(savedPattern.graph).toEqual(customGraph); - }); - - test('still seeds a default graph when the pattern graph is missing', async () => { - const workspace = createWorkspaceSeed(); - const pattern = requirePattern(workspace, 'group-chat'); - const service = createService(workspace); - - const result = await service.savePattern({ - ...pattern, - graph: undefined, - updatedAt: TIMESTAMP, - }); - - const savedPattern = requirePattern(result, 'group-chat'); - expect(savedPattern.graph).toEqual(resolvePatternGraph(pattern)); - }); -}); diff --git a/tests/main/appServiceProjectCustomization.test.ts b/tests/main/appServiceProjectCustomization.test.ts index be69900..438dd47 100644 --- a/tests/main/appServiceProjectCustomization.test.ts +++ b/tests/main/appServiceProjectCustomization.test.ts @@ -2,10 +2,10 @@ import { describe, expect, mock, test } from 'bun:test'; import type { RunTurnCommand } from '@shared/contracts/sidecar'; import { buildAvailableModelCatalog } from '@shared/domain/models'; -import type { PatternDefinition } from '@shared/domain/pattern'; import type { ProjectRecord } from '@shared/domain/project'; import type { SessionRecord } from '@shared/domain/session'; import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace'; +import { resolveWorkflowAgentNodes, type WorkflowDefinition } from '@shared/domain/workflow'; const TIMESTAMP = '2026-03-28T00:00:00.000Z'; @@ -50,11 +50,11 @@ function createProject(overrides?: Partial): ProjectRecord { }; } -function createSession(projectId: string, patternId: string, overrides?: Partial): SessionRecord { +function createSession(projectId: string, workflowId: string, overrides?: Partial): SessionRecord { return { id: 'session-alpha', projectId, - patternId, + workflowId, title: 'Alpha session', createdAt: TIMESTAMP, updatedAt: TIMESTAMP, @@ -67,7 +67,7 @@ function createSession(projectId: string, patternId: string, overrides?: Partial function createService( workspace: WorkspaceState, - pattern: PatternDefinition, + workflow: WorkflowDefinition, options?: { captureRunTurn?: (command: RunTurnCommand) => void; }, @@ -76,7 +76,7 @@ function createService( const internals = service as unknown as Record; internals.loadWorkspace = async () => workspace; internals.persistAndBroadcast = async (nextWorkspace: WorkspaceState) => nextWorkspace; - internals.buildEffectivePattern = async () => pattern; + internals.buildEffectiveWorkflow = async () => workflow; internals.loadAvailableModelCatalog = async () => buildAvailableModelCatalog(); internals.awaitFinalResponseApproval = async () => undefined; internals.finalizeTurn = () => undefined; @@ -101,19 +101,45 @@ function createService( return service; } +function updatePrimaryAgent( + workflow: WorkflowDefinition, + update: (agent: NonNullable[number]>['config']) => NonNullable[number]>['config'], +): WorkflowDefinition { + let updated = false; + return { + ...workflow, + graph: { + ...workflow.graph, + nodes: workflow.graph.nodes.map((node) => { + if (updated || node.kind !== 'agent' || node.config.kind !== 'agent') { + return node; + } + + updated = true; + return { + ...node, + config: update(node.config), + }; + }), + }, + }; +} + +function getPrimaryAgentConfig(workflow: WorkflowDefinition | undefined) { + const node = workflow ? resolveWorkflowAgentNodes(workflow)[0] : undefined; + return node?.config.kind === 'agent' ? node.config : undefined; +} + describe('AryxAppService project customization', () => { test('sendSessionMessage injects project instructions and enabled project agent profiles', async () => { const workspace = createWorkspaceSeed(); - const basePattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); - if (!basePattern) { - throw new Error('Expected a single-agent pattern in the workspace seed.'); + const baseWorkflow = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); + if (!baseWorkflow) { + throw new Error('Expected a single-agent workflow in the workspace seed.'); } - const pattern: PatternDefinition = { - ...basePattern, - agents: [ - { - ...basePattern.agents[0]!, + const workflow = updatePrimaryAgent(baseWorkflow, (agent) => ({ + ...agent, copilot: { customAgents: [ { @@ -122,9 +148,7 @@ describe('AryxAppService project customization', () => { }, ], }, - }, - ], - }; + })); const project = createProject({ customization: { @@ -171,16 +195,16 @@ describe('AryxAppService project customization', () => { lastScannedAt: TIMESTAMP, }, }); - const session = createSession(project.id, pattern.id); + const session = createSession(project.id, workflow.id); workspace.projects = [project]; workspace.sessions = [session]; workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = workflow.id; workspace.selectedSessionId = session.id; let command: RunTurnCommand | undefined; - const service = createService(workspace, pattern, { + const service = createService(workspace, workflow, { captureRunTurn: (capturedCommand) => { command = capturedCommand; }, @@ -189,7 +213,7 @@ describe('AryxAppService project customization', () => { await service.sendSessionMessage(session.id, 'Use the repository guidance.'); expect(command?.projectInstructions).toBe('Use TypeScript.\n\nPrefer focused tests.'); - expect(command?.pattern.agents[0]?.copilot?.customAgents).toEqual([ + expect(getPrimaryAgentConfig(command?.workflow)?.copilot?.customAgents).toEqual([ { name: 'reviewer', prompt: 'Built-in reviewer prompt.', @@ -206,9 +230,9 @@ describe('AryxAppService project customization', () => { test('sendSessionMessage formats file-scoped and task-scoped project instructions for the sidecar', async () => { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); - if (!pattern) { - throw new Error('Expected a single-agent pattern in the workspace seed.'); + const workflow = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); + if (!workflow) { + throw new Error('Expected a single-agent workflow in the workspace seed.'); } const project = createProject({ @@ -248,16 +272,16 @@ describe('AryxAppService project customization', () => { lastScannedAt: TIMESTAMP, }, }); - const session = createSession(project.id, pattern.id); + const session = createSession(project.id, workflow.id); workspace.projects = [project]; workspace.sessions = [session]; workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = workflow.id; workspace.selectedSessionId = session.id; let command: RunTurnCommand | undefined; - const service = createService(workspace, pattern, { + const service = createService(workspace, workflow, { captureRunTurn: (capturedCommand) => { command = capturedCommand; }, @@ -286,22 +310,22 @@ describe('AryxAppService project customization', () => { test('sendSessionMessage carries structured prompt invocations and uses prompt agent plan mode', async () => { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); - if (!pattern) { - throw new Error('Expected a single-agent pattern in the workspace seed.'); + const workflow = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); + if (!workflow) { + throw new Error('Expected a single-agent workflow in the workspace seed.'); } const project = createProject(); - const session = createSession(project.id, pattern.id); + const session = createSession(project.id, workflow.id); workspace.projects = [project]; workspace.sessions = [session]; workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = workflow.id; workspace.selectedSessionId = session.id; let command: RunTurnCommand | undefined; - const service = createService(workspace, pattern, { + const service = createService(workspace, workflow, { captureRunTurn: (capturedCommand) => { command = capturedCommand; }, @@ -348,21 +372,16 @@ describe('AryxAppService project customization', () => { test('sendSessionMessage hydrates prompt model metadata and overrides the turn pattern model', async () => { const workspace = createWorkspaceSeed(); - const basePattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); - if (!basePattern) { - throw new Error('Expected a single-agent pattern in the workspace seed.'); + const baseWorkflow = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); + if (!baseWorkflow) { + throw new Error('Expected a single-agent workflow in the workspace seed.'); } - const pattern: PatternDefinition = { - ...basePattern, - agents: [ - { - ...basePattern.agents[0]!, + const workflow = updatePrimaryAgent(baseWorkflow, (agent) => ({ + ...agent, model: 'gpt-5.4', reasoningEffort: 'high', - }, - ], - }; + })); const project = createProject({ customization: { @@ -382,16 +401,16 @@ describe('AryxAppService project customization', () => { lastScannedAt: TIMESTAMP, }, }); - const session = createSession(project.id, pattern.id); + const session = createSession(project.id, workflow.id); workspace.projects = [project]; workspace.sessions = [session]; workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = workflow.id; workspace.selectedSessionId = session.id; let command: RunTurnCommand | undefined; - const service = createService(workspace, pattern, { + const service = createService(workspace, workflow, { captureRunTurn: (capturedCommand) => { command = capturedCommand; }, @@ -412,8 +431,8 @@ describe('AryxAppService project customization', () => { model: 'Claude Sonnet 4.5', resolvedPrompt: 'Review the REST API for security gaps.', }); - expect(command?.pattern.agents[0]?.model).toBe('claude-sonnet-4.5'); - expect(command?.pattern.agents[0]?.reasoningEffort).toBeUndefined(); + expect(getPrimaryAgentConfig(command?.workflow)?.model).toBe('claude-sonnet-4.5'); + expect(getPrimaryAgentConfig(command?.workflow)?.reasoningEffort).toBeUndefined(); expect(command?.promptInvocation).toEqual({ id: 'project_customization_prompt_rest_review', name: 'rest-review', @@ -426,9 +445,9 @@ describe('AryxAppService project customization', () => { test('setProjectAgentProfileEnabled persists the updated enabled state', async () => { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); - if (!pattern) { - throw new Error('Expected a single-agent pattern in the workspace seed.'); + const workflow = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); + if (!workflow) { + throw new Error('Expected a single-agent workflow in the workspace seed.'); } const project = createProject({ @@ -447,12 +466,12 @@ describe('AryxAppService project customization', () => { lastScannedAt: TIMESTAMP, }, }); - const session = createSession(project.id, pattern.id); + const session = createSession(project.id, workflow.id); workspace.projects = [project]; workspace.sessions = [session]; - const service = createService(workspace, pattern); + const service = createService(workspace, workflow); const updated = await service.setProjectAgentProfileEnabled(project.id, 'agent-readme', false); expect(updated.projects[0]?.customization?.agentProfiles).toEqual([ diff --git a/tests/main/appServiceScratchpadDirectories.test.ts b/tests/main/appServiceScratchpadDirectories.test.ts index e41abaa..1007d8b 100644 --- a/tests/main/appServiceScratchpadDirectories.test.ts +++ b/tests/main/appServiceScratchpadDirectories.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test'; import { access, mkdir, rm } from 'node:fs/promises'; import { join } from 'node:path'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; import { createScratchpadProject } from '@shared/domain/project'; import type { SessionRecord } from '@shared/domain/session'; import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace'; @@ -50,8 +50,8 @@ async function pathExists(path: string): Promise { } } -function requireSinglePattern(workspace: WorkspaceState): PatternDefinition { - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); +function requireSinglePattern(workspace: WorkspaceState): WorkflowDefinition { + const pattern = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); if (!pattern) { throw new Error('Expected the workspace seed to include a single-agent pattern.'); } @@ -59,11 +59,11 @@ function requireSinglePattern(workspace: WorkspaceState): PatternDefinition { return pattern; } -function createScratchpadSession(patternId: string, overrides?: Partial): SessionRecord { +function createScratchpadSession(workflowId: string, overrides?: Partial): SessionRecord { return { id: 'session-scratchpad', projectId: 'project-scratchpad', - patternId, + workflowId, title: 'Scratchpad', createdAt: TIMESTAMP, updatedAt: TIMESTAMP, @@ -116,7 +116,7 @@ describe('AryxAppService scratchpad directories', () => { const scratchpadProject = createScratchpadProject(join(USER_DATA_PATH, 'scratchpad'), TIMESTAMP); workspace.projects = [scratchpadProject]; workspace.selectedProjectId = scratchpadProject.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = pattern.id; const service = createService(workspace); @@ -152,7 +152,7 @@ describe('AryxAppService scratchpad directories', () => { workspace.projects = [scratchpadProject]; workspace.sessions = [originalSession]; workspace.selectedProjectId = scratchpadProject.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = pattern.id; workspace.selectedSessionId = originalSession.id; const service = createService(workspace); @@ -212,7 +212,7 @@ describe('AryxAppService scratchpad directories', () => { workspace.projects = [scratchpadProject]; workspace.sessions = [originalSession]; workspace.selectedProjectId = scratchpadProject.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = pattern.id; workspace.selectedSessionId = originalSession.id; const service = createService(workspace); @@ -248,7 +248,7 @@ describe('AryxAppService scratchpad directories', () => { workspace.projects = [scratchpadProject]; workspace.sessions = [session]; workspace.selectedProjectId = scratchpadProject.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = pattern.id; workspace.selectedSessionId = session.id; const service = createService(workspace); diff --git a/tests/main/appServiceSubworkflow.test.ts b/tests/main/appServiceSubworkflow.test.ts index fc6c3a6..05b7f14 100644 --- a/tests/main/appServiceSubworkflow.test.ts +++ b/tests/main/appServiceSubworkflow.test.ts @@ -201,7 +201,7 @@ describe('AryxAppService sub-workflow operations', () => { expect(session?.workflowId).toBe('parent'); expect(session?.sessionModelConfig).toEqual({ model: 'gpt-5.4', - reasoningEffort: 'medium', + reasoningEffort: undefined, }); }); }); diff --git a/tests/main/appServiceTerminal.test.ts b/tests/main/appServiceTerminal.test.ts index 6fa8425..c4689f8 100644 --- a/tests/main/appServiceTerminal.test.ts +++ b/tests/main/appServiceTerminal.test.ts @@ -48,11 +48,11 @@ function createProject(overrides?: Partial): ProjectRecord { }; } -function createSession(patternId: string, overrides?: Partial): SessionRecord { +function createSession(workflowId: string, overrides?: Partial): SessionRecord { return { id: 'session-1', projectId: 'project-1', - patternId, + workflowId, title: 'Terminal Session', createdAt: TIMESTAMP, updatedAt: TIMESTAMP, @@ -133,7 +133,7 @@ function createService(workspace: WorkspaceState, terminalSnapshot = createTermi describe('AryxAppService terminal integration', () => { test('uses the selected session cwd when creating and restarting the terminal', async () => { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns[0]; + const pattern = workspace.workflows[0]; if (!pattern) { throw new Error('Expected a seeded pattern.'); } diff --git a/tests/main/appServiceTooling.test.ts b/tests/main/appServiceTooling.test.ts index fb28826..9d7f370 100644 --- a/tests/main/appServiceTooling.test.ts +++ b/tests/main/appServiceTooling.test.ts @@ -1,7 +1,7 @@ import { describe, expect, mock, test } from 'bun:test'; import type { RunTurnCommand } from '@shared/contracts/sidecar'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; import { createScratchpadProject } from '@shared/domain/project'; import type { SessionRecord } from '@shared/domain/session'; import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace'; @@ -43,11 +43,11 @@ const { AryxAppService } = await import('@main/AryxAppService'); function createWorkspaceFixture(): { workspace: WorkspaceState; - pattern: PatternDefinition; + pattern: WorkflowDefinition; session: SessionRecord; } { const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'single'); + const pattern = workspace.workflows.find((candidate) => candidate.settings.orchestrationMode === 'single'); if (!pattern) { throw new Error('Expected the workspace seed to include a single-agent pattern.'); } @@ -56,7 +56,7 @@ function createWorkspaceFixture(): { const session: SessionRecord = { id: 'session-scratchpad', projectId: project.id, - patternId: pattern.id, + workflowId: pattern.id, title: 'Scratchpad', createdAt: TIMESTAMP, updatedAt: TIMESTAMP, @@ -69,7 +69,7 @@ function createWorkspaceFixture(): { workspace.projects = [project]; workspace.sessions = [session]; workspace.selectedProjectId = project.id; - workspace.selectedPatternId = pattern.id; + workspace.selectedWorkflowId = pattern.id; workspace.selectedSessionId = session.id; workspace.settings.tooling = { mcpServers: [ @@ -105,7 +105,7 @@ function createWorkspaceFixture(): { function createService( workspace: WorkspaceState, - pattern: PatternDefinition, + pattern: WorkflowDefinition, options?: { captureRunTurn?: (command: RunTurnCommand) => void; knownApprovalToolNames?: string[]; diff --git a/tests/main/appServiceWorkflow.test.ts b/tests/main/appServiceWorkflow.test.ts index a872610..b770dff 100644 --- a/tests/main/appServiceWorkflow.test.ts +++ b/tests/main/appServiceWorkflow.test.ts @@ -87,11 +87,13 @@ function createWorkflow(): WorkflowDefinition { describe('AryxAppService workflow operations', () => { test('saves workflows into workspace state', async () => { const workspace = createWorkspaceSeed(); + const initialWorkflowCount = workspace.workflows.length; const service = createService(workspace); const result = await service.saveWorkflow(createWorkflow()); - expect(result.workflows).toHaveLength(1); + expect(result.workflows).toHaveLength(initialWorkflowCount + 1); + expect(result.workflows.some((workflow) => workflow.id === 'workflow-test')).toBe(true); expect(result.selectedWorkflowId).toBe('workflow-test'); }); @@ -115,40 +117,28 @@ describe('AryxAppService workflow operations', () => { test('creates workflows from templates and selects the new workflow', async () => { const workspace = createWorkspaceSeed(); + const initialWorkflowCount = workspace.workflows.length; const service = createService(workspace); const result = await service.createWorkflowFromTemplate('workflow-template-code-review', { name: 'Template Copy', }); - expect(result.workflows).toHaveLength(1); - expect(result.workflows[0]?.name).toBe('Template Copy'); - expect(result.selectedWorkflowId).toBe(result.workflows[0]?.id); - }); - - test('upgrades a pattern to a saved workflow without removing the pattern', async () => { - const workspace = createWorkspaceSeed(); - const pattern = workspace.patterns.find((candidate) => candidate.mode === 'handoff'); - if (!pattern) { - throw new Error('Expected a handoff pattern.'); - } - - const service = createService(workspace); - const result = await service.upgradePatternToWorkflow(pattern.id, { save: true }); - - expect(result.workspace?.workflows).toHaveLength(1); - expect(result.workspace?.patterns.some((candidate) => candidate.id === pattern.id)).toBe(true); - expect(result.workflow.id).toBe('workflow-handoff-support'); + expect(result.workflows).toHaveLength(initialWorkflowCount + 1); + const createdWorkflow = result.workflows.find((workflow) => workflow.name === 'Template Copy'); + expect(createdWorkflow).toBeDefined(); + expect(result.selectedWorkflowId).toBe(createdWorkflow?.id); }); test('imports and saves workflows from yaml', async () => { const workspace = createWorkspaceSeed(); + const initialWorkflowCount = workspace.workflows.length; const service = createService(workspace); const yaml = exportWorkflowDefinition(createWorkflow(), 'yaml').content; const result = await service.importWorkflow(yaml, 'yaml', { save: true }); - expect(result.workspace?.workflows).toHaveLength(1); + expect(result.workspace?.workflows).toHaveLength(initialWorkflowCount + 1); expect(result.workspace?.selectedWorkflowId).toBe('workflow-test'); expect(result.workflow.id).toBe('workflow-test'); }); diff --git a/tests/main/appServiceWorkflowCheckpointing.test.ts b/tests/main/appServiceWorkflowCheckpointing.test.ts index aa3d4a3..50c0651 100644 --- a/tests/main/appServiceWorkflowCheckpointing.test.ts +++ b/tests/main/appServiceWorkflowCheckpointing.test.ts @@ -8,6 +8,7 @@ import { type RunTimelineEventRecord, type SessionRunRecord, } from '@shared/domain/runTimeline'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; mock.module('electron', () => { const electronMock = { @@ -200,7 +201,7 @@ describe('AryxAppService workflow checkpointing', () => { workspaceKind: 'scratchpad', mode: 'interactive', messageMode: 'enqueue', - pattern: createPattern(), + workflow: createWorkflow(), messages: session.messages, resumeFromCheckpoint, }), @@ -230,7 +231,7 @@ describe('AryxAppService workflow checkpointing', () => { }); function createRunningSession(): { session: SessionRecord; run: SessionRunRecord } { - const pattern = createPattern(); + const workflow = createWorkflow(); const run = createSessionRunRecord({ requestId: 'turn-1', project: { @@ -239,14 +240,14 @@ function createRunningSession(): { session: SessionRecord; run: SessionRunRecord }, workingDirectory: 'C:\\scratchpad', workspaceKind: 'scratchpad', - pattern, + workflow, triggerMessageId: 'msg-user-1', startedAt: '2026-04-01T12:00:00.000Z', }); const session: SessionRecord = { id: 'session-1', projectId: SCRATCHPAD_PROJECT_ID, - patternId: pattern.id, + workflowId: workflow.id, title: 'Checkpoint session', createdAt: '2026-04-01T12:00:00.000Z', updatedAt: '2026-04-01T12:00:00.000Z', @@ -274,23 +275,42 @@ function createRunningSession(): { session: SessionRecord; run: SessionRunRecord return { session, run }; } -function createPattern() { +function createWorkflow(): WorkflowDefinition { return { - id: 'pattern-handoff', + id: 'workflow-handoff', name: 'Checkpointing flow', description: '', - mode: 'handoff' as const, - availability: 'available' as const, - maxIterations: 4, - agents: [ - { - id: 'agent-1', - name: 'Primary', - description: '', - instructions: 'Help with the request.', - model: 'gpt-5.4', - }, - ], + graph: { + nodes: [ + { id: 'start', kind: 'start', label: 'Start', position: { x: 0, y: 0 }, config: { kind: 'start' } }, + { + id: 'agent-1', + kind: 'agent', + label: 'Primary', + position: { x: 200, y: 0 }, + order: 0, + config: { + kind: 'agent', + id: 'agent-1', + name: 'Primary', + description: '', + instructions: 'Help with the request.', + model: 'gpt-5.4', + }, + }, + { id: 'end', kind: 'end', label: 'End', position: { x: 400, y: 0 }, config: { kind: 'end' } }, + ], + edges: [ + { id: 'edge-start-agent', source: 'start', target: 'agent-1', kind: 'direct' }, + { id: 'edge-agent-end', source: 'agent-1', target: 'end', kind: 'direct' }, + ], + }, + settings: { + checkpointing: { enabled: true }, + executionMode: 'off-thread' as const, + orchestrationMode: 'handoff' as const, + maxIterations: 4, + }, createdAt: '2026-04-01T00:00:00.000Z', updatedAt: '2026-04-01T00:00:00.000Z', }; diff --git a/tests/main/sidecarProcess.test.ts b/tests/main/sidecarProcess.test.ts index d9209a7..3c5e468 100644 --- a/tests/main/sidecarProcess.test.ts +++ b/tests/main/sidecarProcess.test.ts @@ -157,22 +157,41 @@ describe('SidecarClient', () => { requestId: 'turn-1', sessionId: 'session-1', projectPath: 'C:\\workspace\\project', - pattern: { - id: 'pattern-1', + workflow: { + id: 'workflow-1', name: 'Single Agent', description: '', - mode: 'single', - availability: 'available', - maxIterations: 1, - agents: [ - { - id: 'agent-1', - name: 'Primary', - description: '', - instructions: 'Help with the request.', - model: 'gpt-5.4', - }, - ], + graph: { + nodes: [ + { id: 'start', kind: 'start', label: 'Start', position: { x: 0, y: 0 }, config: { kind: 'start' } }, + { + id: 'agent-1', + kind: 'agent', + label: 'Primary', + position: { x: 200, y: 0 }, + order: 0, + config: { + kind: 'agent', + id: 'agent-1', + name: 'Primary', + description: '', + instructions: 'Help with the request.', + model: 'gpt-5.4', + }, + }, + { id: 'end', kind: 'end', label: 'End', position: { x: 400, y: 0 }, config: { kind: 'end' } }, + ], + edges: [ + { id: 'edge-start-agent', source: 'start', target: 'agent-1', kind: 'direct' }, + { id: 'edge-agent-end', source: 'agent-1', target: 'end', kind: 'direct' }, + ], + }, + settings: { + checkpointing: { enabled: false }, + executionMode: 'off-thread', + orchestrationMode: 'single', + maxIterations: 1, + }, createdAt: '2026-04-01T00:00:00.000Z', updatedAt: '2026-04-01T00:00:00.000Z', }, @@ -253,22 +272,41 @@ describe('SidecarClient', () => { requestId: 'turn-1', sessionId: 'session-1', projectPath: 'C:\\workspace\\project', - pattern: { - id: 'pattern-1', + workflow: { + id: 'workflow-1', name: 'Handoff', description: '', - mode: 'handoff', - availability: 'available', - maxIterations: 1, - agents: [ - { - id: 'agent-1', - name: 'Primary', - description: '', - instructions: 'Help with the request.', - model: 'gpt-5.4', - }, - ], + graph: { + nodes: [ + { id: 'start', kind: 'start', label: 'Start', position: { x: 0, y: 0 }, config: { kind: 'start' } }, + { + id: 'agent-1', + kind: 'agent', + label: 'Primary', + position: { x: 200, y: 0 }, + order: 0, + config: { + kind: 'agent', + id: 'agent-1', + name: 'Primary', + description: '', + instructions: 'Help with the request.', + model: 'gpt-5.4', + }, + }, + { id: 'end', kind: 'end', label: 'End', position: { x: 400, y: 0 }, config: { kind: 'end' } }, + ], + edges: [ + { id: 'edge-start-agent', source: 'start', target: 'agent-1', kind: 'direct' }, + { id: 'edge-agent-end', source: 'agent-1', target: 'end', kind: 'direct' }, + ], + }, + settings: { + checkpointing: { enabled: true }, + executionMode: 'off-thread', + orchestrationMode: 'handoff', + maxIterations: 1, + }, createdAt: '2026-04-01T00:00:00.000Z', updatedAt: '2026-04-01T00:00:00.000Z', }, diff --git a/tests/main/workspaceRepositoryScratchpad.test.ts b/tests/main/workspaceRepositoryScratchpad.test.ts index 3212b29..5d05b13 100644 --- a/tests/main/workspaceRepositoryScratchpad.test.ts +++ b/tests/main/workspaceRepositoryScratchpad.test.ts @@ -27,15 +27,15 @@ const { WorkspaceRepository } = await import('@main/persistence/workspaceReposit function createStoredWorkspace(): WorkspaceState { const workspace = createWorkspaceSeed(); const scratchpadProject = createScratchpadProject('C:\\legacy\\scratchpad', TIMESTAMP); - const patternId = workspace.patterns[0]?.id; - if (!patternId) { + const workflowId = workspace.workflows[0]?.id; + if (!workflowId) { throw new Error('Expected workspace seed to include at least one pattern.'); } const session: SessionRecord = { id: 'session-scratchpad', projectId: scratchpadProject.id, - patternId, + workflowId, title: 'Scratchpad', createdAt: TIMESTAMP, updatedAt: TIMESTAMP, @@ -49,7 +49,7 @@ function createStoredWorkspace(): WorkspaceState { projects: [scratchpadProject], sessions: [session], selectedProjectId: scratchpadProject.id, - selectedPatternId: patternId, + selectedWorkflowId: workflowId, selectedSessionId: session.id, }; } diff --git a/tests/renderer/messagePhase.test.ts b/tests/renderer/messagePhase.test.ts index b9702ec..b9fe132 100644 --- a/tests/renderer/messagePhase.test.ts +++ b/tests/renderer/messagePhase.test.ts @@ -10,7 +10,7 @@ function createSession( return { id: 'session-1', projectId: 'project-1', - patternId: 'pattern-1', + workflowId: 'pattern-1', title: 'Test session', createdAt: '2026-03-23T00:00:00.000Z', updatedAt: '2026-03-23T00:00:00.000Z', diff --git a/tests/renderer/sessionActivity.test.ts b/tests/renderer/sessionActivity.test.ts index 3be8a6b..f7a7c66 100644 --- a/tests/renderer/sessionActivity.test.ts +++ b/tests/renderer/sessionActivity.test.ts @@ -16,11 +16,11 @@ import { type SessionActivityMap, type SessionRequestUsageMap, } from '@renderer/lib/sessionActivity'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; import type { SessionEventRecord } from '@shared/domain/event'; describe('session activity helpers', () => { - const agents: PatternDefinition['agents'] = [ + const agents = [ { id: 'architect', name: 'Architect', @@ -37,7 +37,14 @@ describe('session activity helpers', () => { model: 'gpt-5.4', reasoningEffort: 'medium', }, - ]; + ] satisfies Array<{ + id: string; + name: string; + description: string; + instructions: string; + model: string; + reasoningEffort?: 'high' | 'medium'; + }>; test('stores activity per session and per agent', () => { const architectEvent: SessionEventRecord = { @@ -247,9 +254,9 @@ describe('session activity helpers', () => { projectId: 'project-1', projectPath: 'C:\\workspace\\project', workspaceKind: 'project', - patternId: 'pattern-1', - patternName: 'Pattern', - patternMode: 'single', + workflowId: 'workflow-1', + workflowName: 'Pattern', + workflowMode: 'single', triggerMessageId: 'msg-1', startedAt: '2026-03-23T00:00:00.000Z', completedAt: '2026-03-23T00:00:01.000Z', diff --git a/tests/renderer/sessionWorkspace.test.ts b/tests/renderer/sessionWorkspace.test.ts index 680461f..769363c 100644 --- a/tests/renderer/sessionWorkspace.test.ts +++ b/tests/renderer/sessionWorkspace.test.ts @@ -10,7 +10,6 @@ describe('session workspace helpers', () => { function createWorkspace(): WorkspaceState { return { projects: [], - patterns: [], workflows: [], workflowTemplates: [], settings: createWorkspaceSettings(), @@ -18,7 +17,7 @@ describe('session workspace helpers', () => { { id: 'session-1', projectId: 'project-1', - patternId: 'pattern-1', + workflowId: 'workflow-1', title: 'Session', createdAt: '2026-03-23T00:00:00.000Z', updatedAt: '2026-03-23T00:00:00.000Z', @@ -196,9 +195,9 @@ describe('session workspace helpers', () => { projectId: 'project-1', projectPath: 'C:\\workspace\\alpha', workspaceKind: 'project', - patternId: 'pattern-1', - patternName: 'Sequential Review', - patternMode: 'sequential', + workflowId: 'workflow-1', + workflowName: 'Sequential Review', + workflowMode: 'sequential', triggerMessageId: 'msg-user-1', startedAt: '2026-03-23T00:00:01.000Z', status: 'running', diff --git a/tests/shared/models.test.ts b/tests/shared/models.test.ts index 913aa17..c19fea9 100644 --- a/tests/shared/models.test.ts +++ b/tests/shared/models.test.ts @@ -5,10 +5,10 @@ import { buildAvailableModelCatalog, findModel, findModelByReference, - normalizePatternModels, + normalizeWorkflowModels, resolveReasoningEffort, } from '@shared/domain/models'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; const availableModels: SidecarModelCapability[] = [ { @@ -24,24 +24,43 @@ const availableModels: SidecarModelCapability[] = [ }, ]; -function createPattern(): PatternDefinition { +function createWorkflow(): WorkflowDefinition { return { id: 'pattern-1', name: 'Pattern', description: '', - mode: 'single', - availability: 'available', - maxIterations: 1, - agents: [ - { - id: 'agent-1', - name: 'Primary Agent', - description: 'Helpful assistant', - instructions: 'Help the user.', - model: 'claude-sonnet-4.5', - reasoningEffort: 'high', - }, - ], + graph: { + nodes: [ + { id: 'start', kind: 'start', label: 'Start', position: { x: 0, y: 0 }, config: { kind: 'start' } }, + { + id: 'agent-1', + kind: 'agent', + label: 'Primary Agent', + position: { x: 200, y: 0 }, + order: 0, + config: { + kind: 'agent', + id: 'agent-1', + name: 'Primary Agent', + description: 'Helpful assistant', + instructions: 'Help the user.', + model: 'claude-sonnet-4.5', + reasoningEffort: 'high', + }, + }, + { id: 'end', kind: 'end', label: 'End', position: { x: 400, y: 0 }, config: { kind: 'end' } }, + ], + edges: [ + { id: 'edge-start-agent', source: 'start', target: 'agent-1', kind: 'direct' }, + { id: 'edge-agent-end', source: 'agent-1', target: 'end', kind: 'direct' }, + ], + }, + settings: { + checkpointing: { enabled: false }, + executionMode: 'off-thread', + orchestrationMode: 'single', + maxIterations: 1, + }, createdAt: '2026-03-23T00:00:00.000Z', updatedAt: '2026-03-23T00:00:00.000Z', }; @@ -70,12 +89,13 @@ describe('dynamic model catalog', () => { expect(findModelByReference('Claude Sonnet 4.5', catalog)?.id).toBe('claude-sonnet-4.5'); }); - test('normalizes pattern agents before runtime execution', () => { - const normalized = normalizePatternModels( - createPattern(), + test('normalizes workflow agent reasoning effort before runtime execution', () => { + const normalized = normalizeWorkflowModels( + createWorkflow(), buildAvailableModelCatalog(availableModels), ); - expect(normalized.agents[0].reasoningEffort).toBeUndefined(); + const primaryAgent = normalized.graph.nodes.find((node) => node.kind === 'agent'); + expect(primaryAgent?.config.kind === 'agent' ? primaryAgent.config.reasoningEffort : undefined).toBeUndefined(); }); }); diff --git a/tests/shared/runTimeline.test.ts b/tests/shared/runTimeline.test.ts index 93b4864..67131cb 100644 --- a/tests/shared/runTimeline.test.ts +++ b/tests/shared/runTimeline.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; import { appendRunActivityEvent, completeSessionRunRecord, @@ -12,30 +12,58 @@ import { import type { ProjectRecord } from '@shared/domain/project'; import type { PendingApprovalRecord } from '@shared/domain/approval'; -function createPattern(): PatternDefinition { +function createWorkflow(): WorkflowDefinition { return { - id: 'pattern-sequential', + id: 'workflow-sequential', name: 'Sequential Trio Review', description: 'Sequential handoff review flow.', - mode: 'sequential', - availability: 'available', - maxIterations: 1, - agents: [ - { - id: 'agent-writer', - name: 'Writer', - description: 'Writes the draft.', - instructions: 'Write.', - model: 'gpt-5.4', - }, - { - id: 'agent-reviewer', - name: 'Reviewer', - description: 'Reviews the draft.', - instructions: 'Review.', - model: 'claude-sonnet-4.5', - }, - ], + graph: { + nodes: [ + { id: 'start', kind: 'start', label: 'Start', position: { x: 0, y: 0 }, config: { kind: 'start' } }, + { + id: 'agent-writer', + kind: 'agent', + label: 'Writer', + position: { x: 200, y: 0 }, + order: 0, + config: { + kind: 'agent', + id: 'agent-writer', + name: 'Writer', + description: 'Writes the draft.', + instructions: 'Write.', + model: 'gpt-5.4', + }, + }, + { + id: 'agent-reviewer', + kind: 'agent', + label: 'Reviewer', + position: { x: 400, y: 0 }, + order: 1, + config: { + kind: 'agent', + id: 'agent-reviewer', + name: 'Reviewer', + description: 'Reviews the draft.', + instructions: 'Review.', + model: 'claude-sonnet-4.5', + }, + }, + { id: 'end', kind: 'end', label: 'End', position: { x: 600, y: 0 }, config: { kind: 'end' } }, + ], + edges: [ + { id: 'edge-start-writer', source: 'start', target: 'agent-writer', kind: 'direct' }, + { id: 'edge-writer-reviewer', source: 'agent-writer', target: 'agent-reviewer', kind: 'direct' }, + { id: 'edge-reviewer-end', source: 'agent-reviewer', target: 'end', kind: 'direct' }, + ], + }, + settings: { + checkpointing: { enabled: false }, + executionMode: 'off-thread', + orchestrationMode: 'sequential', + maxIterations: 1, + }, createdAt: '2026-03-23T00:00:00.000Z', updatedAt: '2026-03-23T00:00:00.000Z', }; @@ -57,7 +85,7 @@ describe('run timeline helpers', () => { project: createProject(), workingDirectory: 'C:\\workspace\\alpha\\packages\\app', workspaceKind: 'project', - pattern: createPattern(), + workflow: createWorkflow(), triggerMessageId: 'msg-user-1', startedAt: '2026-03-23T00:00:01.000Z', preRunGitBaselineFiles: [ @@ -73,9 +101,9 @@ describe('run timeline helpers', () => { projectId: 'project-1', projectPath: 'C:\\workspace\\alpha', workingDirectory: 'C:\\workspace\\alpha\\packages\\app', - patternId: 'pattern-sequential', - patternName: 'Sequential Trio Review', - patternMode: 'sequential', + workflowId: 'workflow-sequential', + workflowName: 'Sequential Trio Review', + workflowMode: 'sequential', triggerMessageId: 'msg-user-1', status: 'running', }); @@ -112,7 +140,7 @@ describe('run timeline helpers', () => { requestId: 'turn-1', project: createProject(), workspaceKind: 'project', - pattern: createPattern(), + workflow: createWorkflow(), triggerMessageId: 'msg-user-1', startedAt: '2026-03-23T00:00:01.000Z', }); @@ -159,7 +187,7 @@ describe('run timeline helpers', () => { requestId: 'turn-1', project: createProject(), workspaceKind: 'project', - pattern: createPattern(), + workflow: createWorkflow(), triggerMessageId: 'msg-user-1', startedAt: '2026-03-23T00:00:01.000Z', }), @@ -187,7 +215,7 @@ describe('run timeline helpers', () => { requestId: 'turn-1', project: createProject(), workspaceKind: 'project', - pattern: createPattern(), + workflow: createWorkflow(), triggerMessageId: 'msg-user-1', startedAt: '2026-03-23T00:00:01.000Z', }); @@ -242,7 +270,7 @@ describe('run timeline helpers', () => { requestId: 'turn-1', project: createProject(), workspaceKind: 'project', - pattern: createPattern(), + workflow: createWorkflow(), triggerMessageId: 'msg-user-1', startedAt: '2026-03-23T00:00:01.000Z', }); diff --git a/tests/shared/session.test.ts b/tests/shared/session.test.ts index 9676cba..39279bb 100644 --- a/tests/shared/session.test.ts +++ b/tests/shared/session.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; import { applySessionApprovalSettings, applySessionModelConfig, @@ -12,42 +12,70 @@ import { type SessionRecord, } from '@shared/domain/session'; -function createPattern(): PatternDefinition { +function createWorkflow(): WorkflowDefinition { return { - id: 'pattern-single', + id: 'workflow-single', name: '1-on-1 Copilot Chat', description: 'Single agent chat', - mode: 'single', - availability: 'available', - maxIterations: 1, - agents: [ - { - id: 'agent-primary', - name: 'Primary Agent', - description: 'Helpful assistant', - instructions: 'Help the user.', - model: 'gpt-5.4', - reasoningEffort: 'high', - }, - { - id: 'agent-secondary', - name: 'Secondary Agent', - description: 'Unused here', - instructions: 'Review.', - model: 'claude-sonnet-4.5', - reasoningEffort: 'medium', - }, - ], + graph: { + nodes: [ + { id: 'start', kind: 'start', label: 'Start', position: { x: 0, y: 0 }, config: { kind: 'start' } }, + { + id: 'agent-primary-node', + kind: 'agent', + label: 'Primary Agent', + position: { x: 200, y: 0 }, + order: 0, + config: { + kind: 'agent', + id: 'agent-primary', + name: 'Primary Agent', + description: 'Helpful assistant', + instructions: 'Help the user.', + model: 'gpt-5.4', + reasoningEffort: 'high', + }, + }, + { + id: 'agent-secondary-node', + kind: 'agent', + label: 'Secondary Agent', + position: { x: 400, y: 0 }, + order: 1, + config: { + kind: 'agent', + id: 'agent-secondary', + name: 'Secondary Agent', + description: 'Unused here', + instructions: 'Review.', + model: 'claude-sonnet-4.5', + reasoningEffort: 'medium', + }, + }, + { id: 'end', kind: 'end', label: 'End', position: { x: 600, y: 0 }, config: { kind: 'end' } }, + ], + edges: [ + { id: 'edge-start-primary', source: 'start', target: 'agent-primary-node', kind: 'direct' }, + { id: 'edge-primary-secondary', source: 'agent-primary-node', target: 'agent-secondary-node', kind: 'direct' }, + { id: 'edge-secondary-end', source: 'agent-secondary-node', target: 'end', kind: 'direct' }, + ], + }, + settings: { + checkpointing: { enabled: false }, + executionMode: 'off-thread', + orchestrationMode: 'single', + maxIterations: 1, + }, createdAt: '2026-03-23T00:00:00.000Z', updatedAt: '2026-03-23T00:00:00.000Z', }; } function createSession(overrides?: Partial): SessionRecord { - return { - id: 'session-1', - projectId: 'project-scratchpad', - patternId: 'pattern-single', + return { + id: 'session-1', + projectId: 'project-scratchpad', + workflowId: 'workflow-single', title: 'Scratchpad', createdAt: '2026-03-23T00:00:00.000Z', updatedAt: '2026-03-23T00:00:00.000Z', @@ -60,13 +88,13 @@ function createSession(overrides?: Partial): SessionRecord { describe('session model config helpers', () => { test('captures the initial model settings from the primary agent', () => { - expect(createSessionModelConfig(createPattern())).toEqual({ + expect(createSessionModelConfig(createWorkflow())).toEqual({ model: 'gpt-5.4', reasoningEffort: 'high', }); }); - test('resolves persisted session overrides over the pattern defaults', () => { + test('resolves persisted session overrides over the workflow defaults', () => { const config = resolveSessionModelConfig( createSession({ sessionModelConfig: { @@ -74,7 +102,7 @@ describe('session model config helpers', () => { reasoningEffort: 'medium', }, }), - createPattern(), + createWorkflow(), ); expect(config).toEqual({ @@ -84,9 +112,9 @@ describe('session model config helpers', () => { }); test('applies session model settings only to the primary agent', () => { - const pattern = createPattern(); + const workflow = createWorkflow(); const updated = applySessionModelConfig( - pattern, + workflow, createSession({ sessionModelConfig: { model: 'gpt-5.4-mini', @@ -95,22 +123,25 @@ describe('session model config helpers', () => { }), ); - expect(updated.agents[0].model).toBe('gpt-5.4-mini'); - expect(updated.agents[0].reasoningEffort).toBe('low'); - expect(updated.agents[1]).toEqual(pattern.agents[1]); + const primaryAgent = updated.graph.nodes[1]; + const secondaryAgent = updated.graph.nodes[2]; + const originalSecondaryAgent = workflow.graph.nodes[2]; + expect(primaryAgent?.config.kind === 'agent' ? primaryAgent.config.model : undefined).toBe('gpt-5.4-mini'); + expect(primaryAgent?.config.kind === 'agent' ? primaryAgent.config.reasoningEffort : undefined).toBe('low'); + expect(secondaryAgent).toEqual(originalSecondaryAgent); }); }); describe('session title helpers', () => { test('keeps a manual title instead of recomputing it from the first user message', () => { - const pattern = createPattern(); + const workflow = createWorkflow(); const session = createSession({ title: 'Release readiness review', titleSource: 'manual', }); expect( - resolveSessionTitle(session, pattern, [ + resolveSessionTitle(session, workflow, [ { id: 'msg-1', role: 'user', @@ -123,11 +154,11 @@ describe('session title helpers', () => { }); test('builds auto titles from markdown-heavy first messages', () => { - const pattern = createPattern(); + const workflow = createWorkflow(); const session = createSession(); expect( - resolveSessionTitle(session, pattern, [ + resolveSessionTitle(session, workflow, [ { id: 'msg-1', role: 'user', @@ -164,25 +195,28 @@ describe('session tooling helpers', () => { }); describe('session approval helpers', () => { - test('normalizes session approval overrides and applies them over pattern defaults', () => { - const pattern = { - ...createPattern(), - approvalPolicy: { - rules: [{ kind: 'tool-call' as const }], - autoApprovedToolNames: ['git.status'], + test('normalizes session approval overrides and applies them over workflow defaults', () => { + const workflow = { + ...createWorkflow(), + settings: { + ...createWorkflow().settings, + approvalPolicy: { + rules: [{ kind: 'tool-call' as const }], + autoApprovedToolNames: ['git.status'], + }, }, }; expect(resolveSessionApprovalSettings(createSession())).toBeUndefined(); expect( - applySessionApprovalSettings( - pattern, - createSession({ + applySessionApprovalSettings( + workflow, + createSession({ approvalSettings: { autoApprovedToolNames: ['git.diff', ' git.diff '], }, }), - ).approvalPolicy, + ).settings.approvalPolicy, ).toEqual({ rules: [{ kind: 'tool-call' }], autoApprovedToolNames: ['git.diff'], diff --git a/tests/shared/sessionLibrary.test.ts b/tests/shared/sessionLibrary.test.ts index 9c41401..032b2cf 100644 --- a/tests/shared/sessionLibrary.test.ts +++ b/tests/shared/sessionLibrary.test.ts @@ -9,30 +9,49 @@ import { renameSessionRecord, setSessionMessagePinnedRecord, } from '@shared/domain/sessionLibrary'; -import type { PatternDefinition } from '@shared/domain/pattern'; +import type { WorkflowDefinition } from '@shared/domain/workflow'; import type { ProjectRecord } from '@shared/domain/project'; import type { SessionRecord } from '@shared/domain/session'; import { createWorkspaceSettings } from '@shared/domain/tooling'; import type { WorkspaceState } from '@shared/domain/workspace'; -function createPattern(overrides?: Partial): PatternDefinition { +function createWorkflow(overrides?: Partial): WorkflowDefinition { return { - id: 'pattern-sequential-review', + id: 'workflow-sequential-review', name: 'Sequential Review', description: 'Multi-agent review workflow.', - mode: 'sequential', - availability: 'available', - maxIterations: 1, - agents: [ - { - id: 'agent-analyst', - name: 'Analyst', - description: 'Reviews the request and finds issues.', - instructions: 'Analyze the request.', - model: 'gpt-5.4', - reasoningEffort: 'high', - }, - ], + graph: { + nodes: [ + { id: 'start', kind: 'start', label: 'Start', position: { x: 0, y: 0 }, config: { kind: 'start' } }, + { + id: 'agent-analyst-node', + kind: 'agent', + label: 'Analyst', + position: { x: 200, y: 0 }, + order: 0, + config: { + kind: 'agent', + id: 'agent-analyst', + name: 'Analyst', + description: 'Reviews the request and finds issues.', + instructions: 'Analyze the request.', + model: 'gpt-5.4', + reasoningEffort: 'high', + }, + }, + { id: 'end', kind: 'end', label: 'End', position: { x: 400, y: 0 }, config: { kind: 'end' } }, + ], + edges: [ + { id: 'edge-start-agent', source: 'start', target: 'agent-analyst-node', kind: 'direct' }, + { id: 'edge-agent-end', source: 'agent-analyst-node', target: 'end', kind: 'direct' }, + ], + }, + settings: { + checkpointing: { enabled: false }, + executionMode: 'off-thread', + orchestrationMode: 'sequential', + maxIterations: 1, + }, createdAt: '2026-03-23T00:00:00.000Z', updatedAt: '2026-03-23T00:00:00.000Z', ...overrides, @@ -53,7 +72,7 @@ function createSession(overrides?: Partial): SessionRecord { return { id: 'session-1', projectId: 'project-alpha', - patternId: 'pattern-sequential-review', + workflowId: 'workflow-sequential-review', title: 'Investigate Copilot refresh bug', createdAt: '2026-03-23T00:00:00.000Z', updatedAt: '2026-03-23T00:05:00.000Z', @@ -75,8 +94,7 @@ function createSession(overrides?: Partial): SessionRecord { function createWorkspace(overrides?: Partial): WorkspaceState { const workspace: WorkspaceState = { projects: [createProject(), createProject({ id: 'project-scratchpad', name: 'Scratchpad', path: 'C:\\scratchpad' })], - patterns: [createPattern(), createPattern({ id: 'pattern-single-chat', name: '1-on-1 Copilot Chat', mode: 'single' })], - workflows: [], + workflows: [createWorkflow(), createWorkflow({ id: 'workflow-single-chat', name: '1-on-1 Copilot Chat', settings: { checkpointing: { enabled: false }, executionMode: 'off-thread', orchestrationMode: 'single', maxIterations: 1 } })], workflowTemplates: [], settings: createWorkspaceSettings(), sessions: [ @@ -84,7 +102,7 @@ function createWorkspace(overrides?: Partial): WorkspaceState { createSession({ id: 'session-2', projectId: 'project-scratchpad', - patternId: 'pattern-single-chat', + workflowId: 'workflow-single-chat', title: 'Scratchpad brainstorm', status: 'running', updatedAt: '2026-03-23T00:10:00.000Z', @@ -109,7 +127,7 @@ function createWorkspace(overrides?: Partial): WorkspaceState { }), ], selectedProjectId: 'project-alpha', - selectedPatternId: 'pattern-sequential-review', + selectedWorkflowId: 'workflow-sequential-review', selectedSessionId: 'session-1', lastUpdatedAt: '2026-03-23T00:10:00.000Z', ...overrides, @@ -291,7 +309,7 @@ describe('session library helpers', () => { const branch = branchSessionRecord( sourceSession, - createPattern(), + createWorkflow(), 'session-branch', 'msg-3', '2026-03-23T00:04:00.000Z', @@ -341,7 +359,7 @@ describe('session library helpers', () => { expect(() => branchSessionRecord( sourceSession, - createPattern(), + createWorkflow(), 'session-branch', 'msg-1', '2026-03-23T00:04:00.000Z', @@ -384,7 +402,7 @@ describe('session library helpers', () => { const branch = branchSessionRecord( sourceSession, - createPattern(), + createWorkflow(), 'session-branch', 'msg-2', '2026-03-23T00:05:00.000Z', @@ -436,7 +454,7 @@ describe('session library helpers', () => { const regenerated = regenerateSessionRecord( sourceSession, - createPattern(), + createWorkflow(), 'session-regenerated', 'msg-4', '2026-03-23T00:06:00.000Z', @@ -483,7 +501,7 @@ describe('session library helpers', () => { expect(() => regenerateSessionRecord( sourceSession, - createPattern(), + createWorkflow(), 'session-regenerated', 'msg-2', '2026-03-23T00:06:00.000Z', @@ -541,7 +559,7 @@ describe('session library helpers', () => { const edited = editAndResendSessionRecord( sourceSession, - createPattern(), + createWorkflow(), 'session-edited', 'msg-3', 'Focus on session state only.', @@ -585,7 +603,7 @@ describe('session library helpers', () => { { sessionId: 'session-1', score: 31, - matchedFields: ['title', 'message', 'project', 'pattern'], + matchedFields: ['title', 'message', 'project', 'workflow'], }, ]); }); diff --git a/tests/shared/workflow.test.ts b/tests/shared/workflow.test.ts index 89806dc..efa1ee2 100644 --- a/tests/shared/workflow.test.ts +++ b/tests/shared/workflow.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from 'bun:test'; import { - buildWorkflowExecutionPattern, + buildWorkflowExecutionDefinition, validateWorkflowDefinition, type WorkflowDefinition, } from '@shared/domain/workflow'; @@ -245,16 +245,16 @@ describe('workflow validation', () => { expect(issues.some((issue) => issue.message.includes('exactly one of workflowId or inlineWorkflow'))).toBe(true); }); - test('builds a synthetic execution pattern from workflow agents', () => { - const pattern = buildWorkflowExecutionPattern(createWorkflow()); + test('builds an execution definition from workflow agents', () => { + const execution = buildWorkflowExecutionDefinition(createWorkflow()); - expect(pattern.id).toBe('workflow-1'); - expect(pattern.agents).toHaveLength(1); - expect(pattern.agents[0]?.name).toBe('Primary Agent'); - expect(pattern.graph?.nodes.map((node) => node.kind)).toEqual(['user-input', 'agent', 'user-output']); + expect(execution.id).toBe('workflow-1'); + expect(execution.agents).toHaveLength(1); + expect(execution.agents[0]?.name).toBe('Primary Agent'); + expect(execution.orchestrationMode).toBe('single'); }); - test('includes referenced sub-workflow agents when building execution patterns', () => { + test('includes referenced sub-workflow agents when building execution definitions', () => { const childWorkflow = createReferencedSubWorkflow(); const workflow = createWorkflow(); workflow.graph.nodes[1] = { @@ -270,12 +270,12 @@ describe('workflow validation', () => { workflow.graph.edges[0] = { id: 'edge-start-sub', source: 'start', target: 'sub-workflow', kind: 'direct' }; workflow.graph.edges[1] = { id: 'edge-sub-end', source: 'sub-workflow', target: 'end', kind: 'direct' }; - const pattern = buildWorkflowExecutionPattern(workflow, { - resolveWorkflow: (workflowId) => workflowId === childWorkflow.id ? childWorkflow : undefined, + const execution = buildWorkflowExecutionDefinition(workflow, { + resolveWorkflow: (workflowId: string) => workflowId === childWorkflow.id ? childWorkflow : undefined, }); - expect(pattern.mode).toBe('single'); - expect(pattern.agents.map((agent) => agent.id)).toEqual(['agent-reviewer']); + expect(execution.orchestrationMode).toBe('single'); + expect(execution.agents.map((agent) => agent.id)).toEqual(['agent-reviewer']); }); test('accepts simple property and expression conditions', () => { diff --git a/tests/shared/workflowTemplate.test.ts b/tests/shared/workflowTemplate.test.ts deleted file mode 100644 index d8734ac..0000000 --- a/tests/shared/workflowTemplate.test.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { describe, expect, test } from 'bun:test'; - -import { createBuiltinPatterns } from '@shared/domain/pattern'; -import { - exportWorkflowDefinition, - importWorkflowDefinition, -} from '@shared/domain/workflowSerialization'; -import { - buildWorkflowFromPattern, - createBuiltinWorkflowTemplates, -} from '@shared/domain/workflowTemplate'; -import { validateWorkflowDefinition } from '@shared/domain/workflow'; - -const TIMESTAMP = '2026-04-05T00:00:00.000Z'; - -function requirePattern(mode: 'sequential' | 'concurrent' | 'handoff' | 'group-chat') { - const pattern = createBuiltinPatterns(TIMESTAMP).find((candidate) => candidate.mode === mode); - if (!pattern) { - throw new Error(`Expected built-in ${mode} pattern.`); - } - - return pattern; -} - -describe('workflow templates', () => { - test('builds a valid sequential workflow from a pattern', () => { - const workflow = buildWorkflowFromPattern(requirePattern('sequential')); - - expect(workflow.id).toBe('workflow-sequential-review'); - expect(workflow.graph.nodes.map((node) => node.kind)).toEqual(['start', 'agent', 'agent', 'agent', 'end']); - expect(workflow.graph.edges.map((edge) => `${edge.source}->${edge.target}:${edge.kind}`)).toEqual([ - 'start->agent-node-agent-sequential-analyst:direct', - 'agent-node-agent-sequential-analyst->agent-node-agent-sequential-builder:direct', - 'agent-node-agent-sequential-builder->agent-node-agent-sequential-reviewer:direct', - 'agent-node-agent-sequential-reviewer->end:direct', - ]); - expect(validateWorkflowDefinition(workflow)).toEqual([]); - }); - - test('builds a valid concurrent workflow from a pattern', () => { - const workflow = buildWorkflowFromPattern(requirePattern('concurrent')); - - expect(workflow.graph.edges.filter((edge) => edge.kind === 'fan-out')).toHaveLength(3); - expect(workflow.graph.edges.filter((edge) => edge.kind === 'fan-in')).toHaveLength(3); - expect(validateWorkflowDefinition(workflow)).toEqual([]); - }); - - test('builds a valid handoff workflow from a pattern graph', () => { - const workflow = buildWorkflowFromPattern(requirePattern('handoff')); - - expect(workflow.graph.edges.map((edge) => `${edge.source}->${edge.target}`)).toContain('start->agent-node-agent-handoff-triage'); - expect(workflow.graph.edges.map((edge) => `${edge.source}->${edge.target}`)).toContain( - 'agent-node-agent-handoff-triage->agent-node-agent-handoff-ux', - ); - expect(workflow.graph.edges.map((edge) => `${edge.source}->${edge.target}`)).toContain( - 'agent-node-agent-handoff-runtime->agent-node-agent-handoff-triage', - ); - expect(validateWorkflowDefinition(workflow)).toEqual([]); - }); - - test('builds a group-chat workflow with a loop approximation', () => { - const workflow = buildWorkflowFromPattern(requirePattern('group-chat')); - const loopEdge = workflow.graph.edges.find((edge) => - edge.source === 'agent-node-agent-group-reviewer' && edge.target === 'agent-node-agent-group-writer'); - const entryEdge = workflow.graph.edges.find((edge) => - edge.source === 'start' && edge.target === 'agent-node-agent-group-writer'); - const exitEdge = workflow.graph.edges.find((edge) => - edge.source === 'agent-node-agent-group-reviewer' && edge.target === 'end'); - - expect(loopEdge).toEqual(expect.objectContaining({ - source: 'agent-node-agent-group-reviewer', - target: 'agent-node-agent-group-writer', - isLoop: true, - maxIterations: 5, - condition: { type: 'always' }, - })); - expect(entryEdge?.isLoop).not.toBe(true); - expect(exitEdge?.isLoop).not.toBe(true); - expect(validateWorkflowDefinition(workflow)).toEqual([]); - }); - - test('creates 8 hand-crafted builtin workflow templates', () => { - const templates = createBuiltinWorkflowTemplates(TIMESTAMP); - - expect(templates).toHaveLength(8); - expect(templates.map((template) => template.id)).toEqual([ - 'workflow-template-code-review', - 'workflow-template-research-summarize', - 'workflow-template-customer-support', - 'workflow-template-content-creation', - 'workflow-template-multi-agent-debate', - 'workflow-template-data-processing', - 'workflow-template-approval', - 'workflow-template-nested-orchestrator', - ]); - expect(templates.every((template) => template.source === 'builtin')).toBe(true); - }); - - test('builtin templates span all categories', () => { - const templates = createBuiltinWorkflowTemplates(TIMESTAMP); - const categories = new Set(templates.map((template) => template.category)); - - expect(categories).toContain('orchestration'); - expect(categories).toContain('data-pipeline'); - expect(categories).toContain('human-in-loop'); - }); - - test('builtin templates produce valid workflows', () => { - const templates = createBuiltinWorkflowTemplates(TIMESTAMP); - - for (const template of templates) { - const issues = validateWorkflowDefinition(template.workflow); - expect(issues.filter((issue) => issue.level === 'error')).toEqual([]); - } - }); - - test('builtin templates use the provided timestamp', () => { - const templates = createBuiltinWorkflowTemplates(TIMESTAMP); - - for (const template of templates) { - expect(template.createdAt).toBe(TIMESTAMP); - expect(template.updatedAt).toBe(TIMESTAMP); - } - }); - - test('research-summarize template uses fan-out and fan-in edges', () => { - const templates = createBuiltinWorkflowTemplates(TIMESTAMP); - const research = templates.find((t) => t.id === 'workflow-template-research-summarize')!; - - expect(research.workflow.graph.edges.filter((e) => e.kind === 'fan-out')).toHaveLength(3); - expect(research.workflow.graph.edges.filter((e) => e.kind === 'fan-in')).toHaveLength(3); - }); - - test('content-creation template has a loop edge with maxIterations', () => { - const templates = createBuiltinWorkflowTemplates(TIMESTAMP); - const content = templates.find((t) => t.id === 'workflow-template-content-creation')!; - const loopEdge = content.workflow.graph.edges.find((e) => e.isLoop && e.source === 'editor' && e.target === 'writer'); - - expect(loopEdge).toBeDefined(); - expect(loopEdge!.maxIterations).toBe(3); - expect(loopEdge!.source).toBe('editor'); - expect(loopEdge!.target).toBe('writer'); - }); - - test('data-processing template includes invoke-function nodes', () => { - const templates = createBuiltinWorkflowTemplates(TIMESTAMP); - const dataProc = templates.find((t) => t.id === 'workflow-template-data-processing')!; - const funcNodes = dataProc.workflow.graph.nodes.filter((n) => n.kind === 'invoke-function'); - - expect(funcNodes).toHaveLength(2); - }); - - test('approval template includes a request-port node', () => { - const templates = createBuiltinWorkflowTemplates(TIMESTAMP); - const approval = templates.find((t) => t.id === 'workflow-template-approval')!; - const portNode = approval.workflow.graph.nodes.find((n) => n.kind === 'request-port'); - - expect(portNode).toBeDefined(); - expect(portNode!.config).toEqual(expect.objectContaining({ - kind: 'request-port', - portId: 'review', - requestType: 'ReviewRequest', - responseType: 'ReviewDecision', - })); - }); - - test('nested-orchestrator template includes a sub-workflow node', () => { - const templates = createBuiltinWorkflowTemplates(TIMESTAMP); - const nested = templates.find((t) => t.id === 'workflow-template-nested-orchestrator')!; - const subNode = nested.workflow.graph.nodes.find((n) => n.kind === 'sub-workflow'); - - expect(subNode).toBeDefined(); - expect(subNode!.config).toEqual(expect.objectContaining({ kind: 'sub-workflow' })); - }); - - test('round trips workflow yaml import and export', () => { - const workflow = buildWorkflowFromPattern(requirePattern('sequential')); - const exported = exportWorkflowDefinition(workflow, 'yaml'); - const imported = importWorkflowDefinition(exported.content, 'yaml'); - - expect(exported.format).toBe('yaml'); - expect(imported).toEqual(workflow); - }); - - test('exports mermaid flowcharts with expected edges', () => { - const workflow = buildWorkflowFromPattern(requirePattern('sequential')); - const exported = exportWorkflowDefinition(workflow, 'mermaid'); - - expect(exported.content.startsWith('flowchart LR')).toBe(true); - expect(exported.content).toContain('-->'); - expect(exported.content).toContain('n0 --> n1'); - }); -}); diff --git a/tests/shared/workspace.test.ts b/tests/shared/workspace.test.ts index 2bbb8fb..e2cde5e 100644 --- a/tests/shared/workspace.test.ts +++ b/tests/shared/workspace.test.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test'; import { createWorkspaceSeed } from '@shared/domain/workspace'; describe('workspace seed', () => { - test('starts empty and seeds built-in patterns and workflow templates with a shared timestamp', () => { + test('starts empty and seeds built-in workflows and workflow templates with a shared timestamp', () => { const workspace = createWorkspaceSeed(); expect(workspace.projects).toEqual([]); @@ -19,16 +19,15 @@ describe('workspace seed', () => { }, }); expect(workspace.selectedProjectId).toBeUndefined(); - expect(workspace.selectedPatternId).toBeUndefined(); + expect(workspace.selectedWorkflowId).toBeUndefined(); expect(workspace.selectedSessionId).toBeUndefined(); - expect(workspace.patterns.map((pattern) => pattern.mode)).toEqual([ + expect(workspace.workflows.map((workflow) => workflow.settings.orchestrationMode)).toEqual([ 'single', 'sequential', 'concurrent', 'handoff', 'group-chat', - 'magentic', ]); expect(workspace.workflowTemplates.map((template) => template.id)).toEqual([ 'workflow-template-code-review', @@ -41,16 +40,12 @@ describe('workspace seed', () => { 'workflow-template-nested-orchestrator', ]); - for (const pattern of workspace.patterns) { - expect(pattern.createdAt).toBe(workspace.lastUpdatedAt); - expect(pattern.updatedAt).toBe(workspace.lastUpdatedAt); - expect(pattern.approvalPolicy?.rules).toContainEqual({ kind: 'tool-call' }); + for (const workflow of workspace.workflows) { + expect(workflow.createdAt).toBe(workspace.lastUpdatedAt); + expect(workflow.updatedAt).toBe(workspace.lastUpdatedAt); + expect(workflow.settings.approvalPolicy).toBeUndefined(); } - const magentic = workspace.patterns.find((pattern) => pattern.mode === 'magentic'); - - expect(magentic?.availability).toBe('unavailable'); - expect(magentic?.unavailabilityReason).toContain('unsupported'); for (const template of workspace.workflowTemplates) { expect(template.createdAt).toBe(workspace.lastUpdatedAt); expect(template.updatedAt).toBe(workspace.lastUpdatedAt); diff --git a/tests/shared/workspaceAgent.test.ts b/tests/shared/workspaceAgent.test.ts deleted file mode 100644 index 64ee44e..0000000 --- a/tests/shared/workspaceAgent.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { describe, expect, test } from 'bun:test'; - -import { - resolvePatternAgent, - resolvePatternAgents, - findWorkspaceAgentUsages, - normalizeWorkspaceAgentDefinition, - type WorkspaceAgentDefinition, -} from '@shared/domain/workspaceAgent'; -import type { PatternAgentDefinition, PatternDefinition } from '@shared/domain/pattern'; - -const TIMESTAMP = '2026-04-01T00:00:00.000Z'; - -function makeWorkspaceAgent(overrides: Partial = {}): WorkspaceAgentDefinition { - return { - id: 'wa-1', - name: 'Code Reviewer', - description: 'Reviews code for quality', - instructions: 'Review all code carefully', - model: 'gpt-5.4', - reasoningEffort: 'high', - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - ...overrides, - }; -} - -function makeInlineAgent(overrides: Partial = {}): PatternAgentDefinition { - return { - id: 'agent-1', - name: 'Inline Agent', - description: 'An inline agent', - instructions: 'Do stuff', - model: 'claude-sonnet-4', - reasoningEffort: 'medium', - ...overrides, - }; -} - -function makeLinkedAgent(overrides: Partial = {}): PatternAgentDefinition { - return { - id: 'agent-linked', - name: 'Code Reviewer', - description: 'Reviews code for quality', - instructions: 'Review all code carefully', - model: 'gpt-5.4', - reasoningEffort: 'high', - workspaceAgentId: 'wa-1', - ...overrides, - }; -} - -function makePattern(agents: PatternAgentDefinition[], overrides: Partial = {}): PatternDefinition { - return { - id: 'pattern-1', - name: 'Test Pattern', - description: '', - mode: 'sequential', - availability: 'available', - maxIterations: 10, - agents, - createdAt: TIMESTAMP, - updatedAt: TIMESTAMP, - ...overrides, - }; -} - -describe('resolvePatternAgent', () => { - const workspaceAgents = [makeWorkspaceAgent()]; - - test('returns inline agent unchanged', () => { - const agent = makeInlineAgent(); - const resolved = resolvePatternAgent(agent, workspaceAgents); - expect(resolved).toEqual(agent); - }); - - test('resolves linked agent from workspace agent base', () => { - const agent = makeLinkedAgent(); - const resolved = resolvePatternAgent(agent, workspaceAgents); - expect(resolved.name).toBe('Code Reviewer'); - expect(resolved.model).toBe('gpt-5.4'); - expect(resolved.instructions).toBe('Review all code carefully'); - expect(resolved.workspaceAgentId).toBe('wa-1'); - expect(resolved.id).toBe('agent-linked'); - }); - - test('applies per-pattern overrides on top of workspace agent', () => { - const agent = makeLinkedAgent({ - overrides: { model: 'claude-opus-4', instructions: 'Override instructions' }, - }); - const resolved = resolvePatternAgent(agent, workspaceAgents); - expect(resolved.model).toBe('claude-opus-4'); - expect(resolved.instructions).toBe('Override instructions'); - expect(resolved.name).toBe('Code Reviewer'); - expect(resolved.description).toBe('Reviews code for quality'); - }); - - test('falls back to inline fields when workspace agent is missing', () => { - const agent = makeLinkedAgent({ workspaceAgentId: 'nonexistent' }); - const resolved = resolvePatternAgent(agent, workspaceAgents); - expect(resolved).toEqual(agent); - }); - - test('partial overrides only replace specified fields', () => { - const agent = makeLinkedAgent({ - overrides: { name: 'Custom Name' }, - }); - const resolved = resolvePatternAgent(agent, workspaceAgents); - expect(resolved.name).toBe('Custom Name'); - expect(resolved.model).toBe('gpt-5.4'); - expect(resolved.reasoningEffort).toBe('high'); - }); -}); - -describe('resolvePatternAgents', () => { - const workspaceAgents = [makeWorkspaceAgent()]; - - test('resolves all agents in a pattern', () => { - const pattern = makePattern([ - makeInlineAgent(), - makeLinkedAgent(), - ]); - const resolved = resolvePatternAgents(pattern, workspaceAgents); - expect(resolved.agents[0].name).toBe('Inline Agent'); - expect(resolved.agents[1].name).toBe('Code Reviewer'); - expect(resolved.agents[1].workspaceAgentId).toBe('wa-1'); - }); - - test('preserves pattern metadata', () => { - const pattern = makePattern([makeInlineAgent()], { id: 'p-custom', name: 'Custom' }); - const resolved = resolvePatternAgents(pattern, workspaceAgents); - expect(resolved.id).toBe('p-custom'); - expect(resolved.name).toBe('Custom'); - }); -}); - -describe('findWorkspaceAgentUsages', () => { - test('finds patterns referencing a workspace agent', () => { - const patterns = [ - makePattern([makeLinkedAgent()], { id: 'p1', name: 'Pattern 1' }), - makePattern([makeInlineAgent()], { id: 'p2', name: 'Pattern 2' }), - makePattern( - [makeInlineAgent(), makeLinkedAgent({ id: 'agent-linked-2' })], - { id: 'p3', name: 'Pattern 3' }, - ), - ]; - const usages = findWorkspaceAgentUsages('wa-1', patterns); - expect(usages).toHaveLength(2); - expect(usages[0].patternId).toBe('p1'); - expect(usages[1].patternId).toBe('p3'); - }); - - test('returns empty when no patterns reference the agent', () => { - const patterns = [makePattern([makeInlineAgent()])]; - const usages = findWorkspaceAgentUsages('wa-1', patterns); - expect(usages).toHaveLength(0); - }); -}); - -describe('normalizeWorkspaceAgentDefinition', () => { - test('trims string fields', () => { - const agent = makeWorkspaceAgent({ - name: ' Code Reviewer ', - description: ' Reviews code ', - instructions: ' Review carefully ', - model: ' gpt-5.4 ', - }); - const normalized = normalizeWorkspaceAgentDefinition(agent); - expect(normalized.name).toBe('Code Reviewer'); - expect(normalized.description).toBe('Reviews code'); - expect(normalized.instructions).toBe('Review carefully'); - expect(normalized.model).toBe('gpt-5.4'); - }); - - test('preserves non-string fields', () => { - const agent = makeWorkspaceAgent({ reasoningEffort: 'xhigh' }); - const normalized = normalizeWorkspaceAgentDefinition(agent); - expect(normalized.reasoningEffort).toBe('xhigh'); - expect(normalized.id).toBe('wa-1'); - expect(normalized.createdAt).toBe(TIMESTAMP); - }); -});