ki

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ki holds the side-effect-free logic of the ki CLI: resolving a repo to its scope and identity, choosing a token, and building the agent launch.

Index

Constants

View Source
const (
	KindApprove = "approve"
	KindReview  = "review"
)

Kinds a ledger record can have besides a plain delegated job: `ki approve` writes one record per run and, with --review, one for the review agent.

View Source
const (
	ApproveApproved  = "APPROVED"
	ApproveMerged    = "MERGED"
	ApproveCommented = "COMMENTED"
	ApproveChanges   = "CHANGES"
	ApproveRefused   = "REFUSED"
	ApproveDryRun    = "DRY_RUN"
)

What a `ki approve` run did, as its ledger record's status.

View Source
const (
	SourceKB     = "kb"
	SourceVault  = "vault"
	SourceGitHub = "gh"
)

Where an answer may come from.

View Source
const (
	CursorMCPFile = ".cursor/mcp.json"
	CursorCLIFile = ".cursor/cli.json"
)

Where Cursor reads a workspace's MCP servers and its permissions.

View Source
const (
	ResumedSession    = "session"
	ResumedTranscript = "transcript"
)

How a follow-up reached the earlier conversation.

View Source
const (
	ConfigFile    = "config.yaml"
	ConfigLink    = "config" // under the ki config directory, like "harness"
	ProjectsFile  = "projects.yaml"
	ModelsFile    = "models.env"
	AliasesFile   = "aliases.yaml"
	MCPConfigFile = "mcp-config.json"
)

A configuration directory holds everything that is yours rather than the harness's: the projects file, the model settings, the aliases, the brains map the MCP server serves, and config.yaml for settings that are not projects. The harness checkout carries one under deploy/config as the example and as the fallback for machines that never linked their own.

View Source
const (
	ConfigFromEnv     = "env"     // KI_CONFIG
	ConfigFromLink    = "link"    // ~/.config/ki/config, written by ki setup config
	ConfigFromHarness = "harness" // <harness>/deploy/config, the layout every machine started with
)

Where a configuration directory came from.

View Source
const (
	JobPR      = "PR"
	JobDone    = "DONE"
	JobBlocked = "BLOCKED"
	JobFailed  = "FAILED"
	// JobRunning is the placeholder status in result.json while the worker is alive.
	JobRunning = "RUNNING"
	// JobLaunchFailed means the agent exited before producing any result
	// (not logged in, bad flags, missing binary). It is kept apart from
	// FAILED so a routing policy can read it as "this provider is down".
	JobLaunchFailed = "LAUNCH_FAILED"
	// JobStalled means the worker printed no event for the stall limit and ki
	// ended it. Its worktree and commits are kept. A job killed at --timeout
	// is FAILED instead.
	JobStalled = "STALLED"
	// JobQuota means the worker stopped on a usage limit after it started
	// the task. Its worktree, commits and last progress lines are kept, so
	// `ki delegate resume` can continue it on another provider.
	JobQuota = "QUOTA"
	// JobQueued is a job waiting in the queue for a provider of its role;
	// it is never in the ledger, only in its job folder's queue.json.
	JobQueued = "QUEUED"
)

A delegated job is one task run headless on one agent, in its own worktree, that answers with a single status line. The statuses are the ki-resolver contract, so a planner reads every worker the same way whichever vendor ran it.

View Source
const (
	// HangCooldown is how long a provider is skipped after a job that hung.
	HangCooldown = 30 * time.Minute
	// DemoteAfter hung jobs within DemoteWindow demote the provider.
	DemoteAfter  = 2
	DemoteWindow = 24 * time.Hour
	// HealthJobs is how many of a provider's latest jobs `ki delegate health` reads.
	HealthJobs = 20
	// HealthSince is how far back a provider seen only in the ledger is listed.
	HealthSince = 7 * 24 * time.Hour
)

A job that hangs (STALLED, or killed at --timeout) says the provider is stuck rather than down. It parks the provider for a cool-down, and two in a day send it to the end of the order until a job on it ends PR or DONE.

View Source
const (
	ClassJudgement = "judgement"
	ClassExecution = "execution"
	ClassSearch    = "search"
	ClassWriting   = "writing"
)

Task classes a model policy can name. The session itself is judgement work; subagents that apply a described change are execution; read-only lookups are search; light prose (summaries, changelogs, commit and PR text, status posts) is writing.

View Source
const (
	MCPSourceKi        = "ki"
	MCPSourceClaudeAI  = "claude.ai"
	MCPSourcePlugin    = "plugin"
	MCPSourceLocal     = "local"
	MCPSourceProject   = "project"
	MCPStatusConnected = "connected"
	MCPStatusNeedsAuth = "needs-auth"
	MCPStatusFailed    = "failed"
	MCPStatusUnknown   = "unknown"
)

Where an MCP server comes from.

View Source
const (
	OptProject  = "@ki-project"
	OptAgent    = "@ki-agent"
	OptIdentity = "@ki-identity"
	OptTask     = "@ki-task"
	OptMode     = "@ki-mode"
	OptDir      = "@ki-dir"
	OptCreated  = "@ki-created"
)

Window user options, set when ki mecca opens a window.

View Source
const (
	StatusWorking   = "working"
	StatusIdle      = "idle"
	StatusNeedsUser = "needs-user"
	StatusWaiting   = "waiting"
	StatusDone      = "done"
	StatusExited    = "exited"
)

Window statuses reported by ls.

View Source
const (
	// ReservationFile holds the picks whose job is not in the ledger yet,
	// one JSON line each. It sits beside the ledger, which keeps its format.
	ReservationFile = "reservations.jsonl"
	// PickLockFile is the flock taken around reading, choosing and reserving.
	PickLockFile = "pick.lock"
	// PickLockWait is how long a pick waits for another one before giving up.
	PickLockWait = 10 * time.Second
)

A pick reads the ledger, chooses a provider and records the choice. Run in parallel, several processes would read the same ledger and choose the same provider, so PickAndReserve does all three under one lock.

View Source
const (
	SourceFlag    = "flag"
	SourceEnv     = "KI_AGENT"
	SourcePlanner = "roles.planner"
	SourceDefault = "default"
)

Where the session's agent came from, highest precedence first.

View Source
const (
	StrategyOrdered    = "ordered"
	StrategyRoundRobin = "round-robin"
)

A role is a class of work with a list of providers that may run it, so a planner names the work (`ki delegate --role execution`) and the machine decides which vendor gets it. Only two strategies exist: ordered keeps the first provider busy and the rest as failover; round-robin takes turns, weighted. Failover is not a strategy: every pick skips a provider that is missing, over quota, recently failed to launch, or over its daily cap.

View Source
const (
	// QueueEntryFile is the queued job's request in its job folder.
	QueueEntryFile = "queue.json"
	// QueueLockFile is the flock taken while the queue is read and changed.
	QueueLockFile = "queue.lock"
	// QueueStartGrace is how long an entry may be marked starting without the
	// ki process that starts it recording its pid, before it goes back to waiting.
	QueueStartGrace = 2 * time.Minute
)

A job whose role has no provider available can wait in the queue instead of being refused (ki delegate --when-available). The queue is one queue.json per job folder, so a queued job already has the id it will run under; `ki queue run` starts the oldest ones once a provider is back.

View Source
const (
	HealthOK      = "ok"
	HealthSkipped = "skipped"
	HealthDemoted = "demoted"
)

Health of a provider as a role reports it.

View Source
const AgentWorkingLabel = "agent: working"

AgentWorkingLabel is the claim: a delegated job puts it on an issue while it runs, and nothing else about the job is written to GitHub. A crashed job leaves it; finish takes it off.

View Source
const AllowAllSubagents = "*"

AllowAllSubagents turns the guard off when it is the only entry of the policy.

View Source
const AskHistoryMax = 20000

AskHistoryMax caps the earlier turns a transcript carries, in characters.

View Source
const BreakerCooldown = 10 * time.Minute

BreakerCooldown is how long a provider is skipped after a LAUNCH_FAILED.

View Source
const BrowserSkipped = "checks skipped: browser (sandbox)"

BrowserSkipped is added to the result of a sandboxed job whose brief asked for a browser check.

View Source
const ClaudeSettings = `{"attribution":{"commit":"","pr":""}}`

ClaudeSettings is passed to Claude Code with --settings for every ki session: no Co-Authored-By trailer and no attribution line in PR descriptions.

View Source
const CodexTable = "[mcp_servers." + MCPServerName + "]"

CodexTable is the config.toml table ki manages for the knowledge base.

View Source
const CodexVaultTable = "[mcp_servers." + VaultServerName + "]"

CodexVaultTable is the config.toml table for the local vault server.

View Source
const CursorAuto = "auto"

CursorAuto is the model recorded for a Cursor job that named none and whose stream named none either: Cursor then chose for itself in its Auto mode.

View Source
const CursorSandboxFile = ".cursor/sandbox.json"

CursorSandboxFile is where Cursor reads a workspace's sandbox policy.

View Source
const DefaultCheckoutRoot = "~/code"

DefaultCheckoutRoot is the identity-folder parent from docs/laptop-setup.md.

