Skip to content

AI goals and orders

VlcekM edited this page Nov 24, 2026 · 3 revisions

This guide explains how code mods make characters act: adding custom AI goals, adding jobs to a character's job list, and issuing direct orders. If you are new to code mods, start with Writing code mods; for other hooks, see Code mod hooks. The full engine specification lives in docs/modding.md under "Chooser goals and jobs", "Mod jobs", and "Ordering characters".

These APIs require code-mod API 3, so set "apiVersion": 3 in meitou.json. If you are updating a mod written for API 1 or 2, see Moving from API 1 or 2.

How characters choose

Every character (both player-controlled and NPC) decides what to do using the same Kenshi priority pipeline: direct orders first, then jobs and AI goals sorted by priority tier and desire score, and finally a fallback idle task. Mods can plug in at three points:

What you want Use Who decides when it runs
Characters to want to do something, competing fairly with other AI goals A goal added to their AI data The AI chooser, based on your goal's desire score
A repeating task placed in a character's job list A job The chooser's job pass, in job-list order
A character to do something right now An order (just like a player command) Your code

The types used in this guide come from Meitou.Simulation.Ai (IChooserOwner, ChooserRegistry, IModGoal, ModGoalAsk, ModGoalStart, ModGoalEnd, ModGoals, IJobSource, DecisionCheck, TaskStart, TaskRequest, TaskSource), Meitou.Data.Gameplay.Ai (TaskType), Meitou.Simulation.Movement (SpeedMode, CharacterTask), and Meitou.Simulation.Player (OrderCheck, OrderVerdict).

A goal

1. Claim a task type ID

public const TaskType Gather = (TaskType)1000;

public void Initialize(ModContext c) => c.AddGoalType(Gather, "Gathering");

AddGoalType(TaskType type, string name) claims a task ID from 1000 upward. Only one mod can own a given ID (across both goals and jobs), though the same mod may register one ID as both a goal and a job. name is used in logs and notices.

2. Add the goal to character AI data

In your .mod file (or programmatically during the data phase), create an AI_TASK record with enum set to your claimed number, a classification (TP_URGENT, TP_NON_URGENT, or TP_FLUFF), and a targeting mode. Then add it to any goal list characters read:

  • NPCs: the role lists of their squad's AI_PACKAGE (Leader AI Goals, Squad AI Goals, Squad2 AI Goals), Slave AI Goals of the squad they obey, their race's AI Goals, or their faction's AI Goals when their squad has no AI contract.
  • Player characters: their faction's AI Goals (plus race AI Goals for animals), and their squad's AI_PACKAGE roles when the squad is autonomous (SetSquadAutonomy, see Code mod hooks).

The entry's active hours and weight work just like vanilla goals. While your goal is running, the HUD's Goal line displays the AI_TASK record's name. If your code mod is later disabled, the data record still loads cleanly and is simply never picked.

3. Register the goal with the chooser

Implement IChooserOwner on one of your tick systems:

public sealed class GatherSystem : ITickSystem, IChooserOwner
{
    public void Register(ChooserRegistry chooser) => chooser.Goal(GatherMod.Gather, new GatherGoal());
}

Register runs once per world when the world is created. Call chooser.Goal(type, goal) only for types your mod claimed. Registering an unclaimed type, another mod's type, registering the same type twice, or calling Goal outside Register throws an exception, which drops that system's registrations and stops the system with a notice.

4. Implement IModGoal

public interface IModGoal
{
    float Desire(in ModGoalAsk ask);
    bool Start(World world, in ModGoalStart ask);
    void End(World world, int slot, CharacterId id, TaskType type, ModGoalEnd why);
}

Desire

Returns how strongly the character wants to run this goal right now (0 or less means "don't run"). The chooser multiplies your return value by the list entry's tier, hours, and weight, and applies a 1.25x continuity bonus if the character is already running this goal.

