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
- Variables
- func Age(d time.Duration) string
- func AgentFamily(agent string) string
- func AgyRule(entry string) string
- func AgySettingsPath(home string) string
- func Alive(pid int) bool
- func AppendLedger(path string, r Result) error
- func AppendLineOnce(path, line string) error
- func ApproveBody(security string) string
- func AskArgs(agent string, s AskSetup) []string
- func AskBrief(question string, sources []string) string
- func AskBriefAfter(question string, sources []string, history string) string
- func AskGitHub(agent string) bool
- func AskHistory(turns []AskTurn, max int) string
- func AskSupported(agent string) bool
- func AsksBrowserCheck(task string) bool
- func AttributionLine(line string) string
- func BackAt(skipped []Skipped) time.Time
- func BriefTitle(brief string) string
- func BriefTitleFile(jobsDir, id string) string
- func Candidates(in PickInput) (try []Provider, skipped []Skipped)
- func CapLines(s string, n int) string
- func CheckSkillTool(entry string, fromCaller bool) error
- func ClaudeAttributionIsOff(content []byte) bool
- func ClaudeAttributionOff(content []byte) (out []byte, changed bool, err error)
- func ClaudeToolRule(entry string) string
- func CleanOption(s string) string
- func CleanTitle(s string) string
- func Clock(d time.Duration) string
- func CodexMCPBlock(url string, vault MCPServer) string
- func CombineInstructions(harness, config string) string
- func CursorRule(instructions string) string
- func EnsureAgyAllow(path string, entries []string) ([]string, error)
- func EnsureCursorSandbox(dir string) (bool, error)
- func ExpandHome(p, home string) string
- func FindSkill(name string, dirs []string) (string, error)
- func GuardBash(command string) string
- func HandoffTask(task string, prev Result, p WorkDone) string
- func HasBlock(content string, c Comment) bool
- func HeadlessSupported(agent string) bool
- func HooksEnv(base []string, dir string) map[string]string
- func IdentityProblem(s Session, actualEmail string) string
- func InstructionsRunFile(runDir, text string) string
- func IssueBranch(number int, title string) string
- func IssueBrief(ref IssueRef, title, body string) string
- func LeakMatch(text string) string
- func LockQueue(ctx context.Context, jobsDir string, wait time.Duration) (unlock func(), err error)
- func MeccaEnv(getenv func(string) string) map[string]string
- func MeccaKiArgv(kiBinary string, a MeccaNewArgs) []string
- func MentionsTooling(s string, terms []string) bool
- func MergeEnv(base []string, extra map[string]string) []string
- func MissingConfigFiles(dir string) []string
- func ModeArgs(agent string, m Mode, agentArgs []string) (args []string, overridden bool, err error)
- func ModeArgsAllow(agent string, m Mode, agentArgs, allow []string) (args []string, overridden bool, err error)
- func NeedsTail(w Window, now time.Time) bool
- func NewJobID(now time.Time) string
- func ParseAskStatus(last string) (status, detail string)
- func ParseSandboxedStatus(last string) (status, detail string)
- func ParseSince(v string, now time.Time) (time.Time, error)
- func ParseSkillStatus(last string) (status, detail string)
- func ParseSources(s string) ([]string, error)
- func ParseStatus(last string) (status, detail string)
- func ParseVerdictStatus(last string) (status, detail string)
- func PickAndReserve(ctx context.Context, dir string, in PickInput, id string, wait time.Duration) (try []Provider, skipped []Skipped, err error)
- func Progress(line []byte) []string
- func PromptInstructions(instructions, task string) string
- func PruneRunFiles(dir string, maxAge time.Duration, now time.Time) (int, error)
- func PullRequestRefusal(n int) string
- func PullURL(s string) string
- func QuotaFromText(text string, now time.Time) time.Duration
- func ReadOnlyArgs(agent string) ([]string, bool)
- func ReadOnlySupported(agent string) bool
- func RedactTarget(raw string) string
- func Refusal(ref IssueRef) string
- func RemoveQueueEntry(jobsDir, id string) error
- func RenderMachine(m Machine) string
- func ResolveTitle(flag, issueTitle, brief string) string
- func ResolvedModel(agent, requested, reported string) string
- func ResumeArgs(agent, session string) []string
- func ReviewBrief(ref PRRef, pr PullRequest, diff, procedure string) string
- func ReviewProcedure(skill string) string
- func RoleStates(m *Machine, in PickInput) map[string]RoleState
- func RunSessionGuard(in io.Reader, out io.Writer, allow []string, worker bool) error
- func RunSkillGuard(in io.Reader, out io.Writer) error
- func Sandboxed(agent string, m Mode) bool
- func ScrubTooling(text string, terms []string) string
- func SecuritySurface(diff string) string
- func SessionSettings(g *SubagentGuard) string
- func ShorthandAgents() []string
- func SkillBrief(s *Skill, args []string, ws SkillWorkspace) string
- func SkillClaudeArgs(tools, dirs []string, kiBinary string, sub *SubagentGuard) []string
- func SkillGuardSettings(kiBinary string, sub *SubagentGuard) string
- func SkillUnsupported(agent string, tools, agents []string) string
- func SkillVaultWrites(tools []string) bool
- func Slug(s string) string
- func Snippet(fact string, max int) string
- func SortMCP(entries []MCPEntry)
- func SourceLink(cfg *projects.Config, source string) string
- func SourceTitle(source string) string
- func SplitAnswer(last string) (answer string, sources []string)
- func SplitShorthand(args []string) (agent string, rest []string)
- func Streams(agent string) bool
- func StripAttribution(msg string) string
- func SubagentDenied(in io.Reader, allow []string, worker bool) string
- func SupportsMode(agent string, m Mode) bool
- func TaskBranch(title, jobID string) string
- func TokenFile(confDir string, s Session) string
- func UniqueBranch(name, jobID string, taken func(string) bool) string
- func UniqueName(name string, taken []string) string
- func UpsertBlock(content, body string, c Comment, conflict string) (string, error)
- func ValidJobID(s string) bool
- func ValidateBrains(brains []string) error
- func WindowName(project, task string) string
- func WrapEditsTask(task string, allow []string, draft bool) string
- func WrapSandboxedTask(task string) string
- func WrapTask(task string, draft bool) string
- func WriteHooks(dir, kiBinary, repoHooks string) error
- func WritePrivate(path string, v any) error
- func WritePrivateBytes(path string, data []byte) error
- func WriteQueueEntry(jobsDir string, e QueueEntry) error
- type AskSetup
- type AskState
- type AskTurn
- type CheckRun
- type Checkouts
- type Checks
- type Comment
- type CommitStatus
- type CursorPermissions
- type Delegate
- type Headless
- type IssueRef
- type Launch
- type LaunchInput
- type MCPConfig
- type MCPEntry
- type MCPServer
- type Machine
- func (m *Machine) Carries(identity string) bool
- func (m *Machine) DelegateAllow() []string
- func (m *Machine) EffortFor(class string) string
- func (m *Machine) ModelFor(class, agent string) string
- func (m *Machine) NotifyStall() bool
- func (m *Machine) QueueByDefault() bool
- func (m *Machine) QueueParallel() int
- func (m *Machine) RoleFor(name string) (Role, bool)
- func (m *Machine) RoleNames() []string
- func (m *Machine) StallLimit() time.Duration
- func (m *Machine) SubagentAllow() []string
- func (m *Machine) SubagentPolicy() string
- type MeccaNewArgs
- type MixedIdentitiesError
- type Mode
- type NoPlannerError
- type Outcome
- type PRRef
- type PickInput
- type Provider
- type ProviderHealth
- type PullRequest
- type QueueEntry
- type Reservation
- type Result
- type Role
- type RoleProvider
- type RoleState
- type RunArgs
- type Session
- type SessionAgent
- type Sessions
- type Settings
- type Skill
- type SkillWorkspace
- type SkipNote
- type Skipped
- type SubagentGuard
- type Summary
- type Tokens
- type Verdict
- type Window
- type WorkDone
Constants ¶
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.
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.
const ( SourceKB = "kb" SourceVault = "vault" SourceGitHub = "gh" )
Where an answer may come from.
const ( CursorMCPFile = ".cursor/mcp.json" CursorCLIFile = ".cursor/cli.json" )
Where Cursor reads a workspace's MCP servers and its permissions.
const ( ResumedSession = "session" ResumedTranscript = "transcript" )
How a follow-up reached the earlier conversation.
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.
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.
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.
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.
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.
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.
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.
const ( StatusWorking = "working" StatusIdle = "idle" StatusNeedsUser = "needs-user" StatusWaiting = "waiting" StatusDone = "done" StatusExited = "exited" )
Window statuses reported by ls.
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.
const ( SourceFlag = "flag" SourceEnv = "KI_AGENT" SourcePlanner = "roles.planner" SourceDefault = "default" )
Where the session's agent came from, highest precedence first.
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.
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.
const ( HealthOK = "ok" HealthSkipped = "skipped" HealthDemoted = "demoted" )
Health of a provider as a role reports it.
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.
const AllowAllSubagents = "*"
AllowAllSubagents turns the guard off when it is the only entry of the policy.
const AskHistoryMax = 20000
AskHistoryMax caps the earlier turns a transcript carries, in characters.
const BreakerCooldown = 10 * time.Minute
BreakerCooldown is how long a provider is skipped after a LAUNCH_FAILED.
const BrowserSkipped = "checks skipped: browser (sandbox)"
BrowserSkipped is added to the result of a sandboxed job whose brief asked for a browser check.
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.
const CodexTable = "[mcp_servers." + MCPServerName + "]"
CodexTable is the config.toml table ki manages for the knowledge base.
const CodexVaultTable = "[mcp_servers." + VaultServerName + "]"
CodexVaultTable is the config.toml table for the local vault server.
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.
const CursorSandboxFile = ".cursor/sandbox.json"
CursorSandboxFile is where Cursor reads a workspace's sandbox policy.
const DefaultCheckoutRoot = "~/code"
DefaultCheckoutRoot is the identity-folder parent from docs/laptop-setup.md.
const DefaultQueueParallel = 2
DefaultQueueParallel is how many queued jobs run at once unless delegate.queue_parallel says otherwise.
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.
const DefaultSessionAgent = "claude"
DefaultSessionAgent starts when nothing else names an agent.
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.
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.
const HookGuardCommand = "delegate guard"
HookGuardCommand is the hidden subcommand the hooks call.
const JobEnv = "KI_JOB"
JobEnv is set in a delegate worker's environment to its job id; ki delegate refuses to start a job when it is set.
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.
const KindAsk = "ask"
KindAsk marks a ledger record of `ki ask`: one read-only question.
const KindSkill = "skill"
KindSkill marks a ledger record of `ki skill run`: one skill, run once.
const LedgerFile = "ledger.jsonl"
LedgerFile is the per-machine job history under the jobs folder, one JSON line per job.
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" )
const MCPServerName = "ki-kb"
MCPServerName is the name agents see the knowledge base under.
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.
const MaxReviewDiff = 200 << 10
MaxReviewDiff is how much of a diff goes into the brief; a bigger one is read from the checkout instead.
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.
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.
const MeccaSession = "ki-mecca"
MeccaSession is the tmux session that holds one window per agent session.
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.
const SkillFile = "SKILL.md"
SkillFile is the file that holds a skill, in its own folder.
const TitleMax = 90
TitleMax is the longest job title, ellipsis included.
const VaultServerName = "ki-vault"
VaultServerName is the name agents see the local vault server under.
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.
const WorkerRole = "" /* 169-byte string literal not displayed */
WorkerRole opens the worker paragraph of every brief: instructions about delegating are for the planner.
Variables ¶
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") )
var AskSources = []string{SourceKB, SourceVault, SourceGitHub}
AskSources is every source, in the order the brief names them.
var Classes = []string{ClassJudgement, ClassExecution, ClassSearch, ClassWriting}
Classes lists the task classes in the order the machine file renders them.
var ConfigFiles = []string{ProjectsFile, ModelsFile, AliasesFile, MCPConfigFile, ConfigFile}
ConfigFiles are the files a configuration directory must hold.
var DefaultSubagents = []string{"Explore"}
DefaultSubagents is the policy of a machine that sets none: read-only search only.
var ErrBadSettings = errors.New("settings file is not a JSON object")
ErrBadSettings means a settings file is not a JSON object ki can update.
var ErrInvalidBrain = errors.New("invalid brain name")
ErrInvalidBrain is returned for a --brain value that is not a brain name.
var ErrMeccaArgs = errors.New("invalid ki mecca arguments")
ErrMeccaArgs wraps every argument error of `ki mecca`.
var ErrNoCheckout = errors.New("no checkout found")
ErrNoCheckout means a project name did not resolve to exactly one checkout.
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.
var ErrNoWindow = errors.New("no such ki-mecca window")
ErrNoWindow means no window matched a reference.
var ErrPRRef = errors.New("invalid pull request")
ErrPRRef is returned for an argument that is neither a PR URL nor owner/repo#N.
var ErrUnmanagedConflict = errors.New("conflicting definition outside the ki managed block")
ErrUnmanagedConflict means the user already defined what ki wants to manage.
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.
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.
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.
var MCPAgents = []string{"claude", "cursor", "codex"}
Agents `ki mcp ls` reports on, in output order.
Functions ¶
func AgentFamily ¶
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 ¶
AgyRule is agy's permission rule for one allow-list entry: command(git), command(git status).
func AgySettingsPath ¶
AgySettingsPath is agy's user settings file under home. Its permissions.allow rules are what headless agy runs without a prompt.
func AppendLedger ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
AskBriefAfter is AskBrief for a follow-up that starts a fresh run: the earlier turns (AskHistory) come first, then the question.
func AskGitHub ¶
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 ¶
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 ¶
AskSupported reports whether ki can start the agent unable to write.
func AsksBrowserCheck ¶
AsksBrowserCheck reports whether a brief asks for a browser check.
func AttributionLine ¶ added in v0.2.1
AttributionLine returns line when it credits an agent, "" otherwise. A human co-author trailer is not attribution.
func BackAt ¶
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 ¶
BriefTitle is the first sentence of a brief's first non-empty line, without a leading "Repo: ... ." clause or markdown marks.
func BriefTitleFile ¶
BriefTitleFile is BriefTitle of a job's brief.md, "" when it cannot be read.
func Candidates ¶
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 CheckSkillTool ¶
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 ¶
ClaudeAttributionIsOff reports whether settings already hide both attributions.
func ClaudeAttributionOff ¶
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 ¶
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 ¶
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 ¶
CleanTitle redacts credentials, collapses whitespace and caps the text at TitleMax on a word boundary.
func CodexMCPBlock ¶
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 ¶
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 ¶
CursorRule wraps the agent instructions as an always-applied Cursor project rule.
func EnsureAgyAllow ¶
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 ¶
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 FindSkill ¶
FindSkill locates a skill: a path to a SKILL.md or its folder, else the first <dir>/<name>/SKILL.md among dirs.
func GuardBash ¶
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 ¶
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 HeadlessSupported ¶
HeadlessSupported reports whether ki knows the agent's non-interactive flags.
func HooksEnv ¶ added in v0.2.1
HooksEnv is the environment that points git at the hooks in dir: one more config entry after any GIT_CONFIG_COUNT already in base.
func IdentityProblem ¶
IdentityProblem explains why git would commit as the wrong person, or returns "".
func InstructionsRunFile ¶
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 ¶
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 ¶
IssueBrief is the worker's task when --task is not given: the issue itself.
func LeakMatch ¶ added in v0.2.1
LeakMatch returns the first thing in text that must not reach GitHub, "" for ordinary text.
func LockQueue ¶
LockQueue takes the queue's flock, so a run of the queue, a cancel and a queued job recording its start never interleave.
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 ¶
MentionsTooling reports whether s names the tooling or one of terms.
func MergeEnv ¶
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 ¶
MissingConfigFiles lists the required files absent from dir.
func ModeArgs ¶
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 ¶
NeedsTail reports whether Classify needs the pane's visible text: only quiet, live windows do, so ls skips capture-pane for the rest.
func ParseAskStatus ¶
ParseAskStatus reads an ask's final message: any answer is DONE, an empty one FAILED.
func ParseSandboxedStatus ¶
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 ¶
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 ¶
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 ¶
ParseSources reads --source: a comma-separated subset of AskSources.
func ParseStatus ¶
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 ¶
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 ¶
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 ¶
PromptInstructions is the task with the instructions in front, for agents that take no system-prompt file in headless mode.
func PruneRunFiles ¶
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 ¶
PullRequestRefusal is what --issue says for a number that is a pull request.
func QuotaFromText ¶
QuotaFromText is quotaDuration for text outside the agent's JSON, such as what it printed to stderr before dying.
func ReadOnlyArgs ¶
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 ¶
ReadOnlySupported reports whether ReadOnlyArgs knows the agent.
func RedactTarget ¶
RedactTarget reduces a server's URL or command line to its host or command name.
func Refusal ¶
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 ¶
RemoveQueueEntry drops a job from the queue, and its folder when nothing else is in it.
func RenderMachine ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Sandboxed reports whether ki runs the agent in a sandbox that cannot reach git remotes: Cursor in auto mode (--sandbox enabled).
func ScrubTooling ¶
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 ¶
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 ¶
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 ¶
SkillVaultWrites reports whether the tools let the skill write notes.
func SortMCP ¶
func SortMCP(entries []MCPEntry)
SortMCP orders entries by agent (claude, cursor, codex), then name.
func SourceLink ¶
SourceLink is the GitHub page of a source "<project>/<path>", or "" when the project is not in the projects file.
func SourceTitle ¶
SourceTitle names a document by its file: the base name without extension, with dashes and underscores read as spaces.
func SplitAnswer ¶
SplitAnswer separates an answer from its trailing Sources list. An answer without one is all answer and no sources.
func SplitShorthand ¶
SplitShorthand takes a leading agent name off a session's arguments: `ki codex --mode auto` is `ki --agent codex --mode auto`.
func Streams ¶
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 StripAttribution ¶ added in v0.2.1
StripAttribution removes the lines of a commit message that credit an agent and the blank lines they leave at its end.
func SubagentDenied ¶
SubagentDenied says why a subagent call may not run, "" when it may.
func SupportsMode ¶
SupportsMode reports whether ki knows agent's flags for m.
func TaskBranch ¶
TaskBranch is the branch of a job that has no issue: chore/, the slug of its title and the job id's random part, so jobs started together on one task get different branches. The whole id stays out of it, since a branch name reaches GitHub.
func TokenFile ¶
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 ¶
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 ¶
UniqueName appends -2, -3, ... until name is not taken.
func UpsertBlock ¶
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 ¶
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 ¶
ValidateBrains rejects --brain values that are not plain brain names, such as a family pattern, before any token is chosen.
func WindowName ¶
WindowName is `<project>/<task-slug>`, or the project alone without a task.
func WrapEditsTask ¶
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 ¶
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 WriteHooks ¶ added in v0.2.1
WriteHooks writes the job's hooks into dir: the two ki owns and a pass-through for every other executable hook in repoHooks (the directory the repository's hooks come from), so pointing git at dir loses none of them.
func WritePrivate ¶
WritePrivate writes a file only the current user can read; it may hold a token.
func WritePrivateBytes ¶
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
// VaultPaths are the vault folders the read-only server is limited to;
// empty means the whole vault.
VaultPaths []string
// 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.
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 ¶
LoadCheckouts reads mecca.yaml; a missing file means the default root only.
func ParseCheckouts ¶
ParseCheckouts reads mecca.yaml, expanding a leading ~ to home.
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.
type CommitStatus ¶
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 ¶
IssueRef is a GitHub issue, as --issue prints it: owner/repo#N.
func ParseIssueArg ¶
ParseIssueArg reads --issue. A bare number uses owner and repo from the checkout's origin; owner/repo#N stands alone.
type Launch ¶
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 ¶
MCPConfig is the file passed to `claude --mcp-config`.
func AskMCPConfig ¶
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 ¶
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 ¶
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 ¶
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 ¶
ParseMCPJSON reads an `mcpServers` JSON file (Cursor's mcp.json, Claude Code's .mcp.json). Headers and env are never read.
func WithKiServers ¶
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 ¶
ReadOnlyVaultServer is `ki vault mcp --read-only`: the vault's read tools and no vault_write. With paths it reads only those vault folders, one --path each.
func VaultServer ¶
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 ¶
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 ¶
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 ¶
Carries reports whether this machine has the identity. A nil Machine (no file) carries every identity.
func (*Machine) DelegateAllow ¶
DelegateAllow is the edits mode's allow-list, nil when the machine has none.
func (*Machine) ModelFor ¶
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 ¶
NotifyStall reports whether a stalled job should raise a notification.
func (*Machine) QueueByDefault ¶
QueueByDefault reports whether a job with no provider available is queued without --when-available.
func (*Machine) QueueParallel ¶
QueueParallel is how many queued jobs may run at once.
func (*Machine) StallLimit ¶
StallLimit is how long a streaming worker may be silent before ki ends it.
func (*Machine) SubagentAllow ¶
SubagentAllow is the subagent types a ki Claude Code session may start: the machine's list, else DefaultSubagents.
func (*Machine) SubagentPolicy ¶
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.
type NoPlannerError ¶
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 ¶
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 ¶
PRRef is a pull request: owner/repo#N.
func ParsePRRef ¶
ParsePRRef reads a PR URL or owner/repo#N.
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 ¶
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 ¶
HealthProviders lists the providers worth reporting on: those the roles name, then agents the ledger saw since the given time that no role covers.
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 is the branch that holds the job's work: the pull request's head
// when the job ended PR, else the one the worktree ended on. ScratchBranch is
// the name ki gave the worktree, kept only when the worker renamed it.
Branch string `json:"branch,omitempty"`
ScratchBranch string `json:"scratch_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 ¶
ReadLedger returns every recorded job, oldest first; no file means none.
func ReadResult ¶
ReadResult reads one job's result.json.
func ReadRunning ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ParseSkill ¶
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 ¶
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 ¶
Classify sets w.Status and w.Note from the window state and, for a quiet window, the last lines on its screen.
func FindWindow ¶
FindWindow matches ref against a window id (@3), index (3) or exact name.
func ParseWindows ¶
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.
Source Files
¶
- agents.go
- agy.go
- approve.go
- ask.go
- askchain.go
- branch.go
- checkouts.go
- config.go
- cursor_sandbox.go
- delegate.go
- folder.go
- handoff.go
- health.go
- hooks.go
- instructions.go
- issue.go
- jobs.go
- kb.go
- ki.go
- leak.go
- machine.go
- machine_sections.go
- machine_sessions.go
- mcp.go
- mecca.go
- mode.go
- model.go
- pick.go
- planner.go
- policy.go
- queue.go
- quota.go
- rolestate.go
- running.go
- session_guard.go
- skill.go
- skill_guard.go
- stream.go
- title.go