View Source
const DefaultQueueParallel = 2

DefaultQueueParallel is how many queued jobs run at once unless delegate.queue_parallel says otherwise.

View Source
const DefaultQuotaCooldown = 60 * time.Minute

DefaultQuotaCooldown is how long a provider is skipped when its output says it is over a limit but gives no reset time ki can read.

View Source
const DefaultSessionAgent = "claude"

DefaultSessionAgent starts when nothing else names an agent.

View Source
const DefaultStall = 15 * time.Minute

DefaultStall is how long a streaming worker may stay silent before ki ends it, unless --stall or delegate.stall in machine.yaml says otherwise.

View Source
const HandoffDiffLines = 300

HandoffDiffLines caps the diff a handoff note carries; the worker can read the rest with git in the worktree it continues in.

View Source
const JobLost = "LOST"

JobLost is shown for a job whose result.json still says RUNNING but whose worker is gone: ki was killed before it could record the end.

View Source
const KindAsk = "ask"

KindAsk marks a ledger record of `ki ask`: one read-only question.

View Source
const KindSkill = "skill"

KindSkill marks a ledger record of `ki skill run`: one skill, run once.

View Source
const LedgerFile = "ledger.jsonl"

LedgerFile is the per-machine job history under the jobs folder, one JSON line per job.

View Source
const (

	// LegacySensitiveTokenName is the old file name of the sensitive token,
	// still read when token-sensitive is absent so existing machines keep working.
	LegacySensitiveTokenName = "token-pci"
)
View Source
const MCPServerName = "ki-kb"

MCPServerName is the name agents see the knowledge base under.

View Source
const MachineFile = "machine.yaml"

MachineFile is the per-machine file under the ki config directory. It says which identities from projects.yaml this machine carries (whose gh logins doctor expects here, and whose repos ki will start sessions in) and which model each class of work runs on, per agent. projects.yaml is shared by every machine; this file is the one place a laptop differs from the others. No file means every identity and the agents' own defaults.

View Source
const MaxReviewDiff = 200 << 10

MaxReviewDiff is how much of a diff goes into the brief; a bigger one is read from the checkout instead.

View Source
const MeccaConfigFile = "mecca.yaml"

MeccaConfigFile is the per-machine file, under ki's config dir, that says where checkouts live. projects.yaml has no local paths: it is shared with the cluster and every machine lays out its folders differently.

View Source
const MeccaIdleAfter = 15 * time.Second

MeccaIdleAfter is how long a window must be quiet before ls calls it idle: agents redraw a spinner while they work, so silence means they are waiting.

View Source
const MeccaSession = "ki-mecca"

MeccaSession is the tmux session that holds one window per agent session.

View Source
const RolePlanner = "planner"

RolePlanner is the role a bare `ki` reads to choose the session's agent. It takes the same shape as the other roles and the same eligibility rules as a delegate pick, but only reads: nothing is reserved or recorded, since a session is not a job.

View Source
const SkillFile = "SKILL.md"

SkillFile is the file that holds a skill, in its own folder.

View Source
const TitleMax = 90

TitleMax is the longest job title, ellipsis included.

View Source
const VaultServerName = "ki-vault"

VaultServerName is the name agents see the local vault server under.

View Source
const VoiceBrain = "voice"

VoiceBrain is left out of `ki kb --all` unless it is named: it holds how the owner writes, which no UI browsing the knowledge base should surface by default.

Variables

View Source
var (
	// ErrUnknownMode is returned for a mode that is not ask, auto, edits or skip.
	ErrUnknownMode = errors.New("unknown mode")
	// ErrModeUnsupported means the agent has no equivalent of the mode.
	ErrModeUnsupported = errors.New("mode not supported")
)

AskSources is every source, in the order the brief names them.

Classes lists the task classes in the order the machine file renders them.

ConfigFiles are the files a configuration directory must hold.

View Source
var DefaultSubagents = []string{"Explore"}

DefaultSubagents is the policy of a machine that sets none: read-only search only.

View Source
var ErrBadSettings = errors.New("settings file is not a JSON object")

ErrBadSettings means a settings file is not a JSON object ki can update.

View Source
var ErrInvalidBrain = errors.New("invalid brain name")

ErrInvalidBrain is returned for a --brain value that is not a brain name.

View Source
var ErrMeccaArgs = errors.New("invalid ki mecca arguments")

ErrMeccaArgs wraps every argument error of `ki mecca`.

View Source
var ErrNoCheckout = errors.New("no checkout found")

ErrNoCheckout means a project name did not resolve to exactly one checkout.

View Source
var ErrNoVerdict = errors.New("the final message does not end in VERDICT: APPROVE or VERDICT: CHANGES: <reason>")

ErrNoVerdict means the final message did not end in a VERDICT line.

View Source
var ErrNoWindow = errors.New("no such ki-mecca window")

ErrNoWindow means no window matched a reference.

View Source
var ErrPRRef = errors.New("invalid pull request")

ErrPRRef is returned for an argument that is neither a PR URL nor owner/repo#N.

View Source
var ErrUnmanagedConflict = errors.New("conflicting definition outside the ki managed block")

ErrUnmanagedConflict means the user already defined what ki wants to manage.

View Source
var InstructionsFile = filepath.Join("agent", "instructions.md")

InstructionsFile is the agent instructions file, under agent/ in the harness checkout and, optionally, in a configuration directory.

View Source
var KnowledgeBaseFile = filepath.Join("agent", "knowledge-base.md")

KnowledgeBaseFile is the part of the agent instructions about the knowledge base, under agent/ in the harness checkout. It is included only when a knowledge base is configured.

View Source
var ListFormat = func() string {
	parts := make([]string, len(listFields))
	for i, f := range listFields {
		parts[i] = "#{" + f + "}"
	}
	return strings.Join(parts, "\t")
}()

ListFormat is the -F format for `tmux list-windows`, one tab-separated field per listFields entry.

View Source
var MCPAgents = []string{"claude", "cursor", "codex"}

Agents `ki mcp ls` reports on, in output order.

Functions

func Age

func Age(d time.Duration) string

Age renders a duration the way ls shows it: 45s, 12m, 3h, 2d.

func AgentFamily

func AgentFamily(agent string) string

AgentFamily is the agent as a skill's ki-agents names it: claude, codex, cursor or agy, "" for one ki does not know.

func AgyRule

func AgyRule(entry string) string

AgyRule is agy's permission rule for one allow-list entry: command(git), command(git status).

func AgySettingsPath

func AgySettingsPath(home string) string

AgySettingsPath is agy's user settings file under home. Its permissions.allow rules are what headless agy runs without a prompt.

func Alive

func Alive(pid int) bool

Alive reports whether a process with this pid exists.

func AppendLedger

func AppendLedger(path string, r Result) error

AppendLedger records a finished job. Last, Tail and the progress of a QUOTA job are left out: they live in the job's result.json.

func AppendLineOnce

func AppendLineOnce(path, line string) error

AppendLineOnce adds line to the file at path unless a line equal to it is already there, creating the file and its folder when missing.

func ApproveBody

func ApproveBody(security string) string

ApproveBody is the review body of an approval: LGTM, and for a change on a security surface the second-reviewer note, so an approval never reads as a full sign-off there.

func AskArgs

func AskArgs(agent string, s AskSetup) []string

AskArgs are the flags that start the agent for a question, unable to change anything: Claude Code may call only the source tools listed, with no MCP server but ki's and every other tool denied without a prompt; Codex runs in its read-only sandbox with ki's servers defined in -c (the token stays in KI_TOKEN); Cursor runs in ask mode, which refuses edits and shell commands, inside its sandbox, with the MCP tools its workspace allows (AskCursorPermissions).

func AskBrief

func AskBrief(question string, sources []string) string

AskBrief is the prompt of an ask: the question, the sources it may use and how to answer. There is no status line: the answer is the result.

func AskBriefAfter

func AskBriefAfter(question string, sources []string, history string) string

AskBriefAfter is AskBrief for a follow-up that starts a fresh run: the earlier turns (AskHistory) come first, then the question.

func AskGitHub

func AskGitHub(agent string) bool

AskGitHub reports whether the agent can read GitHub during an ask. Only Claude Code can be limited to gh's read subcommands; Codex's read-only sandbox and Cursor's sandbox have no network, which is what keeps gh from writing there.

func AskHistory

func AskHistory(turns []AskTurn, max int) string

AskHistory renders turns for a prompt, newest last, within max characters: the oldest turns are dropped first, and a single turn still too long is cut.

func AskSupported

func AskSupported(agent string) bool

AskSupported reports whether ki can start the agent unable to write.

func AsksBrowserCheck

func AsksBrowserCheck(task string) bool

AsksBrowserCheck reports whether a brief asks for a browser check.

func BackAt

func BackAt(skipped []Skipped) time.Time

BackAt is the earliest time a skipped provider is expected back, zero when none of the reasons has a time (every provider missing from PATH).

func BriefTitle

func BriefTitle(brief string) string

BriefTitle is the first sentence of a brief's first non-empty line, without a leading "Repo: ... ." clause or markdown marks.

func BriefTitleFile

func BriefTitleFile(jobsDir, id string) string