Threading: Desire runs concurrently across multiple threads for many characters at once. It must be fast, deterministic, and strictly read-only. Only read from ask and from private state updated exclusively in serial phases. Never mutate anything here. If computing a desire is expensive, precompute the data in a serial phase and include it in your hashed state (IStateHashed).

ModGoalAsk is a read-only ref struct (valid only for the single call; cannot be stored or captured):

Member Description
Slot, Id, Type, Targeting The character's slot and ID, the goal type, and the AI_TASK record's targeting value.
Self The character's current tick state (ref readonly CharacterHot: position, task, alive).
Faction, Role, PlayerSide, IsAnimal Faction index, squad role list, whether it belongs to the player's faction, and whether it's an animal.
Carrying, InCombat, Orders, RunningRow Who it is carrying (CharacterId.None if none), whether it is in combat, its standing orders, and its active task row.
Running true if this goal currently owns the character.
TryPrevious(who, out state), FactionOf(who) Another character's state from the previous completed tick (false if not in the world), and its faction (-1 if not in the world).
SquadId, Leader, MemberCount, Member(k), Town, Package Squad ID, leader, members, placed town ID where its package runs (-1 if none), and active AI_PACKAGE string ID (null if none).
Relation(a, b), IsHostile(a, b) Faction relation (-100 to 100) and hostility check.
Tick, Hour, GameHours, Seed Current simulation tick, hour of day (0 to 23), total elapsed game hours, and world seed (for Rng.Hash).
Record(stringId) Looks up a merged FCS data record (null if missing). Read-only.

Start

Called serially, one character at a time in a deterministic order, on the tick your goal wins (or the next tick) while the chooser holds the character for you. ModGoalStart provides Slot, Id, Squad, Type, and Targeting.

Find your target and kick off the character's action using a task row you claimed (1000+, such as the goal's own type) and TaskSource.Goal. For example, call TaskStart.Walk(world, slot, point, SpeedMode.Walk, row, TaskSource.Goal) or ProductionSystem.SitOn.

Return true if you started the action. Your goal now holds the character, gets the continuity bonus on future ticks, and stays in control while the task runs. If you registered a task handler for that row, it will receive Start and End notifications for the task.

Return false if there is nothing to do right now. Nothing starts, and the chooser ignores this goal type for that character for the next four think periods.

End

Called serially when your goal loses control of a character (on the same tick or the next). Clean up any internal tracking you kept for that character, and leave its new task untouched. Every Start that returned true gets a matching End call with one of these reasons:

ModGoalEnd Cause
Displaced Another goal (or a player job) outscored your goal. Any task still belonging to your goal is stopped automatically. Combat goals chosen by the chooser (like Self Preservation) end your goal with this reason.
Order A direct order started on the character, or the character changed factions (e.g. recruited).
Replanned The character was knocked out, died, was picked up, received a body order, got a new AI mind, or the goal's scheduled hours ended.
Taken The character fled, entered combat via another system, was caged, or had its task replaced by another system.
Gone The character left the world.

End is not called when you finish the goal yourself with ModGoals.Done, when a goal is dropped after throwing an error, or when loading a save.

ModGoals.Holds and ModGoals.Done

Call these only from serial phases (Inputs, SlowWorld, IWorldReady, or a task handler). Calling them from Desire or any parallel phase throws an exception.

  • ModGoals.Holds(World world, int slot, TaskType type): returns true if your goal still controls the character. Always check this before advancing multi-step goal logic.
  • ModGoals.Done(World world, int slot, TaskType type): tells the chooser your goal is finished. Stops any remaining task owned by the goal and lets the character pick a new goal on its next think pass. Does not call End, and does nothing if your goal no longer holds the character.

Filtering any goal's desire

In Register, you can also call chooser.DesireFilter(IGoalDesireFilter filter) to adjust desire scores for every character and every task type (both vanilla and modded) - for example, to stop a faction from using beds or skip certain jobs.

