Skip to content

Latest commit

 

History

History
117 lines (73 loc) · 25.1 KB

delegation.md

File metadata and controls

117 lines (73 loc) · 25.1 KB

Task delegation and reports

Mainloop's MCP tools create and read durable tasks through the same application service as owner task requests. They do not call owner REST or grant owner consent. PostgreSQL owns task, attempt, hierarchy, capacity and writer authority; native agent activity remains separate.

Tool scope

Main at depth zero creates supervisors. In a project it does not delegate: its delegate with a project_id, in either mode, is refused 409 project_supervisor, and it sends the work to the project's standing supervisor with supervisor_send instead (project supervisor). The refusal comes after the request-id replay, so a request stored before the rule still answers its operation. Main's delegate without a project still makes a root coordination task (the ops agent, research). Only main has project_settings, which reads or changes a project's worker limit and its supervisor's provider, model and effort for the owner. A supervisor at depth one creates direct children within its persisted project and task tree. Children at depth two and ordinary owner workspace agents cannot delegate. Discovery and direct invocation use the same exact role, depth and grant rules; each task call revalidates persisted identity and current ancestry. Missing, superseded, revoked, archived or terminal attempts cannot authenticate.

delegate accepts request_id, title, brief, mode, optional project_id, topic_id, provider_profile_id, model, effort and typed checkout. Code tasks require an owned project and checkout; coordination tasks have no repository authority. The service chooses role, depth, owner, root and native configuration. Provider constraints and admission caps apply through the shared service. Reusing a request ID with identical input returns the original operation; changed input conflicts. A returned pending operation is not a running native session.

Cluster and homelab ops requests go to the ops agent: a coordination task on the ops provider profile. Household and personal requests (Home Assistant, OpenCozy, Gmail, Calendar, Todoist) aren't delegated: main handles them itself with its home tools and personal tools.

Reuse the request ID after a lost or uncertain response. After a confirmed terminal blocked create, a new create requires a new request ID; replaying the old ID returns the recorded blocked operation.

Choosing a worker's model and effort (#318)