BriefTitleFile is BriefTitle of a job's brief.md, "" when it cannot be read.

func Candidates

func Candidates(in PickInput) (try []Provider, skipped []Skipped)

Candidates returns the providers to try, in order, and the ones skipped or demoted with the reason. The caller runs the first; on LAUNCH_FAILED it records the attempt and moves to the next, which is the only retry: a worker that ran is never re-run elsewhere.

func CapLines

func CapLines(s string, n int) string

CapLines keeps the first n lines of s and says how many were cut.

func CheckSkillTool

func CheckSkillTool(entry string, fromCaller bool) error

CheckSkillTool refuses an entry that would grant every shell command, one that contains a git option a skill run refuses (see GuardBash), and one that would let the agent push unless the caller passed it: a skill's own list never pushes.

func ClaudeAttributionIsOff

func ClaudeAttributionIsOff(content []byte) bool

ClaudeAttributionIsOff reports whether settings already hide both attributions.

func ClaudeAttributionOff

func ClaudeAttributionOff(content []byte) (out []byte, changed bool, err error)

ClaudeAttributionOff returns Claude Code user settings with attribution.commit and attribution.pr set to empty strings, so no Co-Authored-By trailer or "Generated with" line is added anywhere Claude Code runs, with or without ki. Every other key is kept. changed is false when nothing needed to change.

func ClaudeToolRule

func ClaudeToolRule(entry string) string

ClaudeToolRule is an entry as Claude Code's --allowedTools takes it: a tool name or MCP tool as written, a plain command as Bash(<command>:*).

func CleanOption

func CleanOption(s string) string

CleanOption makes a value safe to store in a window option and read back through ListFormat: tabs and newlines would split the record.

func CleanTitle

func CleanTitle(s string) string

CleanTitle redacts credentials, collapses whitespace and caps the text at TitleMax on a word boundary.

func Clock

func Clock(d time.Duration) string

Clock renders a job's elapsed time: 02:14, or 1:02:14 past an hour.

func CodexMCPBlock

func CodexMCPBlock(url string, vault MCPServer) string

CodexMCPBlock is the Codex MCP server entry. Token and scope are read from the environment that `ki --agent codex` sets, so one entry serves every repo. With a vault, the block also starts `ki vault mcp` over stdio; the vault path is baked in because config.toml is per machine anyway. With no url the ki-kb table is left out, and with no vault either the block is empty.

func CombineInstructions

func CombineInstructions(harness, config string) string

CombineInstructions is the harness instructions followed by the configuration directory's, a blank line between. With no configuration text it returns the harness text untouched, so a machine without that file sees no change.

func CursorRule

func CursorRule(instructions string) string

CursorRule wraps the agent instructions as an always-applied Cursor project rule.

func EnsureAgyAllow

func EnsureAgyAllow(path string, entries []string) ([]string, error)

EnsureAgyAllow adds command(<entry>) to permissions.allow in agy's settings file for every entry not already there, and returns the entries it added. It only merges: existing rules keep their order, the deny and ask lists and every other key stay as they are. The file is written through a temporary file in the same folder and a rename, mode 0600, creating the folder and the file when missing. A file that is not a JSON object is an error and is never overwritten.

func EnsureCursorSandbox

func EnsureCursorSandbox(dir string) (bool, error)

EnsureCursorSandbox writes the workspace's sandbox policy so a headless Cursor worker in auto mode can reach api.github.com; there is nobody to approve the network prompt. It reports whether it wrote the file. An existing file is the repo's own policy and is never touched.

func ExpandHome

func ExpandHome(p, home string) string

ExpandHome replaces a leading ~ with home.

func FindSkill

func FindSkill(name string, dirs []string) (string, error)

FindSkill locates a skill: a path to a SKILL.md or its folder, else the first <dir>/<name>/SKILL.md among dirs.

func GuardBash

func GuardBash(command string) string

GuardBash says why a shell command may not run in a skill run, "" when it may. Every part of a compound command is checked.

func HandoffTask

func HandoffTask(task string, prev Result, p WorkDone) string

HandoffTask is the brief for a job that continues prev: the original task, then a note on what the earlier worker did and where it stopped, so the next worker finishes the work instead of starting over.

func HasBlock

func HasBlock(content string, c Comment) bool

HasBlock reports whether content contains ki's managed block.

func HeadlessSupported

func HeadlessSupported(agent string) bool

HeadlessSupported reports whether ki knows the agent's non-interactive flags.

func IdentityProblem

func IdentityProblem(s Session, actualEmail string) string

IdentityProblem explains why git would commit as the wrong person, or returns "".

func InstructionsRunFile

func InstructionsRunFile(runDir, text string) string

InstructionsRunFile names the run-directory file holding text. The name carries a hash of the text, so sessions with the same text share one file and a session never reads a file another one is rewriting.

func IssueBranch

func IssueBranch(number int, title string) string

IssueBranch is <type>/<number>-<slug> for an issue titled title. The type is the title's Conventional Commits prefix, chore without one; the slug is the rest of the title.

func IssueBrief

func IssueBrief(ref IssueRef, title, body string) string

IssueBrief is the worker's task when --task is not given: the issue itself.

func LockQueue

func LockQueue(ctx context.Context, jobsDir string, wait time.Duration) (unlock func(), err error)

LockQueue takes the queue's flock, so a run of the queue, a cancel and a queued job recording its start never interleave.

func MeccaEnv

func MeccaEnv(getenv func(string) string) map[string]string

MeccaEnv is the environment passed to a new window with `tmux -e`.

func MeccaKiArgv

func MeccaKiArgv(kiBinary string, a MeccaNewArgs) []string

MeccaKiArgv is the command a window runs: this ki binary with the session flags, so the mode is visible in the window's command line.

func MentionsTooling

func MentionsTooling(s string, terms []string) bool

MentionsTooling reports whether s names the tooling or one of terms.

func MergeEnv

func MergeEnv(base []string, extra map[string]string) []string

MergeEnv returns base with every key in extra set exactly once. Existing entries for those keys are dropped first: with duplicates, some programs read the first copy and others the last, so a stale exported GH_TOKEN could win.

func MissingConfigFiles

func MissingConfigFiles(dir string) []string

MissingConfigFiles lists the required files absent from dir.

func ModeArgs

func ModeArgs(agent string, m Mode, agentArgs []string) (args []string, overridden bool, err error)

ModeArgs returns the flags that start agent in mode m. When the user's own agent args already set permissions, nothing is added and overridden is true, so a flag after `--` always wins and never clashes with ki's. Edits mode gets no allow-list here: use ModeArgsAllow.

func ModeArgsAllow

func ModeArgsAllow(agent string, m Mode, agentArgs, allow []string) (args []string, overridden bool, err error)

ModeArgsAllow is ModeArgs with the edits mode's allow-list (delegate.allow in the machine file, already validated): each entry becomes the agent's own flag where it takes one on the command line. Other modes ignore it.

func NeedsTail

func NeedsTail(w Window, now time.Time) bool

NeedsTail reports whether Classify needs the pane's visible text: only quiet, live windows do, so ls skips capture-pane for the rest.

func NewJobID

func NewJobID(now time.Time) string

NewJobID is time-sortable and unique enough for one machine: j-<utc stamp>-<8 hex>.

func ParseAskStatus

func ParseAskStatus(last string) (status, detail string)

ParseAskStatus reads an ask's final message: any answer is DONE, an empty one FAILED.

func ParseSandboxedStatus

func ParseSandboxedStatus(last string) (status, detail string)

ParseSandboxedStatus is ParseStatus for a worker whose commits ki publishes: a final message without a status line is DONE with its first line as the summary, because a clean exit means the worker finished and the commits decide the rest. A run that failed never reaches it (the exit code decides first).

func ParseSince

func ParseSince(v string, now time.Time) (time.Time, error)

ParseSince reads --since: a count of hours, days or weeks ("36h", "7d", "2w"), a date ("2026-11-01") or an RFC 3339 time. Counts are relative to now.

func ParseSkillStatus

func ParseSkillStatus(last string) (status, detail string)

ParseSkillStatus reads a skill run's final message: its status line when it ends with one, else DONE with the last line as the detail. An empty message is FAILED.

func ParseSources

func ParseSources(s string) ([]string, error)

ParseSources reads --source: a comma-separated subset of AskSources.

func ParseStatus

func ParseStatus(last string) (status, detail string)

ParseStatus reads the status line out of a worker's final message, scanning from the end so a trailing line wins. A message without one is FAILED: the contract was not met and a planner must not guess.

func ParseVerdictStatus

func ParseVerdictStatus(last string) (status, detail string)

ParseVerdictStatus is ParseStatus for a review job: DONE with the verdict line, or FAILED when there is none.

func PickAndReserve

func PickAndReserve(ctx context.Context, dir string, in PickInput, id string, wait time.Duration) (try []Provider, skipped []Skipped, err error)

PickAndReserve is Candidates made atomic across processes on one machine: under an exclusive lock it reads the ledger and the reservations in dir, ranks the providers and reserves the first candidate for job id, so the next pick sees this turn taken. The lock is held only for that, never while an agent runs, and the kernel drops it if the process dies. in.Ledger and in.Reserved are filled here; wait bounds the time spent on the lock.