Desire(World world, in GoalDesireAsk ask) receives the tick, character, task type, GoalDesireKind, and current desire score, and returns the adjusted desire:

GoalDesireKind What is being scored
Goal A goal from a character's AI list before list weight, crowding, and continuity are applied. Bed goals that found no available bed are skipped.
PlanStep A step inside a multi-step plan (like getting out of bed once healed). Returning 0 or less aborts that path.
Order The front of the order queue (returning 0 or less drops it) and the secondary order list.
Job An eligible job from the character's job list, passed in with desire 1 (ask.Job is its list index). Returning 0 or less skips the job.

Filters run in registration order, passing each result to the next filter, and run on any thread. Keep them fast, thread-safe, and read-only. If a filter throws or returns a non-finite number (NaN/Infinity), the engine keeps the prior score, stops calling the filter starting on the next tick, and logs the fault into the state hash. Note that raising a desire from 0 can cause the chooser to pick a goal that has no valid target when it tries to start.

Saves

Active goal ownership is not saved. When a save loads, no mod goals hold any characters and no End callbacks fire; the chooser will simply pick and Start your goal again when appropriate. If you persist your own goal state in IModSaveData, check ModGoals.Holds after loading and clear stale entries.

A job

c.AddJobType(Sweep, "Sweeping");                 // in Initialize
chooser.Jobs(GatherMod.Sweep, new SweepJobs());  // in IChooserOwner.Register

AddJobType(TaskType type, string name) claims a task ID (1000+) under the same single-owner rule as goals. name is shown in the player's Jobs panel. Register its IJobSource handler with chooser.Jobs(type, source).

To assign the job from a serial phase, add a PermaJob (from Meitou.Simulation.Production) to the character's job list (ordered highest priority first): cold.Jobs.Add(new PermaJob(type, siteId))

Jobs run for any character (player or NPC) that has a job list and has the Jobs toggle turned on. Mod jobs are saved in the character's job list; on reload, they are restored if a mod registers that type, or dropped cleanly otherwise. Removing a job from the list does not automatically cancel an in-progress task you started, so check whether the job is still present if you need to stop early.