TaskCreate and delegate take optional model and effort, so the supervisor — the main thread or any agent that calls delegate — can fit a worker's cost and capability to the work, rather than always starting it on its provider profile's default_model and default_effort. Both are validated at create time against the resolved profile (explicit provider_profile_id, else the project's or the installation's default): model against ProviderProfile.models, effort against .effort_levels. Either named but not offered answers 422 with a TaskError whose detail carries allowed_models or allowed_effort_levels (the profile's own list) alongside reason (model_unavailable or effort_unavailable); the delegate tool surfaces the same list in its failure text. Leaving a field unset leaves the session without an override: its turns use the owner's session default for the provider (worker for a child; supervisor, then worker, for a root task), when one is set, and otherwise the provider's own default.

A valid choice is recorded on the task and copied onto its attempt when the attempt is made, then applied as the new session's own /model//effort override (SetModelOverride/SetEffortOverride, the same storage PUT /sessions/{id}/model and /effort use — see sessions) before the attempt's first brief is sent, never by a call after the fact that could race the first turn. A resume or a re-delegation that does not name model/effort keeps the attempt's own values; naming either overrides it for the new attempt.

The delegate tool's description carries short, provider-neutral rules for the choice: weigh the task's scope, risk and reversibility, and whether it is mechanical or needs judgment; default to the cheapest model and lowest effort likely to succeed; prefer a higher tier over repeating the same one when re-delegating a failure. It names no provider's models: model and effort must be exact IDs the provider offers, and it points at list_models for them rather than letting the agent guess a name. Per-project defaults or limits (for example a maximum effort) are not in this slice.

list_models (no arguments, read-only) lists the providers a create can select, from the same provider registry and with the same checks delegate and task_reassign apply: each enabled profile that has an Agent for a task role (supervisor, a root task; child, a supervisor's task), with its provider_profile_id, display_name, aliases, roles, the exact models (id, label) and effort_levels it accepts, its default_model and default_effort, and default: true on the installation's default provider. A disabled profile, or one with no Agent for a task role, is not listed. Every actor that has delegate (main and supervisors) has it. A task's inherited provider constraint still applies to its children: the list is the providers, not the caller's tree.

Main's standing context lists its owner's projects with IDs, full repository names and whether an environment is selected. Selection does not guarantee environment readiness. This index is a snapshot when standing context is installed, not a live project query, and is not included for delegated agents.

Main's standing context also explains that tasks created directly by the owner in the app or through the owner API are owner-authored and legitimate; main reads them with task_get.

MCP-created task briefs include short role guidance before the assigned work: call whoami, read task_get, then perform the work and report. Coding guidance additionally carries what only code tasks need, since coordination tasks have none of these tools: run what get_verification says (CI runs the rest), then git push the task branch once; when the task has dev_sync, try the pushed commit on the project's staging target before opening the pull request (see devloop). It then says to open the pull request with open_pull_request, call watch_checks with reviews and end its turn, so its workspace can suspend while CI runs and one message brings the result or the feedback; after three failed rounds on one check or review to report outcome=blocked, so CI failures and unresolved reviews reach the owner only after the agent has tried; to rerun CI once with an empty commit when a test the change does not touch fails there but passes locally; with no CI, to run every check and propose a starter workflow; and to use merge_pull_request once CI is green, subject to existing policy and tool availability. If it returns approval_required, call merge_pull_request_with_approval (the owner approves in Mainloop), or report missing approval tooling as a blocker. Coordination guidance grants no repository authority. Every task brief, including the brief of a task the owner creates, then carries after the assigned work the owner's own memory when there is any (owner memory), its project's owner instructions when the project has any (project context) and its active project memory (project memory), then the shared Mainloop guidance (below); code briefs add the Workspace environment section after that. A change to the project's instructions or memory, or to owner memory, after the brief reaches the running task in front of its next message (running sessions). The assigned brief is at most 16 KiB; the sections around it are bounded on their own (instructions 8 KiB, project memory 4 KiB, owner memory 3 KiB, shared guidance 1.5 KiB; a test holds the text around the assigned work, without instructions and memory, to 3,072 bytes for a code task and 1,792 for a coordination task).

A child cannot delegate, so its brief says so: a plan, or work that needs more tasks, is reported completed with the plan in the summary for its parent supervisor to delegate, and blocked is not for work the child cannot dispatch. A coordination supervisor's brief says a child's report that holds a plan or asks for dispatch is its to act on, with model and effort left unset so the owner's session defaults apply; it goes to the owner only for an owner decision. The standing supervisor's section says the same (project supervisor). The owner's POST /tasks with mode coordination and a project is refused 409 project_supervisor like main's delegate.

task_get, task_list and task_history read stored task projections, attempts, operations and reports without creating native turns. Main reads its owner's trees; supervisors read themselves and their direct children; children read only themselves. task_transcript and transcript_search read the stored transcripts of the same tasks, also without a native turn (see transcripts). task_cancel requires the current task version and attempt and follows the existing durable cancellation service. Supervisors manage only their direct children, not themselves or another tree. Main alone also has task_hold, which sets a task aside until a time and brings it back with a message then (see tasks).

steer(task_id, request_id, text) lets main (any task of its owner) and a supervisor (its direct children) send a message into a task's running turn. It uses the same send as the owner's composer with steer asked for, so it joins the turn at its next tool boundary when the task's Agent takes steers (MAINLOOP_STEER_AGENTS) and a turn is running. Otherwise (no turn running, a turn waiting on input, an Agent without steers) the message is recorded as an ordinary message instead: queued behind the open turn, or starting a turn when none is open. The result's delivery says which: steered, queued or sent. The message reads [message from main] or [message from supervisor task <id>]. Its message id derives from the caller and request_id, so a retry returns the first send and never sends twice. A task that has ended, or whose current attempt is not active, is refused (task_terminal, task_not_running).

follow_up(task_id, request_id, text) is for the same callers, and sends a message to the task's own native session so the agent keeps its context. A running, waiting or blocked task takes it as its next message and moves back to running; a completed coordination task reopens on the same attempt and session. It is refused for cancelled and failed tasks, completed code tasks, and a task whose kagent Session is gone. The result says sent or queued and whether the task reopened. See tasks.

MCP-created coding briefs include a Workspace environment section after the shared guidance: the workspace is a sandbox where process spawns and small file operations are slow, so prefer fewer, larger commands. Agents must preserve the egress proxy CA environment variables (SSL_CERT_FILE, SSL_CERT_DIR, NODE_EXTRA_CA_CERTS), and only allowlisted hosts are reachable (the shared guidance says GitHub is reached through Mainloop's tools only). A project may use a prebuilt cache image. If it does, Go, pnpm and similar caches are under /opt/cache, set through environment variables (GOCACHE, GOMODCACHE, pnpm_config_store_dir); the agent uses them as set and does not move them. The text is conditional because the brief does not know whether the project's environment has such an image. Even when running as root, agents cannot install OS packages. Coordination briefs omit this section. Delegated sessions skip Mainloop's rendered role text, so it does not duplicate this guidance.

Shared agent guidance

Status: implemented (guidance v11, server/internal/agentcontext); wording is checked in, not owner-editable. It is the same text for every role and any project, so it holds no repository specifics; those belong in the repository's own AGENTS.md, and the owner's per-project direction in project instructions. It is bounded (1.5 KiB, enforced by a test) and rendered, not stored: every task brief carries it after the assigned work, and the stored brief stays as written. The main session gets it in the first message of each kagent Session, after one line naming its role, and in the next message of an existing Session that was given an older version or none (see chat). The text is the same for every role, so it keys what differs on the task's mode, not its role: a supervisor is any task without a parent, and a root code task has a checkout. What only code tasks need (checks, publishing, caches, dev_*) is in the coding guidance above, not here, because coordination tasks have none of those tools. It tells the agent:

  • Where it runs: Mainloop sessions are isolated; code tasks, whatever their role, run in an isolated workspace whose checkout is /data/workspace, and the main session and coordination tasks have no checkout, so code work goes to code tasks.
  • What survives a pause: committed work and /data; writes elsewhere, /tmp and processes may be reset. It runs builds and tests in the foreground.
  • Project specifics come from the repository's AGENTS.md and CLAUDE.md.
  • GitHub is reached only through Mainloop's tools: workspaces have no gh and no GitHub API access. The main session and coordination tasks file an issue with create_issue and add to an existing one with comment_issue (see Issue writes); code tasks report what they find, and the main session or a coordination supervisor files it. Any task may comment on or review (never approve) a pull request with comment_pull_request. An agent the owner opted in also has web_fetch, which reads a public web page; it may pass it to a task it delegates (web_fetch: true), and no other agent may (see Web fetch).
  • No production commands run unless the task or the owner says so.
  • In text the owner reads, a task is written as a link, [<task title>](/tasks/<task id>), which the web renders as an in-app link (see chat), not as a bare id.
  • Tasks report evidence, not claims. A root task or supervisor raises an owner decision as report with outcome=blocked and owner_action; a worker (child) reports its blocker with no owner_action, so its supervisor decides (below). The main session has no report tool and asks the owner directly in chat.
  • The owner's Insights page (/health, see orchestration health) shows orchestration health at a high level.
  • Memory: remember records a one-line lesson for later agents on the project, from the owner's words or a verified fact, never a repository fact (that goes in AGENTS.md). The main session's entries apply at once; anyone else's are proposals the owner decides. forget ends a wrong one (see project memory). With scope: owner (main and supervisors only), the owner's own words about how they work, true across projects (owner memory).

One owner item per cause: the role line of a child's brief (not the shared text above, which is the same for every role) tells it to report blocked naming the blocker with no owner_action. That report reaches its supervisor (and main) like any blocked report and leaves the task blocked / reconciliation, which opens no Needs-you item; the supervisor's role line tells it to answer what it can (steer) and, when several workers share a cause, to raise a single owner_action report for them all. Before this (v10), the supervisor and each worker raised its own owner_decision for the same root cause. It is an instruction, not enforcement: nothing stops a worker from sending an owner_action, and the server does not compare causes, which would need matching free text. Not measured: whether agents follow it.

Plain titles (accepted, not implemented). The next guidance version adds one line after "Task links":

- Titles: name tasks, pull requests and issues by their outcome, in plain words the owner would use; never internal labels like "slice 1" or "S1".

It is in the shared text, not a supervisor's role line, because every role writes titles the owner reads: main and supervisors name tasks, workers name pull requests, main and coordination tasks name issues. It adds 147 bytes, which keeps the text under its bound (1,509 of 1,536 bytes at v11's length). The delegate tool's title property gets a matching description:

What the task delivers, in plain words the owner would use (for example "Rename a task from the Board"); never an internal label like "slice 1" or "S1".

The version is the next one free on main when the change merges: work items take 12 (work items), so this is expected to be 13. Owner-created tasks are named by the owner; a title an agent got wrong is fixed by the owner's rename. Not measured: whether agents follow it.

A change of substance to the wording bumps the version in the code and its heading; the main binding records the version it was given, so a bump reaches a running main on its next message. Not measured: whether agents follow it.

Agent dotfiles (docs/specs/agent-dotfiles.md) carry owner-level instructions and skills as native user-level files rather than rendered guidance text. Their source can be configured, each session records the commit and bundle chosen for it, and kagent lays that bundle out read-only before the agent's first turn.

task_retry and task_reassign are served to main and supervisors for the tasks they manage (task-handoff): the task gets a new attempt in a new session with a continuation brief, and a code task's successor starts from the task branch's head on origin (or its base, when the branch was never pushed). Without a GitHub App a code task's request is recorded blocked (handoff_unavailable). Main and supervisors may hand one task off TASK_MAX_HANDOFFS times (default 3); after that handoff_limit leaves it to the owner. No provider fallback is inferred. Legacy session tools status, read, cancel and clear, and topic/kind delegation arguments, are removed.

loop_arm, loop_list and loop_stop are served to main and supervisors (loops): a loop watches a task they manage (its status, a code task's pull request and CI, or the task going quiet) or a timer, and each firing is one message to the caller, delivered with child reports, so the caller can end its turn instead of polling. A loop armed with expect_change stops, and asks the owner, after three firings in a row find its task unchanged. A supervisor's loops end with its task.

schedule_list, schedule_create, schedule_update and schedule_delete are served to the main thread only (scheduled runs): cron timers that kagent fires, each firing a new session on the schedule's Agent.

whoami returns server-resolved task, attempt, parent, root, role, depth, workspace, attempt number and writer generation alongside existing scoped identity. A workspace grant supplies repository tools only within its own checkout; coordination grants supply no repository or merge tools. Existing PR/merge consent and enablement gates remain in force.

Reporting and completion

A supervisor or child reports only its own current attempt using report(task_id, attempt_id, request_id, summary, outcome, evidence_refs, screenshot_ids). screenshot_ids names up to 8 preview screenshots taken in the attempt's own workspace; any other id refuses the report with 422 report_screenshots. The report's message to the main thread attaches them as images. Outcomes are progress, completed, failed or blocked. Each logical report has a stable request ID: equal replay returns its recorded result, changed content conflicts, and additional progress uses a new ID. Reports are untrusted claims, not instructions or owner approvals.

The report, task update, task event and recipient intents commit together. Child reports route to the current authorized parent attempt and roll up to main. Root reports route to the current authorized main session. Main receives every blocked or failed report from any task, and every terminal report (completed, failed, blocked) of a root task; progress reports of a root task stay on the task. Owner task reads and committed task events expose the same reports and blocked/waiting state; this does not fabricate owner approval cards or transfer native HITL identity.

Notifications use deterministic message IDs and the native delivery ledger. A report is never steered into a running turn: while its recipient (main or a supervisor) has an open turn, and for a short batch window (3 seconds) after it is made, it waits, and the reports that waited together are sent as one message ([N reports], oldest first), one turn rather than one each. Loop firings for the same recipient join the same message ([N updates] when it carries both). Each report keeps its own delivery row and state; only the ledger message is shared, so a replay finds that message and sends nothing twice. A report waiting behind a turn the owner stops is sent once the turn has ended. Restarting the existing task reconciler recovers committed intents without another MCP call. A revoked recipient retains a pending intent; a queued report for a superseded or revoked recipient is cancelled before rerouting to current authority. Sent or uncertain deliveries retain their original identity and are never replayed to a successor. A report does not choose its recipient or escape its tree.

A completed native turn or fallback reply creates no report and completes no task. Coding completed reports leave the task waiting for publication; S4's verified merged publication is required for coding success. After Mainloop has verified the merge and completed the task, the exact still-active workspace binding can send a final completed report, preserving product completion and publication evidence. An existing completed report for that task and attempt consumes this allowance: equal request-ID replay returns the recorded report, changed content conflicts, and a new request ID is refused with a conflict without another task update, event or notification intent. Earlier progress reports do not consume the allowance. It retains only merge status, whoami, its own task_get, and that terminal reporting access until cleanup revokes its credential. Approval-route completions still require the exact owner receipt; auto-route completions do not. Other report outcomes are refused in this context. failed and blocked reports for active tasks preserve authority and capacity pending reconciliation rather than claiming the runtime has stopped.

Coordination completion requires an explicit completed result and no live child reservations. The reconciler waits for outstanding native deliveries, drains the attempt, revokes its credential, confirms runtime deletion, then settles completion and releases capacity. Unknown deletion keeps the attempt draining and the result pending. A pending cancellation takes precedence over completion.

The same cleanup runs for coding tasks after verified merged settlement. Product completion remains visible while runtime deletion is pending; it does not free capacity by itself. The reconciler discovers older completed tasks with held active/draining attempts without a new operation or manual database repair. Failed/cancelled coding outcomes with held attempts are also recovered; ordinary cancellation and provisioning failure already use confirmed settlement. An authoritative failed first/sole brief already draining is disposed through this path, retaining the task's blocked/reconciliation diagnostic. Active failed/blocked reports, publication holds, and handoffs remain reservations pending their existing resolution paths. Live children, outstanding or uncertain deliveries, unresolved publication and pending operations prevent automatic release.

Standing context renders bounded stored task projections and recent report claims without additional model calls. Native history, compaction and structured owner input retain their provider identity. The delegated runtime receives the persisted initial brief, including role guidance for MCP creates; the richer standing projection is not injected into that brief.

Qualification boundary

Offline tests use real isolated PostgreSQL and fake kagent responses. They establish persistence, authority, queueing and restart behavior. They do not qualify live checkout composition, provider delivery, gateway isolation, scoped publication or production enablement.