func Progress

func Progress(line []byte) []string

Progress reads one line of a worker's stream and returns what it did, one entry per tool call or assistant message; thinking, tool results and bookkeeping events give nothing.

func PromptInstructions

func PromptInstructions(instructions, task string) string

PromptInstructions is the task with the instructions in front, for agents that take no system-prompt file in headless mode.

func PruneRunFiles

func PruneRunFiles(dir string, maxAge time.Duration, now time.Time) (int, error)

PruneRunFiles deletes generated MCP configs (they hold a token) and instructions files older than maxAge from dir, and returns how many it removed. A session's files are only read when its agent starts, so old ones are never needed again.

func PullRequestRefusal

func PullRequestRefusal(n int) string

PullRequestRefusal is what --issue says for a number that is a pull request.

func PullURL

func PullURL(s string) string

PullURL is the pull request URL in s, "" when there is none.

func QuotaFromText

func QuotaFromText(text string, now time.Time) time.Duration

QuotaFromText is quotaDuration for text outside the agent's JSON, such as what it printed to stderr before dying.

func ReadOnlyArgs

func ReadOnlyArgs(agent string) ([]string, bool)

ReadOnlyArgs are the flags that start an agent unable to change anything, and false for an agent ki knows no read-only flags for. Claude Code runs without a permission prompt answer, so a tool outside the allow-list is denied; Codex runs in its read-only sandbox.

func ReadOnlySupported

func ReadOnlySupported(agent string) bool

ReadOnlySupported reports whether ReadOnlyArgs knows the agent.

func RedactTarget

func RedactTarget(raw string) string

RedactTarget reduces a server's URL or command line to its host or command name.

func Refusal

func Refusal(ref IssueRef) string

Refusal is the error a second machine sees. Who holds the claim is not on the issue; `ki delegate ls` on that machine says.

func RemoveQueueEntry

func RemoveQueueEntry(jobsDir, id string) error

RemoveQueueEntry drops a job from the queue, and its folder when nothing else is in it.

func RenderMachine

func RenderMachine(m Machine) string

RenderMachine is the file content for a machine: its identities and, when set, its model policy. With no policy the models block is written as a commented example, so the file documents itself.

func ResolveTitle

func ResolveTitle(flag, issueTitle, brief string) string

ResolveTitle is a job's title: the --title flag, else the issue title (set only when the issue is the brief), else the brief's first sentence. Empty when nothing usable is left.

func ResolvedModel

func ResolvedModel(agent, requested, reported string) string

ResolvedModel is the model a job ran on: what the agent reported, else what ki asked for, else Cursor's own Auto choice. It is "" only when nothing was asked and the agent reported nothing.

func ResumeArgs

func ResumeArgs(agent, session string) []string

ResumeArgs are the agent's own flags to reopen the session a job ran, so a BLOCKED job can be answered interactively (ki mecca new <job>).

func ReviewBrief

func ReviewBrief(ref PRRef, pr PullRequest, diff, procedure string) string

ReviewBrief is the task a review agent gets: the pull request, its diff and the review procedure, then the verdict contract.

func ReviewProcedure

func ReviewProcedure(skill string) string

ReviewProcedure is the part of the ki-review skill a headless reviewer follows: reading the change, loading context, reviewing and verifying, not the drafting and posting, which ki does itself.

func RoleStates

func RoleStates(m *Machine, in PickInput) map[string]RoleState

RoleStates reads every role the machine defines the way a pick would, without reserving anything: in carries the ledger, the time and what is installed; its Role and R are set per role.

func RunSessionGuard

func RunSessionGuard(in io.Reader, out io.Writer, allow []string, worker bool) error

RunSessionGuard answers one PreToolUse hook call for the subagent tool: it reads the hook's JSON from in and writes a deny reply to out for a type that allow does not list, nothing for one it does. Input it cannot read is denied: the type cannot be checked, and an allow would let any subagent through.

func RunSkillGuard

func RunSkillGuard(in io.Reader, out io.Writer) error

RunSkillGuard answers one PreToolUse hook call: it reads the hook's JSON from in and writes a deny reply to out for a command the skill run may not run, nothing for one the allow-list alone decides. Input it cannot read is denied.

func Sandboxed

func Sandboxed(agent string, m Mode) bool

Sandboxed reports whether ki runs the agent in a sandbox that cannot reach git remotes: Cursor in auto mode (--sandbox enabled).

func ScrubTooling

func ScrubTooling(text string, terms []string) string

ScrubTooling drops the lines of text that mention the tooling or one of terms (a host name, a worktree path), so nothing posted to GitHub names where or how it was written.

func SecuritySurface

func SecuritySurface(diff string) string

SecuritySurface finds IAM, OIDC, SSO, bucket policy, network ingress or secret changes in a unified diff, by file name and by added line. It backs up the review agent's own SECURITY line: a missed one must not become a plain approval. The result names the file, "" when nothing matched.

func SessionSettings

func SessionSettings(g *SubagentGuard) string

SessionSettings is the --settings JSON of a Claude Code session: ClaudeSettings plus the subagent hook, or ClaudeSettings alone when g is nil.

func ShorthandAgents

func ShorthandAgents() []string

ShorthandAgents lists the names `ki <agent>` accepts.

func SkillBrief

func SkillBrief(s *Skill, args []string, ws SkillWorkspace) string

SkillBrief is the prompt of a skill run: the procedure with its arguments in place of $ARGUMENTS, then the rules of a headless run and the status line to end with.

func SkillClaudeArgs

func SkillClaudeArgs(tools, dirs []string, kiBinary string, sub *SubagentGuard) []string

SkillClaudeArgs are Claude Code's flags for a skill run: anything not allowed is denied without a prompt, the knowledge base and vault reads are allowed, the writes are denied unless tools names them, and git push is denied unless the caller allowed it. dirs are folders the agent may read besides its own, such as the skill's. kiBinary is the ki the run's PreToolUse hook starts to check every shell command (GuardBash); sub, unless nil, adds the subagent guard to the same settings.

func SkillGuardSettings

func SkillGuardSettings(kiBinary string, sub *SubagentGuard) string

SkillGuardSettings is the --settings JSON of a skill run: ClaudeSettings plus the hook that registers the guard and, unless sub is nil, the subagent guard, in one object because Claude Code keeps only the last --settings it is given. The hook command fails closed: a guard that cannot start blocks the command, where Claude Code would otherwise let it through.

func SkillUnsupported

func SkillUnsupported(agent string, tools, agents []string) string

SkillUnsupported says why ki cannot run the skill on agent, "" when it can. Only Claude Code takes a tool allow-list ki can hold it to; Codex and Cursor run a read-only skill through the read-only setup of `ki ask`.

func SkillVaultWrites

func SkillVaultWrites(tools []string) bool

SkillVaultWrites reports whether the tools let the skill write notes.

func Slug

func Slug(s string) string

Slug turns a task description into a short window-name part.

func Snippet

func Snippet(fact string, max int) string

Snippet is a fact on one line, cut to max characters with an ellipsis.

func SortMCP

func SortMCP(entries []MCPEntry)

SortMCP orders entries by agent (claude, cursor, codex), then name.

func SourceLink(cfg *projects.Config, source string) string

SourceLink is the GitHub page of a source "<project>/<path>", or "" when the project is not in the projects file.

func SourceTitle

func SourceTitle(source string) string

SourceTitle names a document by its file: the base name without extension, with dashes and underscores read as spaces.

func SplitAnswer

func SplitAnswer(last string) (answer string, sources []string)

SplitAnswer separates an answer from its trailing Sources list. An answer without one is all answer and no sources.

func SplitShorthand

func SplitShorthand(args []string) (agent string, rest []string)

SplitShorthand takes a leading agent name off a session's arguments: `ki codex --mode auto` is `ki --agent codex --mode auto`.

func Streams

func Streams(agent string) bool

Streams reports whether the agent prints one JSON event per line while it works. agy prints a single object at the end, so it has nothing to follow.

func SubagentDenied

func SubagentDenied(in io.Reader, allow []string, worker bool) string

SubagentDenied says why a subagent call may not run, "" when it may.

func SupportsMode

func SupportsMode(agent string, m Mode) bool

SupportsMode reports whether ki knows agent's flags for m.

func TaskBranch

func TaskBranch(jobID string) string

TaskBranch is the branch of a job that has no issue.

func TokenFile

func TokenFile(confDir string, s Session) string

TokenFile is the KB token for this session: sessions touching a sensitive brain use a separate one. A machine that only has the legacy file keeps getting it; callers compare the base name with LegacySensitiveTokenName to warn.

func UniqueBranch

func UniqueBranch(name, jobID string, taken func(string) bool) string

UniqueBranch is name, or name with the job id's last part when taken reports it exists, so a second job on one issue does not fail git worktree add.

func UniqueName

func UniqueName(name string, taken []string) string

UniqueName appends -2, -3, ... until name is not taken.

func UpsertBlock

func UpsertBlock(content, body string, c Comment, conflict string) (string, error)