On each job pass, the chooser walks the list in order and calls your IJobSource (k is the job's index in cold.Jobs):

IJobSource method When it runs What it should do
DecisionCheck CanRun(World world, int slot, int k) Serially in deterministic order; at most once per character per tick before choosing, and again right before Start. Read-only check returning DecisionCheck.Run (ready to start), DecisionCheck.Runs (already running this job's task), or DecisionCheck.No(why) (cannot run; pass null if no reason text is needed).
void Start(World world, int slot, int k) After CanRun returns Run, on the winning tick or the next. Start the character's task using TaskStart with your claimed row (see the example below).
bool Urgent(World world, int slot, int k) Same timing as CanRun (defaults to false). Return true to evaluate this job ahead of TP_URGENT goals.
void Stop(World world, int slot, int k) When the character is running this job's task, it can no longer run, and no other job in the list can take over (defaults to no-op). Cancel the task if it won't end on its own.

If an IJobSource throws an exception, it is disabled for that world, logged with your mod ID, shown to the player as a notice, and recorded in the state hash.

Letting the player give the job

Call c.AddJobOffer(new ModJobOffer(type, buildings, caption, takers)) in Initialize (after AddJobType, one offer per job type). This adds caption to the bottom of the right-click menu on any completed player-faction building matching one of the BUILDING records in buildings, whenever the current selection includes an allowed character (ModJobTakers.People, Animals, or both).

Clicking the option assigns the job at that building to each eligible selected character. If a character already has a job of that type, it updates to the new building while keeping its spot in the job list.

Workplace slots

Mod-assigned workers don't claim vanilla operator slots at town or outpost workplaces. Before hiring a character for a workplace job, check AiSystem.WorkSlots(building) (pass a town building's TownBuilding.Key or an outpost machine's site ID). It returns WorkplaceSlots(Held, Max) with a Free count as of the last package pass, or null if the AI doesn't treat that building as a workplace. Read-only, serial phases only.

An order

OrderCheck check = world.GiveOrder(npc, TaskType.MoveCusOrdered, point: new Vector3(100, 0, 100));
public OrderCheck GiveOrder(CharacterId actor, TaskType row, CharacterId? target = null, string? site = null, Vector3 point = default,
    bool queued = false)

GiveOrder sends a direct order to a player character or NPC through the exact same order queue used by player right-click commands.

Parameter Meaning
actor Target character (player or NPC).
row A built-in order task type (move, attack, pick up, etc.). Custom mod task rows cannot be passed here. Use TaskType.MoveCusOrdered with point for a standard move command.
target Target character or body (null if none).
site Target building or fixture ID (null if none).
point Target world position.
queued true appends to the queue (like Shift-clicking); false replaces the current queue.

GiveOrder returns an OrderCheck (Verdict, Why, CanRun). If the order is alone in the queue and the character can accept orders immediately, Verdict reports the start check: OrderVerdict.Run, Blocked (with the player-facing reason in Why), or Gone (dropped from the queue). Otherwise it returns Run while waiting in the queue. Invalid actors or non-order task rows return Gone without queuing anything.

NPCs only execute orders while their AI is actively running them (they belong to a squad and aren't carried, unconscious, or dead); otherwise the order waits in the queue. Starting an order displaces any active mod goal (ModGoalEnd.Order), and normal AI resumes once the order queue empties.

Call GiveOrder only from serial phases (Inputs, SlowWorld, IWorldReady); calling it in a parallel phase throws.

A worked example

This example registers a Gather goal that walks characters to a point and releases them once they arrive, a Sweep job, and a helper that issues a direct move order. The companion .mod file defines an AI_TASK named Gathering with enum set to 1000 and adds it to an AI_PACKAGE role list.

using System.Numerics;
using Meitou.Data.Gameplay.Ai;
using Meitou.Modding;
using Meitou.Simulation;
using Meitou.Simulation.Ai;
using Meitou.Simulation.Movement;
using Meitou.Simulation.Player;

namespace Gathering;

public sealed class GatherMod : IMod
{
    public const TaskType Gather = (TaskType)1000;
    public const TaskType Sweep = (TaskType)1001;

    public void Initialize(ModContext c)
    {
        c.AddGoalType(Gather, "Gathering");
        c.AddJobType(Sweep, "Sweeping");
        c.AddSystem("gather", _ => new GatherSystem(), SystemAnchor.End);
    }
}

public sealed class GatherSystem : ITickSystem, IChooserOwner
{
    public void Register(ChooserRegistry chooser)
    {
        chooser.Goal(GatherMod.Gather, new GatherGoal());
        chooser.Jobs(GatherMod.Sweep, new SweepJobs());
    }

    // Serial phase: release characters from the goal once they arrive.
    public void SlowWorld(World world)
    {
        var table = world.Characters;
        for (int s = 0; s < table.HighWater; s++)
        {
            if (!table.Next[s].Alive || !ModGoals.Holds(world, s, GatherMod.Gather)) continue;
            if (GatherGoal.AtSpot(table.Next[s].Position)) ModGoals.Done(world, s, GatherMod.Gather);
        }
    }

    // Serial phase: issue a standard move order.
    public static OrderCheck SendTo(World world, CharacterId who, Vector3 point) =>
        world.GiveOrder(who, TaskType.MoveCusOrdered, point: point);
}

public sealed class GatherGoal : IModGoal
{
    public static readonly Vector2 Spot = new(100, 100);

    public static bool AtSpot(Vector3 p) => Vector2.Distance(new Vector2(p.X, p.Z), Spot) < 50;

    // Runs concurrently on multiple threads: read from ask only.
    public float Desire(in ModGoalAsk ask)
    {
        if (ask.InCombat || ask.Carrying != CharacterId.None) return 0;
        if (ask.Running) return 1;

        return AtSpot(ask.Self.Position) ? 0 : 0.6f;
    }

    public bool Start(World world, in ModGoalStart ask) =>
        TaskStart.Walk(world, ask.Slot, Spot, SpeedMode.Walk, GatherMod.Gather, TaskSource.Goal) == StartResult.Started;

    public void End(World world, int slot, CharacterId id, TaskType type, ModGoalEnd why) { }
}

public sealed class SweepJobs : IJobSource
{
    public DecisionCheck CanRun(World world, int slot, int k)
    {
        ref var self = ref world.Characters.Next[slot];
        if (GatherGoal.AtSpot(self.Position)) return DecisionCheck.No(null);

        // Check if the character is already walking for this job.
        var run = world.Characters.Cold(slot)?.Running;
        if (run is { Source: TaskSource.Job, Row: GatherMod.Sweep } && run.Job == k && run.Runs((CharacterTask)self.Task)) return DecisionCheck.Runs;

        return DecisionCheck.Run;
    }

    // Start a walk tagged as job index k.
    public void Start(World world, int slot, int k)
    {
        var walk = new TaskRequest(CharacterTask.GoTo, GatherMod.Sweep, TaskSource.Job)
        {
            Goal = GatherGoal.Spot,
            Mode = SpeedMode.Walk,
            Job = k,
        };
        TaskStart.Start(world, slot, walk);
    }
}

Remember to set "apiVersion": 3 in meitou.json.

Faults

  • If Desire throws or returns a non-finite number (NaN or infinity), other threads may still call it for the remainder of that tick, but it is disabled from the next tick onward and no new starts are attempted. If Start or End throws, the goal is stopped immediately.
  • The first fault is logged with your mod ID and goal type, displayed as a notice to the player, and recorded in the world state hash.
  • When a goal faults (or its owning system is stopped), Meitou drops it completely: your callbacks won't run again, any characters held by the goal are released without calling End or task handlers (stopping active walks), and they choose a new task normally.
  • Faulting IJobSource handlers are dropped the same way (see A job).

Always verify determinism using meitou-tools mod-check on a busy save (64+ characters). It compares single-threaded and multi-threaded runs tick by tick using the world hash, so make sure any custom state read by Desire is hashed via IStateHashed. See Determinism check for details.

Platoons off screen

PopulationSystem.HoldPlatoon(World world, int platoon, bool held) and PopulationSystem.SendPlatoon(World world, int platoon, Vector2? point) (or SendPlatoon(world, platoon, CharacterId follow)) control a platoon's off-screen stand-in:

  • While held, the engine stops assigning roaming trips to the platoon. Its stand-in stays put until you call SendPlatoon to route it along roads toward a point or a living character (pass null to stop it).
  • HoldPlatoon returns false for unknown platoons, town garrisons, active campaigns, or platoons already held under another mod's name. SendPlatoon returns false if the platoon isn't held, is held by another mod, or if the target point/character is invalid.
  • Unnamed holds are not saved. Tag your platoon (Platoon.ModTags[c.Id]), locate it after loading via world.Platoons.FindByTag(c.Id, tag), and re-hold it in IWorldReady.

Named holds (saved): pass your mod ID with HoldPlatoon(world, platoon, c.Id, held) and SendPlatoon(world, platoon, c.Id, pointOrCharacter). Only your mod can direct or release the platoon, and no other mod can hijack it. Both the hold and its destination are saved whenever the platoon itself is saved (mod spawns, campaigns, and previously spawned squads; unvisited roaming town stand-ins aren't saved). If you sent the platoon after a character that has a lasting ID (world.LastingIds), it resumes following that character after a reload. Loading the save without your mod releases the hold automatically.

Platoon events: implement IPlatoonObserver on a system to receive PlatoonChanged(World, in PlatoonNotice) once per tick for Added, Removed (with cause: despawned, lost a fight, no members, or removed by a mod), Loaded, Unloaded, and Arrived (when a held stand-in reaches your destination). You can safely call PopulationSystem's serial APIs (spawn, hold, send, despawn) from this callback.

Other platoon hooks: population.DespawnPlatoon(world, platoon) permanently removes a non-town, non-player platoon; SpawnPlatoon(..., maxMembers) caps a squad's size; IRemovalVeto stops the engine from despawning a platoon; IOffscreenFightRule controls off-screen combat; and PopulationSystem.Data.Roads exposes the off-screen road graph. See Code mod hooks.

Once a platoon loads on-screen, its characters run their AI packages normally. To steer a loaded squad, use direct orders (World.GiveOrder - followers automatically follow an ordered leader), custom goals in its package, or swap packages with ChangeAi, StartContract, or SetSquadPackages. Player-faction squads can also use custom squad AI flags (SetSquadOptions: sit when idle, sleep when injured, share food, etc.) instead of the player's global toggles.

Moving from API 1 or 2

Meitou now runs code-mod API 3. Existing API 1 and 2 mods still load unchanged. If an older mod tries to call a hook that API 3 removed, it won't crash the game: as soon as the runtime attempts to bind the removed member (at load time, in a factory, or on first call), Meitou stops just that part, continues the game, and shows one notice for the session:

Mod <mod> was built for another version of the game and needs an update; it is stopped and the rest of the game goes on.

Here is how to migrate removed hooks to API 3:

Old API 1/2 hook API 3 replacement
IDecisionOwner + DecisionSystem.Register(source) (IDecisionSource) Use a goal (ChooserRegistry.Goal) or an order (World.GiveOrder). IDecisionSource, DecisionStep, DecisionSystem.Sources, and JobSourceOf are now internal.
DecisionSystem.RegisterJob(type, source) ChooserRegistry.Jobs(type, source) with an IJobSource.
INpcGoalOwner.RegisterGoals(NpcGoals) with Register(type, goal) IChooserOwner.Register with ChooserRegistry.Goal(type, goal).
INpcGoal.Desire(world, in NpcGoalAsk) IModGoal.Desire(in ModGoalAsk) (still multi-threaded; read through ask).
INpcGoal.Start setting Engaged, starting a walk, and returning true IModGoal.Start starting the walk and returning true; the goal now tracks ownership automatically.
Ending a goal by stopping the task, clearing Engaged, and setting Replan ModGoals.Done(world, slot, type).
Manually releasing characters for combat No longer needed; End(Displaced) or End(Taken) fires automatically.
Setting CharacterCold.Engaged to keep AI off a character while moving it Issue an order (world.GiveOrder(id, TaskType.MoveCusOrdered, point: p)) or use a goal; either holds the character automatically.
Taking package members for a goal from a serial step (duties) Add your goal to the package's role list and let the chooser pick it.
HoldPlatoon to override a loaded platoon's routine HoldPlatoon now controls off-screen stand-ins only (see Platoons off screen).
AiMind.ModGoalAsk, ModGoalStarted, ModGoalRow, ModGoalTick, ModGoalBackoff, AiBehaviour.Mod ModGoals.Holds(world, slot, type).
AiMind.Engine, EngineGoals (engine minds) Removed along with engine minds; see HoldPlatoon above.
PopulationSystem.PendingTalk, AnnouncementPatience, FirstAidSettings.AutoReach, Platoon.OrderCooldown, AiMind.CaptiveOffers, LockSystem.ReleaseTimeout Removed with no replacement.
ModHost.TryTakeFactoryNotice CodeModFaults.TryTakeNotice.

Player characters now evaluate mod goals too (via faction/race lists or autonomous squad packages). Update meitou.json to "apiVersion": 3 once you use the new API so older Meitou builds refuse it cleanly with a version message.