UpsertBlock returns content with ki's managed block set to body: replaced if present, appended otherwise. conflict, if non-empty, is a string that must not appear outside the block (e.g. the TOML table header ki defines).

func ValidJobID

func ValidJobID(s string) bool

ValidJobID reports whether s is a job id NewJobID could have made, so a path built from it stays under the jobs folder.

func ValidateBrains

func ValidateBrains(brains []string) error

ValidateBrains rejects --brain values that are not plain brain names, such as a family pattern, before any token is chosen.

func WindowName

func WindowName(project, task string) string

WindowName is `<project>/<task-slug>`, or the project alone without a task.

func WrapEditsTask

func WrapEditsTask(task string, allow []string, draft bool) string

WrapEditsTask is the brief for a worker in edits mode: the task, the rules of that mode with the commands it may run, then the contract, last.

func WrapSandboxedTask

func WrapSandboxedTask(task string) string

WrapSandboxedTask is the brief for a worker ki runs in a sandbox: the task, the rules of the sandbox, then the status lines without a PR, last.

func WrapTask

func WrapTask(task string, draft bool) string

WrapTask is the brief the worker receives: the task plus the contract.

func WritePrivate

func WritePrivate(path string, v any) error

WritePrivate writes a file only the current user can read; it may hold a token.

func WritePrivateBytes

func WritePrivateBytes(path string, data []byte) error

WritePrivateBytes writes data to a file only the current user can read.

func WriteQueueEntry

func WriteQueueEntry(jobsDir string, e QueueEntry) error

WriteQueueEntry writes the entry into its job folder, atomically.

Types

type AskSetup

type AskSetup struct {
	Sources []string
	// MCPURL is the knowledge base's base URL; Brains its scope header.
	MCPURL string
	Brains []string
	// Vault is the read-only vault server, zero when the machine has no vault.
	Vault MCPServer
	// CodexVault is whether Codex's own config defines the vault server, which
	// is then pointed at the read-only one even when no vault is known here.
	CodexVault bool
}

AskSetup is what one ask needs to start an agent read-only.

type AskState

type AskState struct {
	Question string   `json:"question"`
	Identity string   `json:"identity"`
	Brains   []string `json:"brains"`
	Sources  []string `json:"sources"`
	Scratch  string   `json:"scratch"`
}

AskState is what an ask job records so a follow-up keeps its scope: the question for the transcript, the identity, brains and sources it ran with, and the scratch folder the agent ran in, which an agent's session is filed under.

type AskTurn

type AskTurn struct {
	Question, Answer string
}

AskTurn is one question of a conversation and the answer it got.

func AskChain

func AskChain(jobsDir string, prev Result) []AskTurn

AskChain is the turns of the conversation prev ends, oldest first. It follows Continues links through the jobs folder and stops at the first job that is gone or has no ask record, so a pruned root only shortens it.

type CheckRun

type CheckRun struct {
	Name       string
	Status     string
	Conclusion string
}

CheckRun is one check run on the head commit.

type Checkouts

type Checkouts struct {
	// Roots are searched one and two levels deep, so ~/code finds
	// ~/code/acme/app.
	Roots []string
	// Paths name a checkout directly and win over Roots.
	Paths map[string]string
}

Checkouts maps project names to local checkouts.

func LoadCheckouts

func LoadCheckouts(file, home string) (*Checkouts, error)

LoadCheckouts reads mecca.yaml; a missing file means the default root only.

func ParseCheckouts

func ParseCheckouts(data []byte, home string) (*Checkouts, error)

ParseCheckouts reads mecca.yaml, expanding a leading ~ to home.

func (*Checkouts) Find

func (c *Checkouts) Find(name, repo string, originOf func(dir string) string) (string, error)

Find returns the checkout for a project name. repo is the project's normalised GitHub URL from projects.yaml, or "" for a name it does not list; with a repo, a candidate counts only if originOf(dir) is that repo, so a same-named folder of another owner is never picked.

type Checks

type Checks struct {
	Runs     []CheckRun
	Statuses []CommitStatus
	// Incomplete is true when GitHub has more than ki read, so "all green" cannot be shown.
	Incomplete bool
}

Checks are everything GitHub reports on a head commit.

func (Checks) NotReady

func (c Checks) NotReady() string

NotReady says why the checks do not allow an approval, "" when they do.

func (Checks) Summarize

func (c Checks) Summarize() Summary

Summarize sorts every check into passed, skipped, pending or failing. Success, skipped and neutral count as ready; pending is not ready.

type Comment

type Comment struct{ Open, Close string }

Comment styles for the files ki manages.

func MarkdownComment

func MarkdownComment() Comment

MarkdownComment wraps markers for AGENTS.md.

func TOMLComment

func TOMLComment() Comment

TOMLComment wraps markers for config.toml.

type CommitStatus

type CommitStatus struct {
	Context string
	State   string
}

CommitStatus is one legacy commit status on the head commit.

type CursorPermissions

type CursorPermissions struct {
	Permissions struct {
		Allow []string `json:"allow"`
		Deny  []string `json:"deny"`
	} `json:"permissions"`
}

CursorPermissions is a workspace's .cursor/cli.json.

func AskCursorPermissions

func AskCursorPermissions(sources []string) CursorPermissions

AskCursorPermissions allows the source tools of ki's MCP servers and nothing else. Cursor's ask mode refuses every edit and shell command, and an MCP call it is not told to allow; this lets the sources through.

type Delegate

type Delegate struct {
	// Allow lists the shell commands a worker in edits mode may run, each a
	// binary or `binary subcommand`, in the order the file gives them.
	Allow []string
	// Stall is how long a streaming worker may print nothing before ki ends it
	// as STALLED; zero means DefaultStall.
	Stall time.Duration
	// NotifyStall asks for a macOS notification when a job stalls.
	NotifyStall bool
	// Queue makes --when-available the default: a job whose role has no
	// provider available waits in the queue instead of being refused.
	Queue bool
	// QueueParallel is how many queued jobs may run at once; zero means DefaultQueueParallel.
	QueueParallel int
}

Delegate is the machine's policy for headless workers.

type Headless

type Headless struct {
	Task        string
	LastMessage string
	// Instructions go in front of the task for Codex and Cursor, which take no
	// system-prompt file; Claude Code gets them as a flag, agy gets none.
	Instructions string
}

Headless makes BuildLaunch start the agent non-interactively with Task as its prompt and JSON on stdout. LastMessage is the file Codex writes its final message to (-o); Claude Code and Cursor return it inside their JSON.

type IssueRef

type IssueRef struct {
	Owner  string
	Repo   string
	Number int
}

IssueRef is a GitHub issue, as --issue prints it: owner/repo#N.

func ParseIssueArg

func ParseIssueArg(arg, owner, repo string) (IssueRef, error)

ParseIssueArg reads --issue. A bare number uses owner and repo from the checkout's origin; owner/repo#N stands alone.

func (IssueRef) String

func (r IssueRef) String() string

type Launch

type Launch struct {
	Argv []string
	Env  map[string]string
}

Launch is the agent process to exec.

func BuildLaunch

func BuildLaunch(in LaunchInput) Launch

BuildLaunch returns the command and extra environment for the agent. Claude Code gets the MCP config, instructions and settings as flags; other agents read KI_* from the environment through their own configuration. With no knowledge base (MCPURL empty) none of the KB variables are set. With Headless the agent's non-interactive flags and the task come last.

type LaunchInput

type LaunchInput struct {
	Agent            string
	AgentArgs        []string
	Session          Session
	Token            string
	MCPURL           string
	MCPConfigPath    string
	InstructionsPath string
	GHToken          string
	// Model, when set, is passed to the agent (claude and codex take --model);
	// every agent also sees it as KI_MODEL. Empty leaves the agent's default.
	Model string
	// ModeArgs are the agent's permission flags, from ModeArgs. They go before
	// AgentArgs so the user's own flags come last.
	ModeArgs []string
	// Effort is passed to Claude Code and agy as --effort; other agents have no equivalent.
	Effort string
	// Headless, when set, starts the agent non-interactively on one task (ki delegate).
	Headless *Headless
	// Resume, when set, reopens that agent session instead of starting a new one.
	Resume string
	// Settings is Claude Code's --settings JSON (SessionSettings); empty means ClaudeSettings.
	Settings string
}

LaunchInput gathers what BuildLaunch needs.

type MCPConfig

type MCPConfig struct {
	MCPServers map[string]MCPServer `json:"mcpServers"`
}

MCPConfig is the file passed to `claude --mcp-config`.

func AddVaultServer

func AddVaultServer(cfg MCPConfig, kiBinary, vaultDir string) MCPConfig

AddVaultServer adds the vault server to a config when vaultDir is set.

func AskMCPConfig

func AskMCPConfig(s AskSetup, token string, cursor bool) MCPConfig

AskMCPConfig is the MCP config of an ask for Claude Code (--mcp-config) or, with cursor set, for Cursor's workspace. Cursor's file sits in the directory the agent reads, so it names the token through ${env:KI_TOKEN} instead of holding it; Claude Code's sits outside, in the job folder.

func NewMCPConfig

func NewMCPConfig(url, token string, brains []string) MCPConfig

NewMCPConfig builds the client config for the KB server.

type MCPEntry

type MCPEntry struct {
	Agent     string   `json:"agent"`
	Name      string   `json:"name"`
	Source    string   `json:"source"`
	Transport string   `json:"transport"`
	Target    string   `json:"target"`
	Status    string   `json:"status"`
	Brains    []string `json:"brains,omitempty"`
}

MCPEntry is one MCP server one agent can reach. It holds only what is safe to print: the target is a URL's host or a command's name, never a path, query, argument, header or environment value, so no token can reach the output.

func ParseClaudeList

func ParseClaudeList(out string, project []string) []MCPEntry

ParseClaudeList reads `claude mcp list`: one `name: target [(HTTP)] - status` line per server after a health-check header. project names the servers the repo's .mcp.json defines, which the list does not distinguish from user ones.

func ParseCodexTOML

func ParseCodexTOML(source string, data []byte) []MCPEntry

ParseCodexTOML reads the [mcp_servers.NAME] tables of Codex's config.toml: only each server's url and command. Sub-tables (env, headers) are skipped.

func ParseMCPJSON

func ParseMCPJSON(agent, source string, data []byte) ([]MCPEntry, error)

ParseMCPJSON reads an `mcpServers` JSON file (Cursor's mcp.json, Claude Code's .mcp.json). Headers and env are never read.

func WithKiServers

func WithKiServers(entries []MCPEntry, agent, kbURL string, brains []string, vault bool) []MCPEntry

WithKiServers makes sure agent's entries include ki's own servers: the KB server with the brains it would get here, and the vault server when the session would start one. A server the agent's own list already shows keeps its status and transport and gains the source and brains.

type MCPServer

type MCPServer struct {
	Type    string            `json:"type,omitempty"`
	URL     string            `json:"url,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
}

MCPServer is one entry in an MCP client config: an HTTP server (URL and headers) or a stdio one (command, args and env).

func ReadOnlyVaultServer

func ReadOnlyVaultServer(kiBinary, vaultDir string) MCPServer

ReadOnlyVaultServer is `ki vault mcp --read-only`: the vault's read tools and no vault_write.

func VaultServer

func VaultServer(kiBinary, vaultDir string) MCPServer

VaultServer is the stdio entry for `ki vault mcp`: the ki binary itself, pointed at the vault. Added only when the machine has a vault.

type Machine

type Machine struct {
	Identities []string
	// Models maps a task class to the model per agent: models.execution.claude
	// = sonnet, models.execution.codex = gpt-5-mini. Agent names are whatever
	// `ki --agent` takes (the binary's base name), so any vendor fits.
	Models map[string]map[string]string
	// Effort maps a task class to low, medium or high (Claude Code only).
	Effort map[string]string
	// Roles maps a task class to the providers that may run it headless
	// (ki delegate --role): see policy.go.
	Roles map[string]Role
	// Delegate is the delegate block: what a worker in edits mode may run.
	Delegate Delegate
	// Sections holds the blocks of registered sections (see machineSection),
	// so a rewrite of the file keeps them.
	Sections map[string]any
}

Machine is the parsed machine file.

func LoadMachine

func LoadMachine(path string, known map[string]struct{}) (*Machine, error)

LoadMachine reads the machine file. A missing file returns nil, nil: the machine carries every identity and sets no models. Unknown keys, unknown identities, unknown classes and malformed names are errors, so a typo fails instead of silently widening or narrowing.

func LoadPolicy

func LoadPolicy(path string) (*Machine, error)

LoadPolicy reads the models, effort, roles and delegate blocks and ignores whether identities still name something in projects.yaml. setup machine uses it when the file does not validate, so a renamed identity can be replaced without dropping a policy that still parses. A missing file returns nil, nil. A block that does not parse is an error, so a rewrite cannot drop it.

func (*Machine) Carries

func (m *Machine) Carries(identity string) bool

Carries reports whether this machine has the identity. A nil Machine (no file) carries every identity.

func (*Machine) DelegateAllow

func (m *Machine) DelegateAllow() []string

DelegateAllow is the edits mode's allow-list, nil when the machine has none.

func (*Machine) EffortFor

func (m *Machine) EffortFor(class string) string

EffortFor is the effort the policy sets for a class, or "".

func (*Machine) ModelFor

func (m *Machine) ModelFor(class, agent string) string

ModelFor is the model the policy sets for a class and an agent, or "" when it sets none (the agent's own default then applies).

func (*Machine) NotifyStall

func (m *Machine) NotifyStall() bool

NotifyStall reports whether a stalled job should raise a notification.

func (*Machine) QueueByDefault

func (m *Machine) QueueByDefault() bool

QueueByDefault reports whether a job with no provider available is queued without --when-available.

func (*Machine) QueueParallel

func (m *Machine) QueueParallel() int

QueueParallel is how many queued jobs may run at once.

func (*Machine) RoleFor

func (m *Machine) RoleFor(name string) (Role, bool)

RoleFor is the role by name, and whether the machine defines it.

func (*Machine) RoleNames

func (m *Machine) RoleNames() []string

RoleNames lists the roles a machine defines, sorted, for messages.

func (*Machine) StallLimit

func (m *Machine) StallLimit() time.Duration

StallLimit is how long a streaming worker may be silent before ki ends it.

func (*Machine) SubagentAllow

func (m *Machine) SubagentAllow() []string

SubagentAllow is the subagent types a ki Claude Code session may start: the machine's list, else DefaultSubagents.

func (*Machine) SubagentPolicy

func (m *Machine) SubagentPolicy() string

SubagentPolicy is SubagentAllow in one line for ki status.

type MeccaNewArgs

type MeccaNewArgs struct {
	Target    string
	Agent     string
	Task      string
	Mode      string
	Name      string
	Brains    []string
	Model     string
	Force     bool
	Attach    bool
	JSON      bool
	AgentArgs []string
}

MeccaNewArgs are the parsed arguments of `ki mecca new`.

func ParseMeccaNew

func ParseMeccaNew(args []string, defaultAgent string) (MeccaNewArgs, error)

ParseMeccaNew parses `ki mecca new <project|path> [flags] [-- agent args]`. Unlike `ki` itself, unknown flags are errors: they would otherwise reach the agent inside a window where the mistake is easy to miss.

type MixedIdentitiesError

type MixedIdentitiesError struct{ Identities []string }

MixedIdentitiesError is the refusal for a folder whose mapped repos belong to more than one identity: a session has one GH_TOKEN and one knowledge-base token for its whole life, so it cannot follow the agent across them.

func (MixedIdentitiesError) Error

func (e MixedIdentitiesError) Error() string

type Mode

type Mode string

Mode is how far an agent may act without asking: ask prompts before each action, auto lets the agent's own reviewer approve actions, edits accepts file edits and runs only the shell commands on an allow-list, skip never asks.

const (
	ModeAsk   Mode = "ask"
	ModeAuto  Mode = "auto"
	ModeEdits Mode = "edits"
	ModeSkip  Mode = "skip"
)

The modes `ki --mode` and KI_MODE accept.

func ParseMode

func ParseMode(s string) (Mode, error)

ParseMode validates a mode; empty means ask.

type NoPlannerError

type NoPlannerError struct {
	Skipped []Skipped
	Now     time.Time
}

NoPlannerError is the refusal when every provider of roles.planner is skipped.

func (NoPlannerError) Error

func (e NoPlannerError) Error() string

type Outcome

type Outcome struct {
	Last    string
	Session string
	// Model is the model the agent says answered, "" when it says nothing.
	Model   string
	Tokens  Tokens
	CostUSD float64
	// Err is the agent's own failure (is_error, turn.failed), "" when it ran to the end.
	Err string
	// QuotaFor is how long the provider reported it will remain over quota.
	QuotaFor time.Duration
}

Outcome is what ki read back from a worker's output.

func ParseOutput

func ParseOutput(agent string, m Mode, stdout []byte, lastMessage string) Outcome

ParseOutput reads the agent's stdout in the format headlessArgs asked for. lastMessage is the -o file's content for Codex; it wins when present. m is the mode the worker ran in, so a refusal can say what to change.

type PRRef

type PRRef struct {
	Owner  string
	Repo   string
	Number int
}

PRRef is a pull request: owner/repo#N.

func ParsePRRef

func ParsePRRef(arg string) (PRRef, error)

ParsePRRef reads a PR URL or owner/repo#N.

func (PRRef) String

func (r PRRef) String() string

type PickInput

type PickInput struct {
	Role   string
	R      Role
	Ledger []Result
	// Reserved are picks whose job has not reached the ledger yet; they take
	// their turn and count against daily caps like a recorded job.
	Reserved  []Reservation
	Now       time.Time
	Installed func(agent string) bool
}

PickInput is what a pick looks at: the role, the machine's job history, the time, and whether an agent is on this machine. Nothing here touches the network: availability is what the ledger last saw.

type Provider

type Provider struct {
	Agent     string
	Model     string
	Weight    int
	DailyJobs int
}

Provider is one entry of a role: an agent, optionally its model, its share of round-robin turns and a cap on jobs per day (0 is none).

func HealthProviders

func HealthProviders(m *Machine, ledger []Result, since time.Time) []Provider

HealthProviders lists the providers worth reporting on: those the roles name, then agents the ledger saw since the given time that no role covers.

func (Provider) Name

func (p Provider) Name() string

Name is the agent and model as written in machine.yaml: codex:gpt-5-mini.

type ProviderHealth

type ProviderHealth struct {
	Provider string `json:"provider"`
	// Jobs is how many of the provider's latest jobs the counts cover.
	Jobs     int            `json:"jobs"`
	Outcomes map[string]int `json:"outcomes"`
	// MedianS is the median duration, in seconds, of those that ran (not LAUNCH_FAILED).
	MedianS float64 `json:"median_s"`
	Skip    string  `json:"skip,omitempty"`
	Demoted string  `json:"demoted,omitempty"`
}

ProviderHealth is one provider's recent outcomes and what the pick does with it now.

func Health

func Health(in PickInput, providers []Provider) []ProviderHealth

Health reads the ledger the way a pick does and reports each provider.

type PullRequest

type PullRequest struct {
	Title          string
	State          string
	Merged         bool
	Draft          bool
	Author         string
	HeadSHA        string
	HeadRef        string
	BaseRef        string
	MergeableState string
}

PullRequest is what approval decisions read from GitHub.

func (PullRequest) MergeBlocker

func (p PullRequest) MergeBlocker() string

MergeBlocker says why GitHub would not merge the PR right now without bypassing a rule, "" when it would. The mergeable state already folds in required reviews, required checks and conflicts, so ki never reads branch protection itself and never asks to bypass it.

func (PullRequest) OwnedBy

func (p PullRequest) OwnedBy(login string) bool

OwnedBy reports whether login wrote the PR; GitHub refuses a self-approval.

func (PullRequest) Refusal

func (p PullRequest) Refusal() string

Refusal says why a PR cannot be approved or merged at all, "" when it can.

type QueueEntry

type QueueEntry struct {
	ID    string `json:"id"`
	Title string `json:"title,omitempty"`
	Role  string `json:"role"`
	// Repo is the checkout the job runs in.
	Repo  string `json:"repo"`
	Issue string `json:"issue,omitempty"`
	// Args are the `ki delegate` arguments to run, without --when-available.
	Args []string `json:"args"`
	// ResumeOf is the job a queued `ki delegate resume` continues.
	ResumeOf string    `json:"resume_of,omitempty"`
	Queued   time.Time `json:"queued"`
	// Reason is why no provider was available at the last look.
	Reason     string     `json:"reason"`
	StartAfter *time.Time `json:"start_after,omitempty"`
	// Starting is set when `ki queue run` hands the job to a ki process;
	// Pid is that process once it is running.
	Starting *time.Time `json:"starting,omitempty"`
	Pid      int        `json:"pid,omitempty"`
}

QueueEntry is one queued job: what to run, where, and why it waits.

func ReadQueue

func ReadQueue(jobsDir string) ([]QueueEntry, error)

ReadQueue returns every queue entry, oldest first; no jobs folder means none.

func ReadQueueEntry

func ReadQueueEntry(jobsDir, id string) (QueueEntry, error)

ReadQueueEntry reads one job's queue entry.

func (QueueEntry) Result

func (e QueueEntry) Result() Result

Result is the entry as `ki delegate ls` shows it.

func (QueueEntry) Started

func (e QueueEntry) Started(now time.Time) bool

Started reports whether a ki process holds the entry: marked starting and either running or still inside the grace for recording its pid.

func (QueueEntry) Waiting

func (e QueueEntry) Waiting() bool

Waiting reports whether the entry is still waiting for a start.

type Reservation

type Reservation struct {
	ID       string    `json:"id"`
	Role     string    `json:"role"`
	Provider string    `json:"provider"`
	Model    string    `json:"model,omitempty"`
	At       time.Time `json:"at"`
}

Reservation is a turn taken by a job that has not reached the ledger.

func ReadReservations

func ReadReservations(dir string) ([]Reservation, error)

ReadReservations returns the reservations in the jobs folder dir, oldest first.

type Result

type Result struct {
	ID string `json:"id"`
	// Title is a short human label: --title, else the issue title, else the brief's first sentence.
	Title    string `json:"title,omitempty"`
	Provider string `json:"provider"`
	Role     string `json:"role,omitempty"`
	// Model is the model that ran (see ResolvedModel); ModelRequested is the
	// one ki passed, "" when the agent chose. The latter is always written so
	// a record from before the split, which has only model, can be told apart.
	Model          string `json:"model,omitempty"`
	ModelRequested string `json:"model_requested"`
	Repo           string `json:"repo,omitempty"`
	Issue          string `json:"issue,omitempty"`
	// Kind is "" for a delegated task, "review" for the agent `ki approve --review` runs
	// and "approve" for the approval itself; PR is the pull request (owner/repo#N) of the last two.
	Kind     string `json:"kind,omitempty"`
	PR       string `json:"pr,omitempty"`
	Branch   string `json:"branch,omitempty"`
	Worktree string `json:"worktree,omitempty"`
	Status   string `json:"status"`
	Detail   string `json:"detail"`
	// Note is what the planner must still do or know: a check ki skipped for a sandboxed worker.
	Note       string     `json:"note,omitempty"`
	Session    string     `json:"session,omitempty"`
	Last       string     `json:"last,omitempty"`
	Started    time.Time  `json:"started"`
	DurationS  float64    `json:"duration_s"`
	QuotaUntil *time.Time `json:"quota_until,omitempty"`
	Tokens     Tokens     `json:"tokens"`
	CostUSD    float64    `json:"cost_usd,omitempty"`
	Exit       int        `json:"exit"`
	// Pid is the worker while the job is RUNNING; the final result.json leaves it out.
	Pid int `json:"pid,omitempty"`
	// KiPid is the ki process that owns the job while it is RUNNING. The worker's
	// pid is gone before ki has recorded the end, so only both gone means LOST.
	KiPid int `json:"ki_pid,omitempty"`
	// LastEventAt is when a streaming worker last printed an event (its start
	// before the first one). Absent for an agent that prints once at the end.
	LastEventAt *time.Time `json:"last_event_at,omitempty"`
	// StallS is the silence, in seconds, after which ki ends the job as STALLED.
	StallS float64 `json:"stall_s,omitempty"`
	// TimedOut marks a FAILED job ki killed at --timeout, which routing reads as a hung provider.
	TimedOut bool `json:"timed_out,omitempty"`
	// Tail is the last progress lines of a job ended as STALLED, QUOTA or at the timeout.
	Tail []string `json:"tail,omitempty"`
	// Commits and DiffStat are how far a QUOTA job got: its commits on the
	// branch (oldest first, `<sha> <subject>`) and `git diff --stat` against
	// where the branch started, uncommitted changes included.
	Commits  []string `json:"commits,omitempty"`
	DiffStat string   `json:"diff_stat,omitempty"`
	// ResumedFrom is the job this one continues (`ki delegate resume`).
	ResumedFrom string `json:"resumed_from,omitempty"`
	// Continues is the ask job this one continues (`ki ask --continue`), and
	// Resumed how: "session" when the agent reopened the earlier session,
	// "transcript" when a fresh run was given the earlier turns.
	Continues string `json:"continues,omitempty"`
	Resumed   string `json:"resumed,omitempty"`
	// Ask is what a later `ki ask --continue` needs from an ask job.
	Ask *AskState `json:"ask,omitempty"`
	// Queued is when the job entered the queue, absent for one that started at once.
	Queued *time.Time `json:"queued,omitempty"`
	// StartAfter is, for a QUEUED job, the earliest time a provider of its role is expected back.
	StartAfter *time.Time `json:"start_after,omitempty"`
}

Result is one job as written to jobs/<id>/result.json and printed by `ki delegate --json`. The ledger holds the same minus Last.

func ReadLedger

func ReadLedger(path string) ([]Result, error)

ReadLedger returns every recorded job, oldest first; no file means none.

func ReadResult

func ReadResult(jobsDir, id string) (Result, error)

ReadResult reads one job's result.json.

func ReadRunning

func ReadRunning(jobsDir string) ([]Result, error)

ReadRunning returns the jobs whose result.json says RUNNING, newest first, with a dead worker's job marked LOST. The ledger is append-on-finish, so these exist only as job folders.

func ReadSettled

func ReadSettled(jobsDir, id string) (Result, error)

ReadSettled reads one job's result.json, a RUNNING one whose worker is gone as LOST only when ki's own process is gone too, and unless the record changed while the pids were checked.

type Role

type Role struct {
	Strategy  string
	Providers []Provider
}

Role is a strategy over providers.

type RoleProvider

type RoleProvider struct {
	Agent string `json:"agent"`
	// Model is the provider's own, else the machine's model for the role's
	// class and the agent, "" when the agent chooses.
	Model string `json:"model"`
	// Available is whether the agent is installed here.
	Available bool   `json:"available"`
	Health    string `json:"health"`
	Reason    string `json:"reason,omitempty"`
	// Ask is whether `ki ask` can run it read-only.
	Ask bool `json:"ask"`
}

RoleProvider is one provider of a role as the next pick sees it.

type RoleState

type RoleState struct {
	Strategy  string         `json:"strategy"`
	Providers []RoleProvider `json:"providers"`
}

RoleState is a role's strategy and its providers in the order written.

type RunArgs

type RunArgs struct {
	Brains []string
	Agent  string
	Model  string
	Mode   string
	Force  bool
	// Identity is --identity: outside a repo it picks the session's identity;
	// inside one it must be the repo's.
	Identity  string
	AgentArgs []string
	// AgentGiven is true when --agent named the agent, as opposed to defaultAgent.
	AgentGiven bool
}

RunArgs are the parsed arguments of `ki [run]`.

func ParseRunArgs

func ParseRunArgs(args []string, defaultAgent string) RunArgs

ParseRunArgs parses `ki [--brain B]... [--agent A] [--model M] [--mode M] [--identity NAME] [--force] [-- agent args]`. Unknown arguments are passed through to the agent.

type Session

type Session struct {
	Projects  []string
	Brains    []string
	Sensitive bool
	Identity  *projects.Identity
	Board     string
	// Unmapped is true for a repo that is not in projects.yaml. It gets cortex
	// only (plus any --brain), no identity check and no GH_TOKEN, so ki refuses
	// to start it without --force.
	Unmapped bool
	// Folder is true for a session started outside a git repo (ResolveFolder,
	// IdentitySession): there is no repo email to check and no repo to refuse.
	Folder bool
}

Session is what a ki session in one repo may see and who it acts as.

func IdentitySession

func IdentitySession(cfg *projects.Config, id projects.Identity, extra []string) Session

IdentitySession is the session `--identity NAME` asks for outside a repo: that identity's gh account, cortex and the brains of its projects that are not sensitive (a sensitive brain is never in a default scope and has to be named), plus extra.

func Resolve

func Resolve(cfg *projects.Config, remote string, extra []string) Session

Resolve finds the scope for the repo with this git remote. A repo listed under several project names gets the union of their brains. An unknown repo is Unmapped and gets cortex only, never "every brain the token grants".

func ResolveFolder

func ResolveFolder(cfg *projects.Config, remotes, extra []string) (Session, error)

ResolveFolder is Resolve for a folder that is not inside a repo: remotes are the origin remotes of the git repos directly under it. Mapped repos of one identity give that identity and the union of their projects' brains, sensitive ones included exactly as Resolve does for one repo; repos that are not in projects.yaml are ignored; none mapped gives a cortex-only session with no identity. Several identities are a MixedIdentitiesError.

type SessionAgent

type SessionAgent struct {
	Agent  string
	Source string
	// Provider is the planner role's pick, set only when Source is SourcePlanner.
	Provider Provider
	// Skipped are the planner providers passed over, set when the role was read.
	Skipped []Skipped
}

SessionAgent is the agent a session starts and why.

func ResolveSessionAgent

func ResolveSessionAgent(flag, envAgent string, m *Machine, in PickInput) (SessionAgent, error)

ResolveSessionAgent picks the session's agent: the agent given on the command line, else KI_AGENT, else the first eligible provider of roles.planner, else claude. in is read only for the planner role.

func (SessionAgent) Model

func (s SessionAgent) Model(flag, envModel string, m *Machine) string

Model is the session's model: --model, then KI_MODEL, then the picked provider's own, then models.judgement.<agent>, "" for the agent's default.

func (SessionAgent) Notes

func (s SessionAgent) Notes() []SkipNote

Notes lists the skipped providers for status output.

type Sessions

type Sessions struct {
	// Subagents lists the built-in subagent types a Claude Code session may
	// start; ["*"] allows every type. Empty allows none.
	Subagents []string
}

Sessions is the machine's policy for the agents ki starts.

type Settings

type Settings struct {
	KnowledgeBase struct {
		URL string `yaml:"url"`
	} `yaml:"knowledge_base"`
}

Settings is config.yaml: the settings that are not projects.

func LoadSettings

func LoadSettings(path string) (Settings, error)

LoadSettings reads config.yaml. A missing file is an empty Settings, so the fallback layout keeps working without one; unknown keys are errors.

type Skill

type Skill struct {
	Name string
	// Dir is the folder the skill's own files are in.
	Dir string
	// Role is ki-role: the policy role that picks the agent, "" for the default.
	Role string
	// Tools is ki-tools: what the skill may do beyond reading. Empty is read-only.
	Tools []string
	// Agents is ki-agents: the only agents that can run it, empty for any.
	Agents []string
	Body   string
}

Skill is a SKILL.md as `ki skill run` reads it: the frontmatter fields ki acts on and the procedure after them.

func LoadSkill

func LoadSkill(path string) (*Skill, error)

LoadSkill reads and checks a SKILL.md.

func ParseSkill

func ParseSkill(data []byte) (*Skill, error)

ParseSkill splits a SKILL.md into its frontmatter and procedure and checks the ki fields, collecting every problem.

type SkillWorkspace

type SkillWorkspace struct {
	// Checkout is what the worktree holds ("pull request #12", "branch main"), "" for a scratch folder.
	Checkout string
	// SHA is the commit the worktree is detached at; Branch the branch on origin, "" when unknown.
	SHA, Branch string
	// Repo is owner/repo on GitHub, "" when the run has no GitHub repo.
	Repo string
}

SkillWorkspace says where a skill run happens, for its brief.

type SkipNote

type SkipNote struct {
	Provider string `json:"provider"`
	Reason   string `json:"reason"`
	Demoted  bool   `json:"demoted,omitempty"`
}

SkipNote is a skipped planner provider as status reports it.

type Skipped

type Skipped struct {
	Provider Provider
	Reason   string
	Demoted  bool
	// Until is when the reason lapses, zero when no time is known (not on PATH).
	Until time.Time
}

Skipped says why a provider was passed over in one pick. A Demoted one is not passed over: it stays in the list to try, moved behind the rest.

type SubagentGuard

type SubagentGuard struct {
	// Binary is the absolute path of the running ki.
	Binary string
	// Allow lists the subagent types the session may start.
	Allow []string
	// Worker marks a headless session (ki delegate, ask, skill run), whose
	// denial must not point at ki delegate: a worker does the work itself.
	Worker bool
}

SubagentGuard describes the hook of one session.

func NewSubagentGuard

func NewSubagentGuard(kiBinary string, m *Machine, worker bool) *SubagentGuard

NewSubagentGuard is the guard the machine policy asks for, nil when it allows every type and no hook is registered.

type Summary

type Summary struct {
	Passed  int      `json:"passed"`
	Skipped int      `json:"skipped"`
	Pending []string `json:"pending,omitempty"`
	Failing []string `json:"failing,omitempty"`
}

Summary counts the checks the way the JSON result shows them.

type Tokens

type Tokens struct {
	Input     int `json:"input"`
	Output    int `json:"output"`
	CacheRead int `json:"cache_read"`
}

Tokens is what the agents report in common, zero where one does not.

type Verdict

type Verdict struct {
	Approve bool
	// Reason is the one-line reason of a CHANGES verdict.
	Reason string
	// Security is what the review says touches a security surface, "" when nothing does.
	Security string
	// Findings is the review text before the verdict line.
	Findings string
}

Verdict is what a review agent concluded.

func ParseVerdict

func ParseVerdict(last string) (Verdict, error)

ParseVerdict reads a review's final message. Only its last non-empty line counts, so a verdict quoted inside the findings never decides.

type Window

type Window struct {
	ID         string    `json:"id"`
	Index      int       `json:"index"`
	Name       string    `json:"name"`
	Project    string    `json:"project,omitempty"`
	Agent      string    `json:"agent,omitempty"`
	Identity   string    `json:"identity,omitempty"`
	Task       string    `json:"task,omitempty"`
	Mode       string    `json:"mode,omitempty"`
	Dir        string    `json:"dir,omitempty"`
	Created    time.Time `json:"created,omitzero"`
	Activity   time.Time `json:"activity,omitzero"`
	Dead       bool      `json:"dead"`
	ExitStatus int       `json:"exit_status,omitempty"`
	Status     string    `json:"status"`
	Note       string    `json:"note,omitempty"`
}

Window is one window in the ki-mecca session.

func Classify

func Classify(w Window, tail string, now time.Time) Window

Classify sets w.Status and w.Note from the window state and, for a quiet window, the last lines on its screen.

func FindWindow

func FindWindow(ws []Window, ref string) (Window, error)

FindWindow matches ref against a window id (@3), index (3) or exact name.

func ParseWindows

func ParseWindows(out string) ([]Window, error)

ParseWindows reads `tmux list-windows -F ListFormat` output.

type WorkDone

type WorkDone struct {
	// Base is the ref the branch started from, such as origin/main.
	Base string
	// Commits are the branch's commits since Base, oldest first, `<sha> <subject>`.
	Commits []string
	// DiffStat is `git diff --stat` against Base, uncommitted changes included.
	DiffStat string
	// Untracked are new files git does not track yet.
	Untracked []string
	// Diff is the diff against Base, cut at HandoffDiffLines.
	Diff string
}

WorkDone is how far a stopped job got, read from its worktree.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL