CandyCode
Terminal AI coding agent
Terminal AI coding agent, inspired by charmbracelet/crush. It talks to eleven provider type keys over nine engines, runs thirty-eight built-in tools on every launch behind hooks and a six-mode permission gate, keeps per-turn workspace checkpoints with undo and rewind, prunes and compacts its own context, runs sub-agents you can watch and message, and reads skills, memory, MCP servers, workflows and SQLite-backed sessions. It also serves a WebSocket API with a browser UI and an Agent Client Protocol agent for editors, all on the sugar-core render loop with Markdown replies. With no configuration it runs offline on the built-in echo provider.
Install
composer require sugarcraft/candy-code
Requires PHP ^8.3. The package declares its sugarcraft/* siblings with the @dev constraint (composer.json), so a host project must allow dev-stability packages: set "minimum-stability": "dev" with "prefer-stable": true in that host, or run it from a checkout of the monorepo. The package's own composer.json declares both keys (lines 111-112), but Composer reads stability settings from the root project only, so that declaration does not reach a host. A container build is described in docs/DOCKER.md.
Winget and Scoop are not documented as install channels, on purpose. Their manifests in candy-code/packaging/winget and candy-code/packaging/scoop are templates with {{VERSION}} and hash placeholders, and no workflow in the repository renders or publishes them, so a Winget or Scoop command here would name an install that does not exist. The install script and the Homebrew formula described in the README remain the standalone installs. Running candy-code in CI, with the composite action and the GitLab example, is covered in docs/CI.md.
Quickstart
Step 1. Run it with nothing configured. The binary falls back to the offline echo provider, so no network and no key are needed. This is the output of a real run, captured with no provider environment and an empty HOME:
$ candy-code -p "explain the Width helper"
You said:
> explain the Width helper
The line candy-code: no provider configured (…); answering from the offline echo provider. goes to stderr, which is why it is not in the output above. -p is the one-shot mode: it never attaches to the terminal and never opens the alternate screen. Run candy-code with no arguments for the full TUI.
Step 2. Point it at a real model. The provider is chosen by CANDY_CODE_PROVIDER, and the provider's own environment variables supply the key (see the providers table below):
export CANDY_CODE_PROVIDER=openai
export OPENAI_API_KEY=sk-...
export CANDY_CODE_MODEL=gpt-4o # optional; the provider default otherwise
candy-code
A provider run needs a key and network access, so its output is not captured on this page. The offline run above is the reference output.
Step 3. One-shot with JSON output, for scripts. The unattended -p mode starts in the default permission mode and refuses any tool call that would ask, so pass --permission-mode when a script needs tools. This is the captured output (the session_id differs on every run):
$ candy-code -p "audit this" --output-format json
{"schema":1,"result":"You said:\n\n> audit this","refusals":[],"session_id":"3b8c2910e15dae8b"}
$ candy-code -p "audit this" --output-format json | jq -r .result
You said:
> audit this
For a provider-free backend, CANDY_CODE_BACKEND_CMD names a script that reads the JSON history on stdin and writes the reply to stdout; CANDY_CODE_BACKEND_CMD_STREAM is the token-stream variant. Every variable is listed in docs/ENVIRONMENT.md. The step-by-step first run is in docs/TUTORIAL.md.
What it is
ProviderInterface with capability introspection (supportsStreaming(), supportsVision(), contextWindow(), costPer1kTokens()), streaming, function calling and embeddings. OpenAI and Azure share one engine; Anthropic, Claude Code CLI, Codex, SGLang, Bedrock, Vertex, Gemini, and custom (with OpenRouter as a preset) make up the rest. The Claude Code and Codex routes run each turn inside the vendor's own signed-in CLI.EngineBackend::complete() calls the provider, runs the returned tool calls through the hook gate, feeds results back, and repeats until the model answers without calling a tool or maxSteps is reached.ApplyPatch (multi-file patches, all or nothing), search, web fetch and search, skills, language server queries (Lsp), memory, repo map, todo, context pruning and compression, workflows, team board, user questions, plan exit, schedules, sub-agent messaging, media generation, canvas pages, scripts, and background and interactive shells. Path tools are jailed to the project root, plus any read-only roots in the user-tier references setting, and an edit is refused on a file that changed since it was read. Six more tools join only when their condition holds; the full list is in the tools section. Implement Tools\Tool for your own.ProtectFilesHook, ConfirmRemoveHook and AuditHook (registered by HookManager::registerBuiltIns()), plus BashEscapeDenyHook when a worktree root is set, and PermissionGateHook last, which adapts the six-mode PermissionGate onto the same chain. Hooks load from YAML, and an external ScriptHook chooses its outcome by exit code.SKILL.md files inject prompt context. The system prompt carries only each skill's name and description; the model loads a full body through the Skill tool. Ten built-ins ship with the app, and you can add more under ~/.candy-code/skills and <project>/.candy-code/skills, or import them from Claude Code and opencode.Task tool delegates to agent presets, each with its own model, tools, skills and permission mode. Runs can go in parallel, nest, run in the background, or run in a git worktree of their own, and each one can be resumed. Each run gets a live line, an agents strip and an Agent View with its own transcript, where you can message, pause, cancel, or send it to the background with Ctrl+X b. SendMessage, Subagents and InterruptAgent steer sub-agents, a parallel batch shares a board, and teammates claim tasks from a shared SQLite board through the Team tool.WorkflowEngine runs multi-stage agent pipelines (sequential, fan-out parallel, chained, and task-then-verifier) from a PHP DSL or YAML. A run can be paused at a stage boundary and resumed, each task can name its own agent preset, and hard token and cost budgets pause a run when they are reached..mcp.json, with ${VAR} interpolation. A project's servers start only after you trust them. The stdio host, candy-code mcp serve, exposes a fixed read-only tool roster (Read, Glob, Grep, Ls, RepoMap) to the client that spawns it. Per-preset mcpServers allowlists are enforced.~/.candy-code/session.db), with foreign-key cascades and fork, rename and resume. Opt-in retention (sessionRetentionDays) removes sessions idle for that long that have no name you gave them, skipping pinned and sub-agent sessions. A title the model generated does not count as a name, so those sessions are removed too. The database is not encrypted.Prune, Compress and Recall tools, re-injection after a compaction, and recovery from context overflows, cut-off replies and dropped streams.Alt+M toggles plan mode, and the model leaves plan mode with PlanExit, which puts its plan to you for approval. Shell lines proven read-only, such as simple sed scripts that only read or for and while read loops over read-only bodies, run unasked when permissions.autoAllowReadOnly is on. A per-turn workspace checkpoint sits behind /undo, /redo, /rewind and /diff. An optional sandbox confines Bash: Seatbelt on macOS and Bubblewrap elsewhere, and it is off by default. See permissions and safety.Memory tool saves, edits, deletes and recalls them with BM25 ranking, and the agent consolidates memory at the end of a turn, with a periodic review pass. A git history of the memory directory lets you restore an earlier state.candy-code serve runs sessions headless behind an authenticated WebSocket that speaks candy-code.v1. The CandyCodeWeb browser UI and candy-code attach drive those sessions. Remote access is gated by --allowed-host and --allowed-ips, and --allow-dir-browse (confined to --browse-root) lets a client pick a project directory for a new session. candy-code acp serves editors over the Agent Client Protocol on stdio.@file, @diff and @https://… attachments, $skill mentions for one turn, !command shell lines, opt-in AI! comments saved in your editor, /handoff into a fresh session seeded with a state summary, and /newrule to draft a project rule from the conversation.Model and Program tree with buffer-diffed output: Markdown-rendered replies through SugarMarkdown, a live tool-call lifecycle, unified diffs for Edit results, inline images through sugar-image, mouse zones and text selection through sugar-mouse, and a command palette with fuzzy filtering.How the features above are wired together is in docs/ARCHITECTURE.md. Screen-reader mode, audible cues, reduced motion and contrast are in docs/ACCESSIBILITY.md.
Providers and models
Select a provider with CANDY_CODE_PROVIDER, which accepts openai, azure, anthropic, claude-code, codex, sglang, bedrock, vertex, gemini, openrouter or custom — the eleven type keys in the table below — or with a provider entry in ~/.candy-code/config.json, or from the /model command, which persists the choice. Each type's required and optional keys are validated by ProviderFactory (TYPE_SCHEMAS), and each type's environment reads are in ProviderFactory::defaultConfig(). The engine column names the class that serves the type. Full per-provider setup is in docs/PROVIDERS.md, and adding a new type is covered in docs/ADDING_A_PROVIDER.md.
| Type key | Engine (class) | Environment | Default model |
|---|---|---|---|
openai | OpenAIProvider | OPENAI_API_KEY (required), OPENAI_ORG_ID, OPENAI_BASE_URL | gpt-4o |
azure | OpenAIProvider | AZURE_OPENAI_API_KEY; a resource or a full baseUrl in config | gpt-4o |
anthropic | AnthropicProvider | ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL | claude-sonnet-4-6 |
claude-code | ClaudeCodeProvider | none; runs the signed-in claude CLI (claudePath, default claude) | claude-sonnet-4-6 |
codex | CodexProvider | none; runs the signed-in codex CLI (codexPath, default codex) | gpt-5.1-codex-mini |
sglang | SglangProvider | OPENAI_BASE_URL (default http://localhost:30000), optional SGLANG_API_KEY | Qwen/Qwen3.8-Flash-Next-FP8 |
bedrock | BedrockProvider | AWS_REGION or AWS_DEFAULT_REGION (default us-east-1) | us.anthropic.claude-sonnet-4-6 |
vertex | VertexProvider | GCP_PROJECT_ID (required); location defaults to us-central1 | claude-sonnet-4-6 |
gemini | GeminiProvider | GEMINI_API_KEY, GEMINI_BASE_URL | gemini-2.5-flash |
openrouter | CustomProvider (OpenAI-compatible preset) | OPENROUTER_API_KEY | openai/gpt-4o |
custom | CustomProvider | OPENAI_BASE_URL (default http://localhost:8080); in config, name, baseUrl and model are required | gpt-4o |
Types that have a cheaper auxiliary model for titles and other small calls: anthropic and vertex (claude-haiku-4-5), bedrock (us.anthropic.claude-haiku-4-5) and openai (gpt-4o-mini), per ProviderFactory::AUXILIARY_MODEL_BY_TYPE. CANDY_CODE_MODEL overrides the conversation model for whichever provider runs.
API reference
Every public class, interface, trait and enum in the SugarCraft\Code namespace has a row, grouped under its namespace with its method table. So do the ten largest public types under src/, wherever they sit. Each other sub-namespace gets one line stating its public type count. The listing is generated from the source PHPDoc; types and methods marked @internal are left out.
Only methods declared in candy-code/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\Code
Attachment final readonly class
A file attachment for a message. Immutable value object.
| Method | Summary |
|---|---|
__construct(public string $path, public AttachmentType $type, public ?string $data = null, public ?string $mimeType = null, public ?string $skill = null) | |
name(): string | The last path segment - what the transcript chip and notices show. |
AttachmentType enum
Type of file attachment.
Cases: File · Image · Document
PHP also provides cases().
Backend interface
Pluggable assistant backend.
| Method | Summary |
|---|---|
complete(array $history, ?callable $onToken = null, ?callable $onEvent = null): Message | |
completeAsync(array $history, ?callable $onToken = null, ?CancellationToken $cancellation = null, ?callable $onEvent = null): PromiseInterface | Async version of complete(). Returns a promise that resolves to the assistant's reply Message. |
Chat final class
The chat shell, as a SugarCraft Model.
| Method | Summary |
|---|---|
__construct(public readonly array $history = [], string $inputBuf = '', public readonly bool $inFlight = false, ?Backend $backend = null, private readonly bool $streaming = false, private readonly ?\Closure $onToken = null, private readonly array $tools = [], private readonly ?\Closure $onToolCall = null, private readonly ?\SugarCraft\Code\Agents\AgentPoolConfig $agentPoolConfig = null, private readonly ?\SugarCraft\Code\Agents\AgentWorkerPool $effectivePool = null, ?WorkflowEngineInterface $workflowEngine = null, ?AgentManager $agentManager = null, private readonly ?CompactorConfig $compactorConfig = null, ?MemoryStore $memoryStore = null, \SugarCraft\Code\Session\SessionStore|\SugarCraft\Code\Session\EnhancedSessionStore|null $sessionStore = null, ?string $currentSessionId = null, ?SessionTabState $tabState = null, ?\Closure $sessionMint = null, private readonly ?\DateTimeImmutable $lastActivityAt = null, private readonly int $slashMenuIndex = 0, private readonly int $mentionMenuIndex = 0, private readonly bool $mentionMenuDismissed = false, private readonly string $themeName = 'dark', private readonly ?PaletteState $palette = null, private readonly ?\Closure $onConfigChange = null, private readonly int $generation = 0, private readonly ?CancellationToken $inFlightCancellation = null, private readonly ?float $lastEscapeAt = null, private readonly ?float $lastCtrlCAt = null, private readonly ?\SugarCraft\Code\Permissions\PermissionMode $reviewModeRestore = null, private readonly ?int $rows = null, private readonly ?int $cols = null, private readonly ?\SugarCraft\Image\Mosaic $mosaic = null, private readonly ?HookManager $hooks = null, private readonly ?string $currentSessionName = null, private readonly ?Backend $titleBackend = null, private readonly PermissionFlow $flow = new PermissionFlow(), private readonly array $permissionGrants = [], private readonly array $expanded = [], private readonly array $paletteMru = [], private readonly int $scrollOffset = 0, private readonly array $pasteChips = [], private readonly int $pasteCounter = 0, private readonly ?\SugarCraft\Code\Background\BackgroundSupervisor $backgroundSupervisor = null, private readonly array $backgroundStatuses = [], private readonly ?SessionPicker $sessionPicker = null, ?\ArrayObject $liveToolEvents = null, private readonly string $streamingText = '', private readonly string $reasoningText = '', private readonly ?string $projectRoot = null, private readonly ?int $keyHelp = null, ?TextArea $input = null, ?TokenTracker $tokenTracker = null, private readonly ?float $maxCostUsd = null, private readonly ?Backend $summaryBackend = null, private readonly ?string $pendingCompactionId = null, private readonly ?array $pendingIdleCompaction = null, private readonly int $consecutiveRefillCompactions = 0, private readonly array $queuedPrompts = [], private readonly ?array $pendingTurnHooks = null, private readonly ?array $resolvedTurnHooks = null, private readonly ?array $pendingCustomCommand = null, private readonly ?array $resolvedCustomCommand = null, private readonly ?CommandLoader $commandLoader = null, ?array $customCommands = null, private readonly bool $projectCommandsTrusted = false, private readonly array $trustedBundleCommands = [], private readonly array $mcpPromptShell = [], private readonly bool $drainsRuntimeNotices = false, ?RulesState $rulesState = null, private readonly ?int $promptEstimateAtDispatch = null, private readonly ?float $tokenEstimateCalibration = null, private readonly ?WebSearch $webSearch = null, private readonly ?array $promptSuggestion = null, private readonly ?PromptHistory $promptHistory = null, ?array $inputHistory = null, private readonly ?int $inputHistoryCursor = null, private readonly string $inputHistoryDraft = '', private readonly bool $workflowTurnInFlight = false, ?DebouncedTranscriptWriter $transcriptWriter = null, private readonly bool $sessionLocking = false, private readonly ?SessionLock $sessionLock = null, private readonly bool $readOnlySession = false, private readonly ?string $readOnlyDraft = null, private readonly ?string $initialPrompt = null, private readonly ?\Closure $backendFactory = null, private readonly ?\SugarCraft\Code\Host\WorkspaceContext $workspace = null, private readonly ?\SugarCraft\Code\Events\StepStarted $liveStep = null, private readonly ?\SugarCraft\Code\Events\UsageUpdated $liveUsage = null, private readonly int $liveStepGeneration = -1, private readonly ?\SugarCraft\Code\Session\TitleSource $currentSessionTitleSource = null, private readonly ?\SugarCraft\Forms\TextInput\TextInput $titleEditor = null, private readonly ?array $pendingQuickAdd = null, private readonly array $pendingSettingsApply = [], private readonly ?\SugarCraft\Toast\Toast $settingsToast = null, private readonly int $settingsToastGeneration = 0, private readonly ?array $backgroundSummary = null, private readonly ?\SugarCraft\Code\Tui\DirectoryPicker\DirectoryPicker $dirPicker = null, private readonly ?\SugarCraft\Code\Tui\HistorySearch $historySearch = null, private readonly ?string $relaunchDir = null, private readonly ?\SugarCraft\Code\Background\ScheduleRegistry $scheduleRegistry = null, public readonly ComposerVim $composerVim = new ComposerVim(), private readonly EventSink $eventSink = new NullEventSink(), private readonly bool $tabHosted = false, private readonly ?\SugarCraft\Code\Agents\PrimaryAgent $primaryAgent = null, private readonly bool $incognito = false, ?bool $resumeCostGuardArmed = null, private readonly ?array $compactionRecord = null, private readonly int $transcriptEpoch = 0) | |
init(): ?\Closure | Arm the mid-session seam's edge-driven wake-up (E193) AND gather the startup summary's expensive facts off the paint path (VIS-1-P2). |
update(Msg $msg): array | |
static storedPermissionGrants(\SugarCraft\Code\Session\SessionStore|EnhancedSessionStore|null $store, ?string $sessionId): array | The grants $store remembers for $sessionId, as the grant map a Chat opened on that session starts from (Cli\Bootstrap's resume). |
flushTranscript(): void | Write any transcript change still waiting on its debounce tick, now. |
withSessionLocking(): self | Turn on the single-writer session lock and take it for the session this Chat has open. |
isReadOnlySession(): bool | True while another TUI owns the open session — see withSessionLocking(). |
withInitialPrompt(?string $prompt): self | Submit $prompt as this session's first prompt once init() runs — the leftover command-line words. Null or blank clears it. |
static reviveTranscriptMessage(array $row): Message | Rebuild one saved transcript row for a resume: every field Message::fromArray() can restore - tool calls and results, reasoning, usage - with one repair. A "running" placeholder in a saved transcript is a tool call whose process is gone, so it comes back as the same "interrupted" error row reviveCheckpointMessage() makes for /rewind; left as a placeholder it would spin forever for a result that cannot arrive. |
static loadTranscript(\SugarCraft\Code\Session\SessionStore|EnhancedSessionStore|null $store, string $sessionId): array | The saved transcript of $sessionId as Messages, or [] when the store has none (or cannot say) — \SugarCraft\Code\Host\TranscriptStore::load() over $store. |
isTabHosted(): bool | P-TABS.f: the appointment this Chat runs under — true when the App's session deck hosts it as the foreground tab, false standalone. Read by the four session-open routes and their mid-turn refusal gates; set only by withTabHosted() at the App's two chat-swap points. |
withTabHosted(bool $tabHosted): self | P-TABS.f: take the deck appointment from the host. Identity-preserving when the flag already matches, so a factory-less launch's chat-swap points keep their historic object flow byte-identically. |
withSessionPickerOpen(): self | Open the session picker over the chat, as Ctrl+R and /sessions do - the launch-time door for candy-code --resume with no id. Unchanged when there is no store or nothing to pick. |
keyHelp(): ?int | How far the keybinding reference is scrolled, or null when it is closed. Renderer::renderKeyHelp() reads this to decide whether to draw the overlay at all. |
withKeyHelp(?int $offset): self | Open the keybinding reference at $offset lines down, or close it with null. |
pendingPermission(): ?PermissionRequestMsg | The prompt currently blocking this turn, if any. |
permissionStage(): PermissionPromptStage | Whether the pending prompt is still listening for a letter, has been disarmed by a keystroke that was plainly not an answer, or is waiting on the confirm for a session-wide grant. |
permissionGrants(): array | The calls granted "always" for this session, as [grant key => true]. |
permissionAlwaysScope(): ?string | Delegates to PermissionPrompt::alwaysScope() (W5-A); forensic prose lives there. |
permissionPersistPatterns(): array | Delegates to PermissionPrompt::persistPatterns() (W5-A); forensic prose lives there. |
permissionPersistScope(): ?string | Delegates to PermissionPrompt::persistScope() (W5-A); forensic prose lives there. |
permissionEditableScope(): ?string | Delegates to PermissionPrompt::editableScope() (W5-A); forensic prose lives there. |
permissionScopeError(): ?string | Delegates to PermissionPrompt::scopeError() (W5-A); forensic prose lives there. |
permissionScopeRefusal(string $scope): ?string | Delegates to PermissionPrompt::scopeRefusal() (W5-A); forensic prose lives there. |
permissionMatchedRule(): ?\SugarCraft\Code\Permissions\PermissionRule | The configured or remembered rule that decides the pending permission request, read-only through the gate's \SugarCraft\Code\Permissions\PermissionGate::explainRule() so the prompt names the rule /permissions explain would name. Null when no request is pending, no gate is wired, or no rule speaks. |
permissionAlwaysAsks(): ?string | Delegates to PermissionPrompt::alwaysAsks() (W5-A); forensic prose lives there. |
agentLive(): \SugarCraft\Code\Agents\Live\AgentLiveRegistry | The live state of every delegated run this session has heard about (roadmap P-B2, Appendix P §4.5) — what the line under each Task row is drawn from (Renderer::renderView()). |
enqueueToolEvent(ToolStarted|ToolFinished $event, ?int $generation = null): void | Append a tool-lifecycle event to the live inbox ($liveToolEvents). |
liveToolEvents(): array | Tool-lifecycle events queued by the backend but not yet folded into the transcript, oldest first. |
enqueueToken(string $text, ?int $generation = null): void | Append one fragment of assistant text to the live inbox ($liveToolEvents) — the text counterpart of enqueueToolEvent(), written through by a Backend's $onToken callback (Phase 0 item 13). |
enqueueReasoning(string $text, ?int $generation = null): void | Append one fragment of the model's THINKING to the live inbox ($liveToolEvents) — the EMBEDDER and TEST entry point onto that inbox (E456/E494). |
streamingText(): string | The in-flight reply as far as it has arrived; empty outside a turn, and outside a turn the model has actually started answering. |
reasoningText(): string | The model's thinking for the current step as far as it has arrived; empty outside a turn, and outside a turn whose backend reports reasoning at all. |
queuedPrompts(): array | Prompts typed and sent while a turn was in flight, oldest first — see the constructor param's docblock. |
withReadLedger(\SugarCraft\Code\Tools\ReadLedger $ledger): self | Name the session read ledger (roadmap 3.I-2) the tools this Chat runs record into — the \SugarCraft\Code\Tools\ReadLedger an embedder's registerTool() callbacks' Read/Edit/Write/ ApplyPatch share. Each Chat-native call runs in its own forked child (forkToolCalls()), whose copy of the ledger dies with it; with the ledger named here the child carries what it recorded home on its result payload and collectToolResult() merges it, so a file read by one call is known to the next call's staleness check. |
readLedger(): ?\SugarCraft\Code\Tools\ReadLedger | The read ledger withReadLedger() named, or null when none was. |
view(): string|\SugarCraft\Core\View | Returns the full literal frame every call. This used to compute its own cell-level diff (via Buffer/DiffEncoder) and return only the changed bytes - but Program (see bin/candy-code, a plain new Program(Bootstrap::chat(), ...)) ALSO diffs whatever a Model's view() returns, line-by-line, against the previous call's return value (sugar-core's own Renderer::render(), which every other Model in this framework relies on for exactly this). Chat's pre-diffed cursor-jump escape bytes were never literal display text, so Program's Renderer was diffing one diff's raw bytes against the previous diff's raw bytes as if they were screen content - any time the two differed (i.e. almost always) that produced cursor placement that had no relationship to the actual frame, which is what made typed input / replies appear to land in the wrong row (e.g. the status bar) once a conversation grew past a single frame. Program's Renderer already does correct, safe diffing on real text; doing it a second time here was redundant at best. |
backgroundJobCount(): int | Background work this session can still see: sessions the supervisor reports active, plus the shells this session owns (or the untagged ones) that are running. Counted per paint, so a finished job drops off the status bar on the next frame. |
static mouseMode(): MouseMode | How the terminal is asked to report mouse events (§8 E1). |
static mouseClicksEnabled(): bool | Whether click/drag hit-testing is live. False when either CANDY_CODE_DISABLE_MOUSE (no tracking at all) or CANDY_CODE_DISABLE_MOUSE_CLICKS (clicks off, wheel kept) is set, or the mouse / mouseClicks setting is off (roadmap N-P4g). |
static zoneAt(int $col, int $row): ?Zone | The marked zone under a reported pointer cell, or null when there is none — the one hit-test entry point every future click handler goes through, so CANDY_CODE_DISABLE_MOUSE_CLICKS is enforced in exactly one place instead of at each call site. |
static clickTracker(): ZoneClickTracker | The shared Press+Release pairing state machine (sugar-mouse's ZoneClickTracker), which is what makes a press on a tab followed by a release somewhere else — a drag, or a text selection started on the tab strip — dispatch nothing instead of switching sessions. |
static textSelection(): ?TextSelection | The mouse text selection in progress or just copied, or null. |
static textSelectionInProgress(): bool | True between a press that anchored a selection and its release. |
static clearTextSelection(): void | Drop any selection; for tests and for hosts that stop painting the chat. |
scrollOffset(): int | How far back the transcript is scrolled, in lines from the newest one. 0 means pinned to the bottom. Read by Renderer::render(). |
withScrollOffset(int $offset): self | Scroll the transcript back $offset lines from the newest one. |
static programOptions(): ProgramOptions | Runtime options bin/candy-code starts the chat Program with. Exists so the mouse-mode decision above is made once, next to the state it governs, instead of being duplicated in the entrypoint script. |
backend(): Backend | |
withBackend(Backend $backend): self | Swap the backend — also the live half of a settings save that rebuilds the engine (applySettings()), which only ever calls this between turns: the completion handlers of a running turn close over the backend it started on. |
applySettings(array $changed, ?string $savedTo = null): array | Make a settings save take effect (roadmap N-P3, Appendix N §4.6): each changed key goes by its \SugarCraft\Code\Config\Settings\ApplyMode. |
pendingSettingsApply(): array | The settings keys parked until the running turn ends (applySettings()). |
settingsToast(): ?\SugarCraft\Toast\Toast | The settings-save toast to paint, or null (applySettings()). |
agentPoolConfig(): ?\SugarCraft\Code\Agents\AgentPoolConfig | Get the agent pool config, if set. |
pool(): ?\SugarCraft\Code\Agents\AgentWorkerPool | Get the effective worker pool, if set. |
workspace(): ?\SugarCraft\Code\Host\WorkspaceContext | The launch's workspace — the host services (Appendix O §4.3) this Chat resolves — or null for a Chat built without one (tests, embedders). |
agentManager(): ?\SugarCraft\Code\Agents\AgentManager | Get the agent manager, if set. |
backgroundSupervisor(): ?\SugarCraft\Code\Background\BackgroundSupervisor | The background-session supervisor /bg and /fork dispatch onto, if set. |
withBackgroundSupervisor(?\SugarCraft\Code\Background\BackgroundSupervisor $supervisor): self | Attach the supervisor /bg and /fork spawn onto. |
withScheduleRegistry(?\SugarCraft\Code\Background\ScheduleRegistry $registry): self | Wire the AUT-1 roster (see the constructor note: shared by IDENTITY, like the supervisor — a wither clone must keep pointing at the same clock, or the /schedules surface and the pump diverge). |
scheduleRegistry(): ?\SugarCraft\Code\Background\ScheduleRegistry | The AUT-1 roster this session fires from, if any. |
memoryStore(): ?MemoryStore | Get the memory store, if set. |
rulesState(): RulesState | The session's rulebook toggle set — the state /rules reads and writes (P6.S3). |
projectRoot(): string | The directory this session is rooted at, already resolved — the configured $projectRoot (--root), else the process directory. |
sessionStore(): \SugarCraft\Code\Session\SessionStore|\SugarCraft\Code\Session\EnhancedSessionStore|null | Get the session store, if set. |
incognito(): bool | Whether this launch keeps nothing (C-SES-7.c, --incognito). |
withSessionStore(\SugarCraft\Code\Session\SessionStore|\SugarCraft\Code\Session\EnhancedSessionStore|null $sessionStore): self | Create a new Chat with an explicit session store. |
currentSessionId(): ?string | Get the current session ID, if any. |
openTabs(): SessionTabs | The tabs opened this run (ISS-102): the model Renderer's session tab strip renders and cycleSessionTab() switches through. Thin delegate onto the SessionTabState fold (v4 S3) — the renderer keeps reading this entry point. |
contextLedgerView(): ?\SugarCraft\Code\Context\Pruning\ContextLedger | This session's context ledger as its turn runner holds it, or null when it holds none yet (roadmap 3.B-3) — the copy the transcript's pruned / distilled badges and its compressed-block rows read. Never the store: \SugarCraft\Code\Host\TurnRunner::heldLedger() is a memory read, so Renderer may call this per frame. Kept current by every save — a turn's settle, a live ledger frame, /sweep. |
measureContextCmd(): ?\Closure | P-CTX.d: schedule one context measurement OFF the loop. The pane never measures in view() — assembling prompt sections touches disk — so a settle, a landed compaction, or a dock hand hands this closure to the runner, which resolves it against the memo-backed prompt assembly and answers with a \SugarCraft\Code\App\ContextMeasuredMsg repaint nudge once \SugarCraft\Code\Host\TurnRunner::heldContext() is fresh. The state the pass reads is captured at schedule time, so a slow answer still stamps the transcript it was measured against. No wall-clock timer is armed anywhere (E646): the pass is a single prompt assembly. |
withCurrentSessionId(string $currentSessionId): self | Create a new Chat with an explicit current session ID. |
currentSessionName(): ?string | Name of the current session, or null while it is still unnamed. |
currentSessionTitleSource(): ?\SugarCraft\Code\Session\TitleSource | Who set currentSessionName() — see $currentSessionTitleSource. |
titleEditor(): ?\SugarCraft\Forms\TextInput\TextInput | The open inline session-title editor, or null — read by Renderer. |
withCurrentSessionName(?string $currentSessionName): self | Create a new Chat with an explicit session name. Passing null clears the name, which re-arms the one-shot auto-title. |
withTitleBackend(?Backend $titleBackend): self | Create a new Chat with an explicit small-model Backend used only for the background session-title call. See the constructor's $titleBackend docblock for why it is deliberately a separate instance from the conversation backend. |
workerPool(): ?\SugarCraft\Code\Agents\AgentWorkerPool | Backward-compatible alias for pool(). |
executeAgents(array $agents, \SugarCraft\Code\Providers\CompleteRequest $request): \Generator | Execute multiple agents in parallel via the worker pool. |
withWorkerPool(\SugarCraft\Code\Agents\AgentWorkerPool $pool): self | Create a new Chat with an explicit worker pool. |
withAgentPoolConfig(\SugarCraft\Code\Agents\AgentPoolConfig $config): self | Create a new Chat with an agent pool config (used to build the worker pool on demand). |
withMemoryStore(MemoryStore $memoryStore): self | Create a new Chat with an explicit memory store. |
withWorkflowEngine(WorkflowEngineInterface $engine): self | Create a new Chat with an explicit workflow engine. |
workflowEngine(): ?WorkflowEngineInterface | Get the workflow engine, if set. |
mosaic(): ?\SugarCraft\Image\Mosaic | Get the shared sugar-image probe-once capability instance, if wired (see this class's $mosaic constructor docblock, W1.G2/E2). |
hooks(): ?HookManager | The hook chain gating this Chat's own tool calls, if wired (see the $hooks constructor docblock). |
withHooks(HookManager $hooks): self | Gate this Chat's registerTool() calls through $hooks, the same HookManager the engine pipeline already runs its calls through (§1 E1). |
expanded(): array | Tool-call ids whose output the user has expanded (§1 E5). Renderer::render() reads this to decide which tool bodies to paint in full; ids absent from the map are collapsed. |
isToolOutputExpanded(string $id): bool | True when $id's tool output is currently expanded: its entry in the expanded map, else the default — collapsed, or expanded for a tool call under the expandToolOutput setting (expandedByDefault()). |
toggleToolOutput(string $id): self | Flip one tool call's collapsed/expanded state. Returning a call to its default REMOVES the key - see the constructor's $expanded docblock for why the map only ever holds what the user changed. |
static isDeniedResult(ToolResult $result): bool | True when $result is a refusal - a call the user or a hook stopped - rather than a call that ran and failed. |
static isInterruptedResult(ToolResult $result): bool | True when $result stands in for a tool call that never finished because the process running it went away - see reviveCheckpointMessage(). Distinct from isDeniedResult(): nobody refused this call, it simply lost its runner, and the two deserve different words on screen. |
static reviveCheckpointMessage(array $row): Message | Rebuild one checkpointed history row into a Message, healing a checkpoint that was taken while a tool call was still in flight (§1 E7). |
latestThoughtKey(): ?string | The $expanded key of the newest thought on screen, or null when there is none: the in-flight thought (Renderer::THOUGHT_LIVE_KEY) while one is being written, otherwise the newest history entry carrying reasoning - a settled reply, or a tool row (or its running placeholder) the thought was parked on. Public because Renderer offers the Ctrl+O hint on exactly the row this names. |
lastActivityAt(): ?\DateTimeImmutable | Timestamp of the last real user prompt submitted through submit(), or null if none has been recorded yet on this instance. |
withLastActivity(\DateTimeImmutable $lastActivityAt): self | Create a new Chat with an explicit last-activity timestamp. Mainly useful for tests that need to simulate an idle session. |
resumeCostGuardArmed(): bool | C-SES-7.d: whether the next real prompt will be cost-checked as a resume re-send (see the field docblock). Read by the guard in submit() and pinned by the guard's tests. |
liveStep(): ?\SugarCraft\Code\Events\StepStarted | The step the turn on screen last reported (roadmap 1.C-4), or null when no turn is running or the running one reports no steps (a command backend, a workflow, the echo default). |
liveUsage(): ?\SugarCraft\Code\Events\UsageUpdated | The usage the turn on screen last reported (roadmap 1.C-4); null as for liveStep(). |
stopRequested(): bool | Whether the turn on screen has been asked to stop at its next step boundary (first Escape). |
withStreaming(bool $enable): self | |
onToken(callable $callback): self | |
registerTool(string $name, callable $callback): self | Register a tool callback the AI can call on this Chat: the name joins the Chat's own tool map, which invokeTool() consults and runs at dispatch. The shipped CLI registers nothing here — its tools reach the model as catalogued tool classes wired onto the backend — so this seam is filled only by embedders. Registration is immutable: a new Chat carrying the merged map is returned. |
onToolCall(callable $callback): self | Register a callback for tool call events. |
withOnConfigChange(callable $callback): self | Register a callback(string $key, string $value): void fired when any of FOUR DOORS applies a choice: the Ctrl+P palette's Switch Model row, /model <provider>, the palette's Switch Theme row, and /theme <name>. |
withLaunchNotices(array $notices): self | Seed the transcript with the warnings a LAUNCH produced, so they are readable from inside the alt screen. |
withNoticeDrain(bool $drains): self | Appoints (or dismisses) this Chat as the reader of the shared runtime notice inbox — the drainsRuntimeNotices field's flag, moved. |
isStreaming(): bool | |
tools(): array | |
getTools(): array | BC forwarder for the pre-rename accessor name. |
queueOwnsTab(): bool | Whether a bare Tab QUEUES the draft for after the running turn (roadmap 1.C-3, chat.queue) — the follow-up half of "Enter steers, Tab queues" (Codex, nanobot). Only mid-turn, with a draft that would be sent (not a slash command, which is refused mid-turn), and only when neither completion owns Tab and no modal is up — the same reachability contract as slashMenuOwnsTab(): the shell yields Tab on exactly this predicate, so a yielded Tab always lands on a live arm. |
runCommand(string $commandText): array | Run a command line on the user's behalf — a menu-bar row, Ctrl+N, the shell's provider picker — WITHOUT touching the draft. |
runPaletteAction(string $label): array | Run a palette-only action (a CommandRegistry row flagged slashVisible: false, e.g. "New session") on the user's behalf, by its palette label — the runCommand() twin for rows submit() has no arm for. |
abandonActiveHookGroups(): int | Quit reaps the hook processes still running, the same way \SugarCraft\Code\Agents\AgentWorkerPool::cancelAll() reaps its workers: SIGTERM the group, then SIGKILL after a 2-second grace if it has not gone. The grace runs on the loop, so the quit is not held up by it. |
static reportField(string $value): string | One caller-supplied value, made safe to be PART OF A REPORT LINE — see \SugarCraft\Code\Host\Commands\PermissionsCommand::reportField(), where the /permissions report moved (roadmap O-2h). Kept here because Commands\NoticesCommand, Commands\MemoryHistoryCommand and the provider switch's report all render through this name. |
switchProvider(string $provider): array | The public twin of the /model <provider> command for the shell (C-TUI-5.e): the first-run wizard's Finish hands the provider it chose through this door, so the wizard and the slash command are one path and cannot drift — the workspace rebuild, the persistence hook and the model-catalog priming all live in the command and ride here. |
promptSuggestion(): ?string | The grayed suggestion the empty input box shows, or null when there is none to show: none has arrived, a turn is running, or the conversation has moved since it was written (see the $promptSuggestion docblock). |
primaryAgentName(): ?string | The roster preset this session runs as its PRIMARY agent, or null when it runs the plain launch default (C-AGT-4.b). The status line's agent badge reads this; so does the Alt+A cycle, to know where it stands. |
withLaunchPrimaryAgent(string $name): self | Apply --agent <name> at launch — C3 (RS-AGENT). This is NOT a second switch: it travels switchPrimaryAgent() with $echo on, so the flag, /agent use <name> and Alt+A share one code path, one roster, one refusal vocabulary (unknown name answers with the same host.agents.use_unknown transcript row). A launch has no turn in flight, so the mid-turn door can only pass; a refused name leaves the plain default agent in place and costs nothing but the row. |
shouldWatchIdleCompaction(): bool | Whether the idle auto-compaction watch (CTX-5, compaction.idleAuto) should have a tick running. The membership gate for \SugarCraft\Code\App\App::subscriptions()'s keyed tick — deliberately reading only SESSION-scoped state, never the transcript's size: a session that could fold asks occasionally, and whether THIS minute is a folding minute is the tick's own re-check. |
sessionPicker(): ?SessionPicker | The open session picker overlay, or null when it is closed. |
rewindToCheckpoint(int $stepsBack): array | Rewind the conversation to the checkpoint N prompts back — the message picker's Accept chord (C-TUI-3.d). One row is one step back, the same newest-first counting \SugarCraft\Code\Tui\MessagePicker\MessagePicker::open() gives its rows, and the restore seeds the checkpoint's prompt into the composer exactly as the typed /rewind N --chat does (handleRewindCommand(), applyCommandResult()). |
expandPasteChips(string $text): string | ISS-051: replace every chip in $text with the payload it filed. Called by each reader that sends the draft's text — submit, queue, the AskUser/permission answer, the scope editor and the agent-mailbox send — so the model and the transcript never see the marker. CC-QA-5: the match is STRUCTURAL, not byte-exact — a bracketed run carrying a filed '#N' id and a '+' count tail expands even after a caret splice or a width rewrap moved a character inside the chip; silently dropping the payload behind one mis-clicked key was the defect. Text whose id was never filed — hand-typed chip shapes included — survives literally. |
inputCursorOffset(): int | Where the cursor is in $inputBuf, as a codepoint offset from the start of the whole draft (newlines counted as one codepoint each). |
draft(): array | The composer's state as the shell's window stash saves it (P-AGENT.b): the draft text and the flat caret offset — the two halves withDraft() puts back. A snapshot of the same pair Renderer::renderInput() and the checkpoint capture see. |
withDraft(string $text, int $cursor): self | Replace the composer's whole state (P-AGENT.b): text first through withInputBuf() — which owns the slash/mention-menu re-highlight law and the widget reseed — then the caret through the same seek the alt-chords use, so a stale cursor from a stashed viewport clamps to the restored draft instead of pointing past its end. |
slashMenuMatches(): array | Commands from CommandRegistry matching the in-progress "/name" being typed - the "/" popup's data source (Renderer::renderSlashMenu()). Returns [] (hiding the popup) when inputBuf isn't slash-prefixed, or once it contains a space: at that point the command name is already fixed and the user is typing arguments, so there is nothing left to filter/complete. |
slashCommandRows(): array | Every row the "/" popup and /help may list: the built-in slash-visible rows with this session's file-based commands merged over them by NAME. |
customCommands(): array | The file-based commands this session discovered, name => spec. |
slashMenuMatchResults(): array | slashMenuMatches()'s rows with their matched-character indices kept, in the SAME order and the same length - the spec list is derived from this one inside CommandRegistry::filter(), so the two cannot fall out of step. |
slashMenuIndex(): int | The "/" popup's currently-highlighted row index into slashMenuMatches()'s current result - always in range for it, never needs clamping by a caller (see withInputBuf()'s docblock). |
slashMenuOwnsTab(): bool | Whether a bare Tab completes the "/" popup's highlighted row RIGHT NOW. |
mentionOwnsTab(): bool | Whether a bare Tab completes an @file mention — or a $skill one (roadmap 5.14l) — rather than cycling panes: the caret ends such a token in the draft and no modal is up. The modal guards are slashMenuOwnsTab()'s four, for the reason its docblock gives - a shell that yields Tab on a condition update() does not answer turns Tab into a dead key. |
mentionPopupOpen(): bool | TUI-1: whether the fuzzy @ file popup is up RIGHT NOW — the one predicate the Escape arm, the ↑/↓/Enter arms and the renderer all read, mirroring how slashMenuOwnsTab() is the one predicate both the shell's Tab yield and the completion arm read. |
mentionPopupRows(): array | The popup's rows for the mention token under the caret, best match first (MentionIndex::rank()). Empty for a $skill token — those keep their prefix-only completion — and on a non-git root, where the cold-index fallback (FileMentions::complete() via Tab) stays the whole feature. |
mentionMenuIndex(): int | The highlighted popup row, clamped — a caret move between two mention tokens can leave the stored index past the end of a shorter list. |
theme(): Theme | The active color theme, resolved from the stored name on every call - cheap (a handful of Color/Theme factory calls, no I/O) and keeps Chat's own stored state to a plain string rather than an object. |
withThemeName(string $themeName): self | |
palette(): ?PaletteState | The Ctrl+P command palette's current mode/query/selection, or null when closed. |
paletteMatches(): array | Fuzzy-filtered (or full, when the query is empty) item labels for the palette's current mode, ranked best-match-first via SmithWatermanMatcher - the same matcher phlix-console-client's own Ctrl+P palette already uses for the same purpose - and holding only labels that contain EVERY query character in order (see $paletteMatcher). Returns [] when the palette is closed. |
paletteMatchResults(): array | paletteMatches()'s rows with their matched-character indices kept, in the SAME order - the label list is just this list's haystacks (§4 E3: the indices used to be discarded here, so Renderer::renderPalette() had nothing to highlight with and could only bold whole rows). |
paletteCategory(string $label): ?string | The grouping label ("Session", "Model", …) the palette renders above a root row, or null for a row that has none (provider/theme names). |
paletteMru(): array | Palette rows the user has run, most recent first (§4 E7). |
currentPermissionMode(): ?\SugarCraft\Code\Permissions\PermissionMode | The mode this session's gate runs in, or null without a gate — what the status bar's mode badge reads (Renderer). |
static modeChangeNotice(\SugarCraft\Code\Permissions\PermissionMode $from, \SugarCraft\Code\Permissions\PermissionMode $to): string | The model-visible row for a switch from $from to $to: which mode now governs, that it supersedes earlier switches, and what it allows — \SugarCraft\Code\Permissions\PermissionMode::description(), the sentence /permissions shows, measured against the gate. |
activeThemeName(): string | The name of the theme in use, canonicalised to a member of Theme::names() (theme() resolves the stored spelling through Theme::byName()). The Ctrl+P themes picker reads it to mark the active row (ISS-104). |
dirPicker(): ?\SugarCraft\Code\Tui\DirectoryPicker\DirectoryPicker | The /new folder picker, while it is up. |
historySearch(): ?\SugarCraft\Code\Tui\HistorySearch | The Ctrl+G history search, while it is up (plan_comparison TUI-2). |
pendingRelaunch(): ?string | The directory /new chose to restart candy-code in, once the program has quit; null for an ordinary exit. |
subscriptions(): ?\SugarCraft\Core\Subscriptions | Declare the recurring work this model needs the runtime to drive (section 5 E4). |
backgroundStatuses(): array | Last status reported to the user for each background session, keyed by session id. |
rows(): int | Real terminal row count, from the last WindowSizeMsg this Chat received - falls back to TuiRenderer::terminalSize()'s own detection only when no WindowSizeMsg has arrived yet (a Chat built directly, e.g. in a test, without going through a real Program). |
cols(): int | |
withSize(int $cols, int $rows): self | The same size a WindowSizeMsg would have recorded, as a wither. |
shouldPromptIdleCompaction(int $tokenCount, ?\DateTimeImmutable $lastActivityAt = null): bool | Check if idle compaction should be prompted based on token count and idle time. |
contextUsagePercent(): float | Current history's estimated size as a fraction of contextTokenLimit() - for the status bar's context-usage indicator (Renderer). |
contextTokens(): int | The numerator behind contextUsagePercent(): the current history's size in tokens. Exposed so the status bar can print an absolute count next to the percentage instead of multiplying the fraction back out against a limit it would have to hardcode. |
contextTokenLimit(): int | The denominator behind contextUsagePercent() and the budget every context tier is a percentage of: the 70% reminder, the 85% automatic compaction, the 95% blocking refusal and the idle-compaction prompt. |
contextWindowAssumed(): bool | Whether contextTokenLimit() is the assumed fallback rather than the backend's own window (#6): the status bar and /context must say so, because the same 100,000 shown bare reads as a fact about the model. |
spentUsd(): float | This session's provider-reported spend in US dollars. |
hasReportedSpend(): bool | Whether any settled turn this session actually reported usage. |
maxCostUsd(): ?float | The spend ceiling /budget and $CANDY_CODE_MAX_COST set, or null when this session has none. Always a positive finite number when non-null — isUsableSpendCap(), enforced in the constructor. |
usageSummary(): string | The token/cost line /budget prints — TokenTracker::summary(), so the wording lives with the buckets it describes rather than being re-spelled here. |
static isUsableSpendCap(float $cap): bool | Whether $cap is a spend ceiling this app will act on: a positive, finite number of dollars. |
static isCompactionBoundary(Message $message): bool | Whether $message is the boundary row a compaction wrote — \SugarCraft\Code\Host\CompactionService::isCompactionBoundary(). |
abandonActiveBackendChildren(bool $async = false): int | CC-QA-2: kill any command children the backend spawned but has not reaped, announced once on stderr when anything dies. The two command backends own a live-children registry; the API-path backends (EngineBackend and the summariser) never spawn a process tree and answer 0 here, so this is safe to call from every quit path. Async true while the loop still ticks (the Ctrl+C / double-Escape arms), false from the bin funnel where the loop is already stopped. |
ClaudeCodeMcpClient final class
MCP client that connects to Claude Code via stdio transport. Sends JSON-RPC 2.0 messages and receives responses using non-blocking I/O so the TUI loop stays responsive.
| Method | Summary |
|---|---|
__construct(public readonly ?string $command = null, public readonly array $args = [], public readonly ?array $initialOptions = null, private mixed $process = null, private ?array $pipes = null, private bool $connected = false, private int $requestId = 0, public readonly array $env = [], ?float $handshakeTimeoutSeconds = null) | |
connect(?array $options = null): array | Start the Claude Code MCP process and perform handshake. |
callTool(string $name, ?array $params = null): McpMessage | Send a JSON-RPC request and wait for a response. |
listTools(): McpMessage | List available tools from the MCP server. |
sendMessage(McpMessage $message): void | Send a raw message, DRAINING STDERR AS IT GOES, and either write all of it or say so. |
readMessages(): array | Read whatever complete NDJSON lines the child has produced since last time. |
disconnect(): void | Disconnect and clean up the MCP process, in BOUNDED time. |
isConnected(): bool | |
isUp(): bool | E699: connected AND the child still running — the liveness question childIsRunning() already answers inside the write loop, exposed once for the /mcp panel's snapshot the way \SugarCraft\Code\MCP\StdioMcpServer::isUp() does for it. |
pumpStderr(): void | E699: the bounded stderr drain as an on-demand seam, same contract as \SugarCraft\Code\MCP\StdioMcpServer::pumpStderr() — bounded (16 passes inside drainStderr()), a no-op before connect() and after disconnect(), never throws on a torn-down server. |
__destruct() | |
stderrTail(): string | The tail of the server's stderr, for a caller trying to explain a client that went quiet. Empty when the server has said nothing. |
static forClaudeCode(?array $options = null): self | Create a ClaudeCodeMcpClient with default settings for Claude Code. |
CommandParser final class
Parses user input for slash-commands.
| Method | Summary |
|---|---|
parse(string $input): ?ParsedCommand | Parse a raw input string. |
CompactedGroup final readonly class
A group of files produced by the Compactor. $isCompact is true when this group was formed from small-file bucketing and false when it represents a single large file.
| Method | Summary |
|---|---|
__construct(public string $label, public array $paths, public bool $isCompact) | |
count(): int | |
totalSize(): int |
Compactor final class
Groups small files by extension or MIME-type category to reduce visual clutter in directory listings.
| Method | Summary |
|---|---|
__construct(private readonly int $thresholdBytes = self::DEFAULT_THRESHOLD_BYTES, private readonly int $maxPerGroup = 50) | |
compact(array $paths): array | Compact a list of file paths. |
categoryFor(string $path): string | Return the category name for a file path. |
describe(array $paths): string | $paths counted by categoryFor() category, largest first and then by name: code ×12, config ×3 (roadmap 3.B-5, DCP P2-11 — how a receipt names many file outputs in one line). Pure: it reads only the names, never the filesystem, so it describes paths that are gone or belong to another tree as well as present ones. Empty for no paths. |
describeTargets(iterable $argumentLists): string | describe() over the files a list of tool calls name — each call's file_path argument (Read, Edit, Write, …), once per file: how the pruning receipts (Prune, /sweep, /context's pruned list, roadmap 3.B-5) say what the outputs they took away were about. A call that names no file (Bash, a Grep over a directory) is not counted, so a list of only those describes as empty. Pure, like describe(). |
threshold(): int | Threshold in bytes used for compaction decisions. |
Lang final class
Per-library translation facade for candy-code.
| Method | Summary |
|---|---|
static inLocale(string $locale, callable $fn): mixed | $fn() run with the process locale pinned to $locale, and the previous locale restored however it returns. |
static useLaunchLocale(): string | Select the process locale from the environment, once, at launch, the way POSIX ranks it: the first of LC_ALL, LC_MESSAGES, LANG that is set and non-empty decides — LANG=de_DE.UTF-8 reads de-de, then de, then English per key. |
Message final class
One turn in a chat conversation. Immutable, role-tagged, timestamped. The chat history is a list<Message> carried on the Chat model.
| Method | Summary |
|---|---|
__construct(public readonly Role $role, public readonly string $content, public readonly int $createdAt, public readonly array $attachments = [], public readonly array $toolCalls = [], public readonly array $toolResults = [], public readonly ?string $pendingToolCallId = null, public readonly ?string $reasoning = null, public readonly ?string $imageBytes = null, public readonly ?string $imageProtocol = null, public readonly ?Usage $usage = null, public readonly bool $lengthStopped = false, public readonly bool $stepsTruncated = false, public readonly array $pendingToolArguments = [], public readonly bool $uiOnly = false, public readonly ?string $loopGuardStoppedBy = null, public readonly ?string $attachmentNotice = null, public readonly ?string $pendingToolName = null, public readonly ?string $id = null, public readonly ?int $ref = null, public readonly ?string $stepId = null, public readonly bool $userVisible = true, public readonly array $turnTranscript = [], public readonly ?\SugarCraft\Code\Context\Pruning\ContextLedger $contextLedger = null, public readonly bool $error = false, public readonly array $thinkingBlocks = [], public readonly array $recallTitles = [], ?object $rowKey = null) | |
static user(string $content, ?int $now = null): self | |
static assistant(string $content, ?int $now = null, ?string $reasoning = null): self | |
static system(string $content, ?int $now = null): self | |
static notice(string $content, ?int $now = null): self | A Role::System row written for the user's eyes only - the app reporting on itself (a refusal, a queued prompt, a background status change). Shorthand for system()->withUiOnly(true); see $uiOnly's docblock for why such a row must stay off the model wire. |
static recallNotice(int $count, string $text, array $titles = [], ?int $now = null): self | The structured memory-recall row (C-CTX-6.e): a notice() whose $recallTitles let the transcript expand the count sentence into the recalled notes' titles. $text is the count sentence itself — built by \SugarCraft\Code\Diagnostics\RuntimeNoticeSink::recallRowText() at every pump so the TUI row, the served session's payload and a legacy reader all speak one prose — and $titles are note TITLES (first lines), never bodies. Stays off the model wire by the same uiOnly law as every notice row: the recall fence already showed the model what it recalled. |
static toAgent(string $agentName, string $text, string $badge = '', ?int $now = null): self | The row that records a message the user sent a delegated run from the Agent View (roadmap P-D2, Appendix P §5.3): you → explore · also check the cookie ⧗ queued. A notice(): the parent model is never shown it — what the run did with the message reaches the parent through the Task result's trailer, or not at all for a follow-up the user keeps to themselves. $text is folded to one line; $badge says where the message is. |
static agentVisible(array $history): array | $history without its $uiOnly rows - what a backend may be shown. |
static toolRunning(ToolCall $call, ?int $now = null): self | A transient placeholder shown the moment a tool call is dispatched, before it finishes - see this class's $pendingToolCallId docblock and \SugarCraft\Code\Renderer::renderToolResults() for how it's displayed distinctly from a finished result. $call->id must be non-null and unique per in-flight turn for the later replace-by-id lookup to find the right placeholder; \SugarCraft\Code\Chat only ever calls this with backend-issued tool calls, which always carry an id. |
static describeToolCall(ToolCall $call, bool $bounded = true): string | Human-readable one-liner for a tool invocation. |
attachFile(string $path, ?string $contents = null, ?string $skill = null): self | Attach a file. $contents is the snapshot Attachment::$data the wire inlines; see Attachment for why it is captured once. $skill (lane B) names the skill when the attachment IS a mentioned skill's body, so the transcript chip can say which SKILL.md it is. |
attachImage(string $path, ?string $bytes = null, ?string $mimeType = null): self | Attach an image. $bytes/$mimeType are the snapshot a vision-capable provider is sent (\SugarCraft\Code\Providers\AttachmentEncoding). |
attachDocument(string $path, ?string $bytes = null, ?string $mimeType = null): self | Attach a PDF document (CTX-2). $bytes/$mimeType are the snapshot a document-capable provider is sent as its own block (\SugarCraft\Code\Providers\AttachmentEncoding::anthropicBlocks()). |
withToolCalls(array $toolCalls): self | Create a message with tool calls (for assistant responses that invoke tools). |
withToolResults(array $toolResults): self | Attach the tool result(s) this message reports, keeping its existing content/role/attachments/toolCalls untouched - Renderer uses a non-empty $toolResults to render a distinct "tool call" marker instead of a plain assistant bubble. |
withReasoning(?string $reasoning): self | Attach (or clear, via null) the model's extracted reasoning/thinking text — see this class's $reasoning docblock. Used at the \SugarCraft\Code\Backend\EngineBackend conversion seam so the value \SugarCraft\Code\Messages\AssistantMessage::reasoning() already computed isn't thrown away when crossing into the root Message DTO the TUI actually renders. |
withImage(?string $imageBytes, ?string $imageProtocol): self | Attach image bytes captured by a tool result during this turn (e.g. \SugarCraft\Code\Tools\BuiltIn\Doctor's capability swatch) - W1.G2 reachability fix. Used at the \SugarCraft\Code\Backend\EngineBackend conversion seam, mirroring withReasoning()'s role for the parallel reasoning field. |
withUsage(?Usage $usage): self | Attach (or clear, via null) what the turn cost - see $usage's docblock. Used at the \SugarCraft\Code\Backend\EngineBackend conversion seam, where the per-step figures \SugarCraft\Code\Messages\AssistantMessage::usage() carries have just been summed over the whole bounded loop, mirroring withReasoning()'s role for the parallel reasoning field. |
withLengthStopped(bool $lengthStopped): self | Attach (or clear, via false) the provider's "stopped at the output ceiling" verdict - see $lengthStopped's docblock. Used at the \SugarCraft\Code\Backend\EngineBackend conversion seam alongside withUsage()'s, so the turn the fold judged is the turn the transcript labels. |
withStepsTruncated(bool $stepsTruncated): self | Attach (or clear, via false) the harness's own "step ceiling exhausted mid-turn" verdict - see $stepsTruncated's docblock. Written at \SugarCraft\Code\Backend\EngineBackend::runTurn()'s loop-exit seam and carried across the fork result frame like the flag it shadows. |
withUiOnly(bool $uiOnly = true): self | Mark (or clear, via false) this row as for the user's eyes only - see $uiOnly's docblock. A command echo and its output are built with the ordinary user()/assistant() factories, because that is how the transcript renders them, and flagged here. |
withThinkingBlocks(array $thinkingBlocks): self | CTX-1: carry the signed thinking blocks of the provider reply this row reconstructs, so a later resume/replay hands Anthropic its blocks back. |
withError(bool $error = true): self | Mark (or clear, via false) this row as a failure the renderer must paint as one — see $error's docblock. Implies nothing about $uiOnly: every producer that flags an error today also marks it uiOnly, but the two axes stay orthogonal so a future agent-visible error notice need not leak its styling into the model's history. |
withLoopGuardStoppedBy(?string $toolName): self | Attach (or clear, via null) the loop guard's "this turn was ended" verdict — see $loopGuardStoppedBy's docblock. Written at \SugarCraft\Code\Backend\EngineBackend's loop-exit seam beside withStepsTruncated() and carried across the fork result frame the same way. |
withAttachmentNotice(?string $notice): self | Attach (or clear, via null) the attachment-degradation report - see $attachmentNotice's docblock. Written by \SugarCraft\Code\Backend\EngineBackend::complete() and carried across the fork result frame beside $loopGuardStoppedBy. |
withIdentity(?string $id, ?int $ref): self | Give this row its storage id and model-facing ref - see $id's and $ref's docblocks. Written by \SugarCraft\Code\Session\EnhancedSessionStore::loadTranscript()'s rows (through fromArray()). A row minted in this process gets its identity from the store's first save of it instead, keyed by its rowKey() so a wither's copy is the same row to it, and read back live through \SugarCraft\Code\Host\TranscriptStore::identityOf(). An empty id clears it; a ref below 1 clears it. |
withStepId(?string $stepId): self | Tag (or clear, via null) the engine step that produced this row - see $stepId's docblock. |
withUserVisible(bool $userVisible = true): self | Show (true) or hide (false) this row in the transcript the user reads - see $userVisible's docblock. The agent-side twin is withUiOnly(). |
withTurnTranscript(array $rows): self | Attach (or clear, via []) the rows the turn added - see $turnTranscript's docblock. Anything that is not a Message is dropped. |
withContextLedger(?\SugarCraft\Code\Context\Pruning\ContextLedger $ledger): self | Attach (or clear, via null) the ledger the turn ended with - see $contextLedger's docblock. |
withContent(string $content): self | A copy of this row with $content swapped in and every other field — the row-identity token included — carried through mutate(). |
static settleTurnTranscript(array $history, Message $reply): array | Fold a settled engine reply's $turnTranscript into the history the turn ran over (roadmap 1.B-2), so the next request replays the turn as it happened - each step's assistant row with its tool_calls, its narration and its reasoning, each result paired to its call - instead of every tool result read back as something the assistant said. |
rowKey(): object | An opaque token naming this logical row: the same object on every copy a wither makes of it, a different one on every row built afresh (including a fromArray() revival, which carries its identity in $id/$ref instead). \SugarCraft\Code\Session\EnhancedSessionStore keys the identity it gives a not-yet-reloaded row by it, which is what keeps a live row's id stable across saves (\SugarCraft\Code\Host\TranscriptStore::identityOf()). Compare it by identity only; it carries no data. |
hasImage(): bool | True when this message carries image bytes captured by a tool result during this turn - see $imageBytes's docblock. |
toWire(): array | Wire-format dict used by every HTTP backend adapter. Caller decides whether to filter system messages out (some APIs don't accept them in the messages list). |
jsonSerialize(): array | The persisted shape: every field, keyed by its property name, so a saved transcript row resumes as the message it was (fromArray()). |
static fromArray(array $row): self | Rebuild a message from jsonSerialize()'s shape - or from any older row that carries a subset of it. |
ParsedCommand final class
Result of parsing a slash-command input.
| Method | Summary |
|---|---|
__construct(public readonly string $name, public readonly array $args = []) | |
withArgs(array $args): self |
RenderFrame final class
The per-frame mutable state of one Renderer::renderView() paint.
| Method | Summary |
|---|---|
static new(): self | |
beginNext(): self | The frame for the next paint, begun from this published one. |
recordToolCallZone(string $key, string $label): void | Remember tool call $key as a clickable row, first call per id winning (a duplicate zone id makes the scan throw and costs the frame every zone — see \SugarCraft\Code\Renderer::recordToolCallZone() for the guards that decide whether a row is recordable at all). |
toolCallZones(): array | |
recordToolRowHead(string $head): void | Note the styled head of a tool row this frame emitted, in document order. |
toolRowHeads(): array | |
resetToolRowHeads(): void | |
noteCtrlOThoughtKey(?string $key): void | |
ctrlOThoughtKey(): ?string | |
recordPaletteItemZone(array $item): void | Remember one rendered palette box line as a clickable item row. |
paletteItemZones(): array | |
recordSessionRowZone(array $row): void | Remember one rendered session-picker overlay line as a clickable row. |
sessionRowZones(): array | |
recordAgentLineZone(array $line): void | Remember one live agent line as a clickable row. |
agentLineZones(): array | |
notePaletteAbandoned(bool $abandoned): void | |
paletteAbandoned(): bool | |
noteAgentsPaneDocked(bool $docked): void | |
noteBackgroundJobCount(int $count): void | |
backgroundJobCount(): int | |
agentsPaneDocked(): bool | |
noteAgentView(?array $view): void | |
agentView(): ?array | |
noteFocusedToolRowKeys(array $keys): void | |
focusedToolRowKeys(): array | |
setZoneOrigin(array $origin): void | |
resetZoneOrigin(): void | |
zoneOrigin(): array | |
setSelectableRegion(?array $region): void | |
selectableRegion(): ?array | |
setSelectableLines(array $lines): void | |
selectableLines(): array | |
noteMaxScrollOffset(int $overflow): void | |
maxScrollOffset(): int | |
noteKeyHelpMaxOffset(int $overflow): void | |
keyHelpMaxOffset(): int | |
clearZoneState(): void | Drop the between-frame zone/selection/origin state. This is what Renderer::clearZones() applies to the published frame when a shell paints something that does NOT contain this renderer's output — stale boxes under fresh content would fire the wrong click. maxScrollOffset and keyHelpMaxOffset are NOT zeroed here: every paint that sets them runs before they matter, and a frame that never renders must leave the last clamps standing, exactly as the loose statics always did. |
Renderer final class
Pure view function for Chat — the renderer that actually paints the transcript a real user running bin/candy-code sees.
| Method | Summary |
|---|---|
static toolRowPrefix(): string | Fixed head of a finished tool row, ahead of the model-chosen tool name. Named because renderToolResults() subtracts its width from the row budget and a boundary spelled twice is a boundary that drifts. The word is translated, so the head is built per call and measured by width. |
static skillRowPrefix(): string | The head prefix of a Skill tool row — ✨ skill: <name> instead of the generic 🔧 tool: Skill, so the collapsed transcript says WHICH skill loaded (lane B, skills-qa F1). Pairs with toolRowPrefix(): same shape, same verbatim-prefix law for the click zones. |
static toolOutputExpandedByDefault(): bool | Whether a settled tool call's output is shown in full until the user collapses it: the expandToolOutput setting (roadmap N-P4g, default off — hide-on-success, §1 E5). Chat::expanded() then records only the calls that differ from it, so a false entry is a call the user closed. Thoughts keep their own collapsed default. |
static markDividerCell(string $sideValue, int $absRow, int $frameRows, int $width = 1): string | The marked segment for one band row of a side's resize seam: divider:<side>:r<absRow> wrapping $width cells (the side box's border, any stacked divider column, and the centre's border — see \SugarCraft\Code\Tui\Renderer::dividerZones()). |
static markStackGapRow(string $sideValue, int $slotIndex, int $absRow, int $frameRows, int $width): string | The marked segment for one stacked side's whole intra-stack gap row: stackdiv:<side>:<slotIndex>:r<absRow> wrapping $width cells, where slotIndex is the slot ABOVE the gap. Same degrade rules — and the same one-zone-per-line invariant — as markDividerCell(). |
static markSideRow(string $paneId, string $key, int $absRow, int $frameRows, int $width): string | A siderow:<paneId>:<key> grab span of $width blanks for the scanner scratch row — or plain blanks when clicks are off or the id cannot be marked. Same validation as markDockedPaneHeader(): a key is provider- or model-authored (a tool-call id), and a bad one must cost its row the click, never the frame its zones. |
static markDockedPaneHeader(string $paneId, int $absRow, int $frameRows, int $width): string | The marked header row of a docked pane: pane:<paneId> across the side block's width — the dock-drag gesture's press target. Same degrade rules and one-zone-per-line invariant as markDividerCell(). |
static scanner(): Scanner | Zone registry produced by the most recent scanRoot() pass. Hit-tested by Chat::zoneAt(). |
static publishedFrame(): RenderFrame | The frame this renderer currently owns: the last COMPLETED paint. A render in flight builds its own next frame (renderView's $drawing) and swaps it into this slot only when the frame is whole, so between and after paints this accessor answers the same frame today's statics did. All fourteen per-frame fields live on RenderFrame and are reached through this slot; the RenderFrame class docblock owns the serial-render story for why collecting them into one object matters. |
static setZoneOrigin(int $col, int $row): void | Declare where the frame scanRoot() just scanned ended up on the terminal, in 0-based column/row deltas. |
static zoneOrigin(): array | |
static setPaletteAbandoned(bool $abandoned): void | Declare whether the hosted palette is abandoned for the frame being composited. Called by the shell compositor around its render, never by a standalone Chat render. |
static setAgentsPaneDocked(bool $docked): void | Declare whether the Agents sidepane is docked for the frame being composited. Called by the shell compositor around its render, never by a standalone Chat render. |
static setBackgroundJobCount(int $count): void | Declare how many background jobs are running for the frame being composited, for the status bar's "N bg" segment. Same per-paint lineage as setAgentsPaneDocked(): the shell sets it around one paint, and the default 0 keeps the segment absent everywhere else. Storage: RenderFrame (its backgroundJobCount() read). |
static setAgentView(?array $view): void | Declare the Agent View for the frame being composited (roadmap P-C2), as \SugarCraft\Code\App\App::agentViewFrame() built it, or null for the parent transcript. |
static setFocusedToolRowKeys(array $keys): void | Declare the row-unit keys the shell's SETTLED Ctrl+F cursor stands on for the frame being composited (v2:a11y-F1, W7-B), or the empty list when no cursor is settled. |
static clearZones(): void | Drop the click-zone registry and reset the origin and the abandonment signal. |
static maxScrollOffset(): int | Upper clamp for Chat::scrollOffset(), measured on the last rendered frame. 0 when the transcript fits the window (nothing to scroll) or when nothing has been rendered yet. |
static keyHelpMaxOffset(): int | Upper clamp for Chat::keyHelp(), measured on the last rendered reference. 0 when the whole list fits, or when it has never been drawn. |
static scanRoot(string $frame, int $width, ?RenderFrame $render = null): string | The zone-scan pass, run exactly ONCE per frame and only at the root. |
static render(Chat $chat): string | The frame's text bytes only, discarding any pixel-graphics image layer renderView() collected. |
static renderView(Chat $chat, ?string $agentStripFocus = null, array $agentStripDismissed = []): View | The full frame plus the pixel-graphics layer for any image-bearing tool result in the transcript (§9 E3). |
static selectableRegion(): ?array | The rectangle of the last frame a mouse drag may select text in, as inclusive [rowFrom, rowTo, colFrom, colTo] cells of that frame, or null when nothing on it is selectable. The cells are 1-based — the space SGR mouse reports, zones and sugar-mouse's \SugarCraft\Mouse\Selection use — so frame line R is selectableLines()[R - 1]. |
static selectableLines(): array | The last frame's lines, unhighlighted — what a finished selection is read from. Static for scanner()'s reason: the release that copies arrives between frames and can only read the one on screen. |
static modeBadgeForms(\SugarCraft\Code\Permissions\PermissionMode $mode): array | The badge's forms, widest first. plan names its way out, because a mode that refuses every edit is the one a user most needs to leave. |
static thoughtKey(string $reasoning): string | The Chat::expanded() key of a settled thought: derived from the text alone, so the running placeholder a thought rides on and the finished row that replaces it (a new Message, new timestamp) resolve to the same open/closed state. |
static recallKey(Message $msg): string | The Chat::expanded() key of a structured memory-recall row (C-CTX-6.e): derived from the row's sentence and titles, so the same recall of the same notes keeps its open/closed state across repaints and the row rides the transcript's existing tool-row click affordance — same registry, same key space, no new key binding. |
static collapseToolOutput(string $output, int $maxLines, int $maxChars): array | Clip a tool's raw output to at most $maxLines lines AND $maxChars characters, reporting whether anything was dropped ( §1 E5). |
static styleDiffLine(string $line, Theme $theme, bool $isHeader): Style | Pick the Style for one unified-diff line from its marker column. The ---/+++ file headers are matched before the bare -/+ markers they start with, otherwise a diff's own header would render as a giant removal followed by a giant addition. |
Role enum
Conversation role for a Message. Mirrors the Anthropic / OpenAI / Ollama wire vocabulary so backend adapters can pass the value through without translation.
Cases: System · User · Assistant
PHP also provides cases(), from() and tryFrom().
Runtime final class
| Method | Summary |
|---|---|
__construct(private ProviderInterface $provider, private HookManager $hookManager, private ?EnvironmentBlock $environmentBlock = null, private bool $parallelToolCalls = true, private int $parallelToolDeadlineSeconds = self::PARALLEL_TOOL_DEADLINE_SECONDS, private ?int $maxOutputTokens = null, private ?int $maxConcurrentDelegations = null, private ?\SugarCraft\Code\Support\ToolCallIdAllocator $toolCallIds = null, private ?array $jsonSchema = null, private ?string $agentInstructions = null, private ?string $appendedSystemPrompt = null, private bool $redactToolOutput = false) | |
jsonSchemaFor(App $app): ?array | Which request the operator's --json-schema (AUT-4) rides, and which it does not — the TERMINAL/SELF-FINISHING-TURN ruling. |
markWriteSinceLastRender(bool $writeSinceLastRender): void | Record whether the step that just finished ran anything that could have written the working tree, so the NEXT prompt this Runtime assembles shows the git diff or withholds it. |
static stepRequestedAWrite(?array $toolCalls): bool | Whether one step of the agentic loop asked for a tool that could have written the working tree. |
run(App $app, ?callable $onEvent = null, ?callable $onPermissionRequest = null, ?callable $onToken = null, ?callable $onProgress = null, ?callable $onHeartbeat = null, ?callable $onRequest = null): \Generator | Run a completion and handle tool calls. |
static hookInput(array $arguments): string | The JSON text a hook reads as CRUSH_TOOL_INPUT (and its _FILE twin). |
assembledSystemPrompt(App $app): string | The system prompt $app would send, as the assembled string itself — the raw half the Backend\DumpsSystemPrompt capability hands to /context --raw (GAP-PRM-15). One fold behind the very method a turn builds with, so the dumped bytes ARE the sent bytes, and they sum to the promptSectionSizes() rows exactly — the identity the dump test pins. The transcript never sees this string; it only ever reaches a file the user named (or the exports shelf), which is WHY this arm exists beside the panel rather than inside it. |
promptSectionSizes(App $app): array | The system prompt $app would send, measured per layer — what /context shows (roadmap 5.6). Built from the very section list run() assembles, through the one fold (assembleSections()), so the bytes counted are the bytes sent: every row's bytes includes the "\n\n" separator its block carries, and the rows sum to the assembled prompt's length exactly. Empty layers fold away here as they do there. |
static planInstructionDocuments(\SugarCraft\Code\Context\InstructionFileLoader $loader): array | Which instruction documents one prompt build inlines and which it defers to a pointer line — C3's budget, as one definition. |
static planEnabledSkills(array $enabledSkills, \SugarCraft\Code\Context\CompactorConfig $budget): array | What each enabled skill contributes to one prompt build, in enabled order — its body, or, over budget, its heading and a pointer — and why a deferred one was deferred. |
skillDeferrals(): array | The enabled skills whose bodies the most recent prompt build deferred for budget, keyed by skill name, mapped to why. |
turnContext(App $app): Context\TurnContextBlock | The volatile per-step context (step 1.A-1): the git section of this Runtime's environment snapshot — so the write signal markWriteSinceLastRender() sets still decides whether the diffs render — plus the files this conversation's Edit/Write calls touched, and the files changed on disk since the turn's tools read them (step 3.I-2, from the Tools\ReadLedger those tools share). |
primeInstructionDiff(App $app): void | Fill the instruction-diff slot in the process that OUTLIVES the turn — the parent-side sibling of primeSessionPrompt(), called by EngineBackend right after that prime, before a turn's fork and before a summary's (C-CTX-1). |
withSessionPromptMemo(Context\SessionPromptMemo $memo): self | Share one Context\SessionPromptMemo with this Runtime, so its PerSession layers (static <env>, repo map, project memory, standing instruction slab) are read from — and filled into — a memo that outlives the turn. Without one the Runtime keeps a private memo, which is the pre-1.A-1 per-Runtime memoisation exactly. |
primeSessionPrompt(App $app): void | Fill the session memo's PerSession layers for $app without sending anything — the parent-side prime of step 1.A-2. EngineBackend calls it before forking a turn's child, so the static <env>, repo map, project memory and standing instruction slab are read ONCE, in the process that outlives the turn, and every child inherits them warm. Builds exactly the section list run() would, so the slots it fills are the ones the child reads. |
withTurnContextPersisted(): self | A copy whose run() does not append the <turn-context> row, because the caller persists it into the history before each step (step 1.A-2). A clone, like withSessionPromptMemo(). |
withTurnInbox(\SugarCraft\Code\Backend\TurnInbox $inbox): self | A copy that probes $inbox before each sequential tool call (roadmap 1.C-3): once a mid-turn message is waiting, the step's unstarted calls are skipped (executeToolCalls()). The inbox itself is drained by the step loop that owns it (EngineBackend::runTurn). A clone, like withSessionPromptMemo(). |
withChunkUsageObserver(\Closure $observer): self | A copy that hands each streamed chunk's folded usage to $observer the moment runStreaming() folds it, so a delegated run's row can count a long response while it streams. The observer sees every attempt's chunks, including ones a retry later drops; the step's AssistantMessage usage stays the billed figure. A clone, like withTurnInbox(). |
memoryRecall(App $app): Context\MemoryRecallBlock | The memory notes recalled for $app's latest user message (roadmap 5.3-2), carried by the <turn-context> row (turnContext()). |
primeMemoryRecall(App $app, string $query, ?\Closure $embedder): Context\MemoryRecallBlock | Rank $app's memory notes against $query and keep the result as this session's recall — the priming half of roadmap 5.3-2, run by EngineBackend in the process that assembles the request (the forked turn child, or the blocking fallback with no child) since ISS-072, so the note reads and the one embedding request ($embedder, null for keyword-only) happen once per turn off the parent's event loop. |
primeSymbolMap(App $app): Context\SymbolMapBlock | Capture the symbol-level repo map for $app's session once, into the session memo the turn's prompt reads (roadmap 5.5-5). EngineBackend calls it in the parent before forking a turn; after the first turn of a session — and until a refresh point forgets the session's layers — it returns the held capture without touching the checkout, so the bytes the prompt carries never move inside a session. A capture that came back empty is held too: the session stays without the map rather than gaining it mid-session and moving message 0. |
shouldPromptIdleCompaction(App $app, int $tokenCount): bool | Determine whether to prompt the user about idle-session compaction. |
Session final class
Session persistence for candy-code.
| Method | Summary |
|---|---|
__construct(public readonly string $cwd = '', public readonly array $selected = [], public readonly string $filter = '', public readonly string $sortColumn = 'name', public readonly string $sortDir = 'asc', public readonly string $activePane = 'files') | |
static load(): self | Load session state from the JSON file. |
save(): void | Save session state to the JSON file. |
withCwd(string $cwd): self | |
withSelected(array $selected): self | |
withFilter(string $filter): self | |
withSort(string $column, string $direction): self | |
withActivePane(string $pane): self |
StreamingDirectoryLister final class
Lazily enumerates directory entries using a Generator so that even directories with thousands of files do not cause memory exhaustion.
| Method | Summary |
|---|---|
list(string $path, bool $includeHidden = false) | Yield directory entries lazily. Empty directories produce an empty Generator (caller handles that). |
listFiles(string $path, bool $includeHidden = false): Generator | List only regular files (not directories or symlinks). |
count(string $path, bool $includeHidden = false): int | Count entries WITHOUT loading them into memory. Uses a single-pass scan rather than building an array. |
Theme final class
A named colour theme for Renderer's chrome (borders, user/assistant/ system labels), the whole src/Tui/ shell (menu bar and its dropdown, pane boxes, sidebars, status colours) and SugarMarkdown's markdown rendering, resolved from the two theme classes that already exist elsewhere in the monorepo rather than inventing a third colour system:
| Method | Summary |
|---|---|
__construct(public readonly string $name, public readonly MarkdownTheme $markdown, public readonly Color $border, public readonly Color $userLabel, public readonly Color $assistantLabel, public readonly Color $systemLabel, public readonly Color $shellForeground, public readonly Color $shellMuted, public readonly Color $shellPrimary, public readonly Color $shellSuccess, public readonly Color $shellWarning, public readonly Color $shellError, public readonly Color $shellInfo, public readonly Color $shellSeparator) | |
static contrast(Color $a, Color $b): float | Contrast ratio between two colours, WCAG 2.1 §1.4.3: the lighter relative luminance plus 0.05 over the darker plus 0.05, so 1.0 is "identical" and 21.0 is black on white. |
static byName(string $name): self | Resolve a theme name — a built-in (builtInNames(), matched case-insensitively), a discovered file under ~/.candy-code/themes/ (ThemeFile), or neither. |
static adaptive(): self | The dark/light preset the attached terminal actually calls for, kept under the name adaptive so the choice re-resolves on every read (and on every launch) instead of being frozen at pick time. |
static legibleOn(Color $colour, Color $background): Color | $colour if it already reaches CONTRAST_MIN on $background, else the same colour nudged along its own HSL lightness axis, away from the background, until it does - the background-only half of project()'s nudge, for a colour a theme did not declare. |
static dark(): self | The house default palette: the shipped dark theme. Named for the palette rather than default() because ::new() is the factory root and ::default() is a banned name; mirrors the descriptive-name spelling of sugar-style's Theme::ansi(). |
static names(): array | Everything byName() answers: the six built-ins in their fixed order, then the custom theme files discovered under ~/.candy-code/themes/, sorted. A custom file whose stem collides with a built-in name keeps the built-in — the person's palette file never shadows a name the docs and validators promise. |
static builtInNames(): array | The machine-independent half: exactly the shipped palettes, in the fixed order, no directory scan behind them. Documentation, the settings validator's advertised list, and any test that must mean "everywhere this runs" quote THIS, so a machine's private theme files never leak into a page another machine reads. |
static isBuiltInName(string $name): bool | Whether a name is one of the shipped palettes, matched case-insensitively like byName(). |
static canonicalBaseName(string $name): ?string | The canonical spelling of a base theme name, or null when it is not one. |
static suggest(string $name): ?string | The advertised name closest to a misspelling, or null when nothing is close. Folded (case, - and _ dropped) equality wins outright, else one edit for short names and two for longer ones — the \SugarCraft\Code\Config\LayeredSettings::suggestKey() budget, so both places that guess a name guess with the same tolerance. |
static resetForTesting(): void | Forget the discovered files, the parses, and which names have warned — tests move HOME between cases, and each home is its own theme world. |
ToolCall final class
Represents a request to call a tool/function.
| Method | Summary |
|---|---|
__construct(public readonly string $name, public readonly array $arguments = [], public readonly ?string $id = null) | |
static fromArray(array $data): self | Create from an array (e.g., from JSON parse of backend response). |
toEngineCall(): EngineToolCall | Adapt this Chat-side call to the canonical engine-side EngineToolCall the live Runtime/EngineBackend/provider pipeline speaks (§1 E1). |
static fromEngineCall(EngineToolCall $call): self | Adapt a canonical engine-side EngineToolCall (what every ProviderInterface puts on CompleteResponse::$toolCalls) into the Chat/Renderer-side shape. Inverse of toEngineCall(). |
toArray(): array | Convert to array for serialization. |
ToolResult final class
Represents the result of a tool/function call.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(public readonly string $name, public readonly string $result, public readonly ?string $error = null, public readonly ?string $id = null, public readonly ?string $imageBytes = null, public readonly ?string $imagePath = null, public readonly ?string $imageProtocol = null, public readonly ?string $diff = null, public readonly ?int $durationMs = null, public readonly ?string $description = null, public readonly array $arguments = [], public readonly ?DenialKind $denial = null, public readonly ?int $exitCode = null) | |
static ok(string $name, string $result, ?string $id = null): self | Create a successful result. |
static error(string $name, string $error, ?string $id = null): self | Create an error result. |
static denied(string $name, DenialKind $kind, string $detail, ?string $id = null): self | Create the result of a call that was STOPPED before it ran: an error whose text is $kind's rendered reason and which carries $kind structurally, so a reader never has to classify the text. |
static okWithImage(string $name, string $result, string $imageBytes, ?string $id = null): self | Create a successful result that also carries raw image bytes (e.g. a tool that captured a screenshot). Probes the terminal's image capability once via Mosaic::auto() -- never throws -- so a later renderer (see E3, not part of this step) knows which protocol to paint with without re-probing the TTY per tool call. |
withImage(string $imageBytes, ?string $imagePath = null): self | Fluent attach of image bytes onto an existing result, e.g. a tool that already produced text output also captured a screenshot. Returns a new instance -- $this is left untouched, per this repo's immutable+with*() convention (see AGENTS.md). |
withDescription(?string $description): self | Fluent attach of the human-readable one-liner describing the CALL this result answers -- see the constructor's $description docblock for why a display-only field is carried here rather than derived at render time. |
withArguments(array $arguments): self | Fluent attach of the raw arguments of the CALL this result answers -- see the constructor's $arguments docblock. Returns a new instance. |
hasDescription(): bool | True when this result knows the call it answers, i.e. it can tell the user WHAT ran and not merely which tool ran. |
hasImage(): bool | True when this result carries image bytes for in-TUI rendering. |
hasDiff(): bool | True when this result carries a unified diff for a renderer to show (§1 E3) instead of only a "File updated: …" one-liner. |
diffTexts(): array | This result's diff as the before/after text of each changed region — diffTextsOf() over $diff. |
static diffTextsOf(string $diff): array | A unified diff as the before/after text of each hunk: what an editor that renders a change from its two sides (the Agent Client Protocol's {type: "diff", path, oldText, newText}, roadmap 5.9-2) needs, where $diff is the patch a terminal renders. Context and removed lines make oldText, context and added lines newText; a hunk that starts at -0,0 created the file, so its oldText is null. The path is the +++ b/ header's, without the a//b/ prefix. |
toEngineResult(): EngineToolResult | Adapt this Chat-side result to the canonical engine-side EngineToolResult the Tools\Tool interface, Runtime and \SugarCraft\Code\Events\ToolFinished speak ( §1 E1). |
static fromEngineResult(EngineToolResult $result, string $name): self | Adapt a canonical engine-side EngineToolResult into the Chat/Renderer-side shape. Inverse of toEngineResult(). |
static setRenderMode(string $mode): void | Set the render mode probeMosaic() derives from (W2.2). Called once per launch by \SugarCraft\Code\Cli\Bootstrap::applyMediaRenderMode() with the resolved ui.imageRenderMode value; empty or whitespace-only input normalises to 'auto', asking the terminal. The word is stored normalised (trimmed, lower-cased) because mosaic's own vocabulary comparator is, and the memo key must not fork on spelling noise. |
static renderMode(): string | The currently configured render-mode word (see setRenderMode()). |
static resetRenderMode(): void | Discard every cached probe in the per-mode memo (W5.7, crush_media §8.2) so the next mosaic() re-derives instead of answering from a ??= hit. This resets the CACHES, not the word — the word only changes through setRenderMode() (and the boot-time precedence in \SugarCraft\Code\Cli\Bootstrap::applyMediaRenderMode(), where CANDY_CODE_MEDIA_RENDER_MODE reasserts itself at the next launch). The /rendermode command calls set-then-reset together; a bare reset is the seam for any future caller that re-detects the terminal without changing the requested mode. |
static mosaic(): Mosaic | Public accessor for the same probe-once Mosaic instance probeMosaic() caches -- the shared instance \SugarCraft\Code\Cli\Bootstrap::chat() threads into \SugarCraft\Code\Chat's mosaic: constructor parameter (W1.G2/E2), so a future renderer (E3) reads the SAME detected protocol this class's own image-bearing results were built from, rather than re-probing the TTY independently. |
toWire(): array | Convert to array for serialization (wire format). |
isError(): bool |
Usage final readonly class
What one provider call — or a whole turn's worth of them summed — actually cost, in PROVIDER-COUNTED tokens and dollars (Phase 5 item 7). Since prompt_plan.md P4.S1 (backlog E17) it also carries the provider's own token BUCKETS — input/output, the two cache sides, and (since qwen.md §Q6) the completion-side reasoning side — null until a provider reports each one, and never defaulted to a number a provider did not say.
| Method | Summary |
|---|---|
static new(int $totalTokens = 0, float $costUsd = 0.0, ?int $inputTokens = null, ?int $outputTokens = null, ?int $cacheReadTokens = null, ?int $cacheCreationTokens = null, ?int $reasoningTokens = null, ?string $unpricedModel = null, int $delegatedTokens = 0, int $webSearchRequests = 0): self | |
static reported(int $totalTokens, float $costUsd, ?int $inputTokens = null, ?int $outputTokens = null, ?int $cacheReadTokens = null, ?int $cacheCreationTokens = null, ?int $reasoningTokens = null, ?string $unpricedModel = null, int $delegatedTokens = 0, int $webSearchRequests = 0): ?self | The usage a provider call actually reported, or null when it reported nothing measurable. |
plus(self $other): self | This usage plus $other's — the operation an agentic TURN needs, because one turn is N provider calls, not one. |
ownTokens(): int | $totalTokens without the share delegated runs billed into it — the tokens THIS conversation's own provider calls counted. What a reader that treats the total as a conversation size must use. |
promptTokens(): ?int | The prompt-side total, the identity the cache-bucket split exists to make computable: promptTokens = cacheRead + cacheCreation + input (prompt_plan.md P4.S1, backlog E17; prompt_expand.md §9.14). |
withInputTokens(?int $tokens): self | The usage with a reported/unreported input bucket set. Passing null clears it back to unreported; the other buckets ride along untouched — that is what the paired bool $xSet sentinels on mutate() are for (repo convention; canonical sugar-style/src/Style.php). |
withOutputTokens(?int $tokens): self | As withInputTokens(), for the completion side. |
withCacheReadTokens(?int $tokens): self | As withInputTokens(), for the cache-read bucket. |
withCacheCreationTokens(?int $tokens): self | As withInputTokens(), for the cache-creation bucket. |
withReasoningTokens(?int $tokens): self | As withInputTokens(), for the completion-side reasoning bucket. |
static sum(array $usages): ?self | Sum of a list of per-call usages, or null when the list is empty or holds only nulls — preserving the "nothing reported" answer rather than turning it into a zero. |
toArray(): array | Plain-array form for the Backend\EngineBackend::completeAsync() fork boundary, whose parent unserializes with allowed_classes => false and so cannot receive the object itself — same rule Backend\EngineBackend::encodeEvent() follows for tool events. |
static fromArray(mixed $raw): ?self | Rebuild from toArray(), tolerating anything that is not the shape it wrote: the payload has crossed a socket, and a corrupt frame must cost the turn its accounting, not the turn itself. |
SugarCraft\Code\App
App final class
Main application state - immutable with*() builders. Mirrors the canonical sugar-style/src/Style.php pattern.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
static new(ProviderInterface $provider, string $model): self | |
withProvider(ProviderInterface $v): self | |
withModel(string $v): self | |
withMessages(array $v): self | |
withTools(array $v): self | |
withPane(Pane $v): self | |
contextPaneToggle(): self | P-CTX.e: flip the Context box between summary and category rows. Collapsing drops the drill too — the sub-rows live inside the expanded body, and a drill that survives its own container would resurrect on the next expand pointing at a row that was never shown. |
contextPaneDrill(?ContextCategory $v): self | P-CTX.e: show one category's sub-rows (null returns to the flat list); drilling implies expanding, the same containment the collapse rule enforces from the other side. |
withError(?string $v): self | |
withStatus(?string $v): self | |
withSessionId(?string $v): self | |
withReasoningEffort(string|float|null $v): self | |
withContextFiles(array $v): self | |
withEnabledSkills(array $v): self | |
withAvailableSkills(SkillRegistry $registry): self | |
withActiveHooks(array $v): self | |
withSelectedAgentIndex(int $v): self | |
toggleAgentExpanded(string $runId): self | Expand a delegated run's row, or collapse it if it was expanded. |
isAgentExpanded(string $runId): bool | |
agentStripItems(): array | The runs the live agents strip shows (P-B3): the hosted chat's live registry, minus what the user dismissed. Empty with no chat. |
withAgentStripFocus(?string $id): self | Give the strip the keyboard on run $id, or with null hand it back to the input. |
dismissFromAgentStrip(string $id): self | Take a run off the strip (x on a finished run); focus moves to a neighbour. |
openAgent(string $id): self | Open run $id (P-B3's strip Enter): the read-only Agent View (P-C2). |
openAgentView(string $id, ?string $childSessionId = null, ?string $name = null): self | Open the read-only Agent View on run $id (roadmap P-C2, Appendix P §5.1): the chat pane's transcript area shows that run's own transcript, with \SugarCraft\Code\Tui\AgentViewHeader pinned above it, until closeAgentView(). The input box becomes that run's composer (P-D2): Enter sends the draft to it (agentComposerTargets()). |
refreshAgentView(): self | Read what the open view's log gained since the last read — one window of \SugarCraft\Code\Agents\Live\AgentTranscriptTail::MAX_BYTES_PER_READ at most — and re-project the rows. The shell's tail tick (subscriptions()) calls it through openAgentView(). |
closeAgentView(): self | Leave the Agent View: the parent transcript is back, and the dashboard is no longer attached. Pane focus is left where it is. P-AGENT.b: the leaving is a window swap — the run's view keeps whatever draft and scroll it holds, and the tab's main window comes back exactly as it was before the view opened. |
agentViewSiblings(): array | The runs of the open run's Task batch, in spawn order, itself included — what Alt+N / Alt+P and the header's ‹ i of N › walk. A single run, or a worker that is not a run, has none. |
agentViewSibling(int $step): ?string | The sibling $step places away from the open run (Alt+N is +1, Alt+P is -1), or null at either end or with no siblings. |
agentComposerTargets(): array | The runs the Agent View's composer sends to (roadmap P-D2): the run on screen — or, while Ctrl+G's broadcast is on (P-D3), every running run of its batch (every running run, for one not in a batch), and the one on screen when none is running any more. Empty while no view is open — the box is then the main chat's. |
runningAgentIds(): array | Every delegated run of this session that has not finished, oldest first — what stop-all and a broadcast address. |
withAgentViewLeader(bool $down): self | The same shell with the Agent View's Ctrl+X leader down or up ($agentViewLeader). |
withAgentsStopArmedAt(?float $at): self | The same shell with the Agents dashboard stop-all arming stamp set or cleared ($agentsStopArmedAt, rv-a11y M3a two-press s). |
isAgentPaused(string $id): bool | Whether the user paused run $id and has not let it go ($agentPaused). |
toggleAgentBroadcast(): self | Ctrl+G (roadmap P-D3, Appendix P §5.5): the composer's broadcast — send to every running agent of the batch at once. Turned on, it opens the Agent View on the newest running run when none is open, so the box that broadcasts is the composer that says it does. Turned off by the second press. With nothing running there is no one to address, and the status line says so. |
deliverAgentControl(\SugarCraft\Code\App\AgentControlMsg $control): array | Deliver a control to the hosted chat, which owns the runs' mailboxes (roadmap P-D3) — after the shell's own half: a second cancel of the same runs within AGENT_HARD_CANCEL_SECONDS becomes the hard stop, pause/resume keep $agentPaused current, opening a run as a session leaves the view, and the status line says what was asked. |
recordAgentMessage(\SugarCraft\Code\App\AgentMessageSentMsg $sent): self | Keep what became of a composer message ($agentMessages): a later state of the same message — a follow-up that replied or failed — replaces the earlier one, so each message keeps one row. |
agentViewFrame(): ?array | What one frame of the open view draws, for Renderer::setAgentView() — or null while no view is open. Read in view(): it computes from state and reads nothing from disk. |
paneScroll(string $id): int | How far the surface $id is scrolled down; 0 is the top. |
withPaneScroll(string $id, int $delta, ?int $max = null): self | Scroll the surface $id by $delta (positive = down), never above the top. The bottom bound is the renderer's: it knows the content height and clamps an offset that outgrew it. |
withAgentSplitCols(?int $cols): self | Set (or with null, release) the live-agent column's dragged width. |
withAgentViewMode(AgentViewMode $v): self | |
withLastActivity(DateTimeImmutable $lastActivityAt): self | |
withSkillPickerOptions(array $v): self | |
withSkillPickerIndex(int $v): self | Move the skill picker's cursor. Clamped to the option list rather than trusting the caller, so an index can never point past the last row and make Enter select nothing. |
withInstructionLoader(?InstructionFileLoader $v): self | Attach the session's shared InstructionFileLoader so \SugarCraft\Code\Runtime::buildSystemPrompt() can fold the repo-root CLAUDE.md/AGENTS.md and the config-driven forced-instruction globs into every system prompt. |
withChat(?Chat $v): self | Host a Chat inside the shell (§5 E7, merge branch). |
withRoot(?string $v): self | Point this App at a project root — see $root. |
withMemoryStore(?MemoryStore $v): self | |
withRulesState(?RulesState $v): self | The session's rulebook toggle set, forwarded to the rules splice. |
withSettingsSources(?\Closure $v): self | |
withSettingsEditor(?SettingsEditor $v): self | Replace the open settings view's state (null closes it). |
withMediaForm(?MediaForm $v): self | Replace the open media form's state (null closes it). |
withVideoPlayer(?VideoPlayerScreen $v): self | Replace the open player's state (null closes it — WITHOUT stopping; prefer closeVideoPlayer()). |
withSettingsWriter(?SettingsWriter $v): self | |
withTrustDialog(?TrustDialog $v): self | Replace the open launch trust dialog's state (null closes it). |
withDiffReview(?DiffReview $v): self | Replace the open diff review's state (null closes it). |
withFirstRunWizard(?FirstRunWizard $v): self | Replace the open first-run wizard's state (null closes it; C-TUI-5.e). |
previewSettings(): self | Build the open settings view's save preview from what its tier's file holds now (N-P2). One small read, on an explicit request — the same shape as openSettings() resolving the files when the view opens. |
confirmSettingsSave(): array | Confirm the open preview: the write runs as a Cmd (it is I/O) and answers with a SettingsSavedMsg. Nothing happens without a preview that SettingsSavePreview::canSave(). |
openSettings(string $query = ''): self | Open the settings view, its search pre-filled with $query. |
closeSettings(): self | |
openMediaForm(?MediaRequest $request = null): self | Open the media generation form (crush-media W3.1), optionally seeded with a draft. Pure state: the sections were built at open, the form dials nothing — the Generate action comes back through applyMediaFormAction(). |
closeMediaForm(): self | |
openVideoPlayer(string $path, ?\Closure $playerFactory = null): array | Raise the full-screen video player (crush-media W5.4) on a resolved local path. Pure state plus one promise Cmd: the probe-and-spawn runs inside \SugarCraft\Core\Cmd::promise() AFTER the "Preparing…" placeholder is the painted frame, so a slow ffmpeg degrades to a visible wait rather than a frozen UI. The build itself is the synchronous, one-time cost the plan accepted; there is no wall-clock deadline anywhere on it (E646 — the wait is bounded by the spawn, not by a timer this shell invented). |
closeVideoPlayer(): self | Close the player and stop its clip. The only path that drops the slot. |
openDiffReview(DiffReview $review): self | Raise the checkpoint-diff review (C-TUI-2.e) on an already-loaded model — the shell-slot twin of openMediaForm(): the command dials DiffReviewSource::load() and hands the finished review over as an OpenDiffReviewMsg; this only closes the menu and takes the slot. Pure state: the patches are already in the model. |
closeDiffReview(): self | Drop the diff review if one stands (C-TUI-2.e); idempotent. |
openFirstRunWizard(): self | Raise the first-run wizard (C-TUI-5.e) — the shell-slot twin of openDiffReview(): the launch command asks FirstRunWizard::shouldOffer() and answers an OpenFirstRunWizardMsg; this only closes the menu and takes the slot with a fresh model, seeded with the current column count so the provider pill row windows inside the band the renderer clips at (NN-01 — null cols on a headless build keeps the legacy unwindowed row). Already open → unchanged, so a doubled msg never re-seeds the form under the user's keys. |
closeFirstRunWizard(): self | Drop the first-run wizard if one stands (C-TUI-5.e); idempotent. |
firstRunWizardOfferCmd(?bool $isInteractiveTty = null, ?string $stampPath = null): ?\Closure | The launch's wizard offer (C-TUI-5.e), as a Cmd like every other init() member — the opener decides, the shell owns the slot. All three inputs are caller state, never model state (FirstRunWizard::shouldOffer()): no provider was SELECTED for this launch (env tier, --provider, or a persisted provider key — the same reads \SugarCraft\Code\Cli\Bootstrap makes to build the backend), no provider carries a usable API key in the user config, and the terminal is a live interactive tty. Both seams are injectable for pins: the tty probe is guarded by is_resource on each stream because tests/bootstrap.php frees the PHP-level \STDIN resource during its fd-0 repair — an unguarded stream_isatty(STDIN) THROWS on that invalid resource under strict_types rather than answering false — and with the guard the freed STDIN plus a piped stdout answer false, so the default never fires in a test run; the stamp path reads the real cache corner by default. |
openMessagePicker(array $promptsNewestFirst): self | Open the message picker over these prompts, newest first (C-TUI-3.d). Public for the shell's own dial below and for the wiring observation in the key-binding drift guard; on the review's open law — close the menu bar and take the slot, the rows being plain strings already read from the store by the caller. |
closeMessagePicker(): self | Drop the message picker if one stands (C-TUI-3.d); idempotent. |
dock(): DockLayout | The docked-pane layout in force, with the default folded in. |
static defaultDock(): DockLayout | The launch-default dock: Files left, right side empty. |
static isUntouchedDefaultDock(DockLayout $dock): bool | Whether a dock is byte-for-byte the untouched defaultDock() — same slots AND same design shares. The renderer's width rule keys on this (see \SugarCraft\Code\Tui\Renderer::sideWidth()): while nothing has ever been docked or resized, the frame keeps the exact legacy quarter-measure it shipped with for a decade of snapshot pins. |
static seedSharesFromFrame(DockLayout $dock, int $bandCols, ?Side $docksInto = null): DockLayout | Snapshot the frame the eye last saw into the dock's column shares, exactly once — at the moment the untouched default first acquires a side's worth of slots. |
withDock(?DockLayout $v): self | |
withOnLayoutChange(?\Closure $v): self | |
withPaneAutoShow(PaneAutoShow $v): self | Replace the auto-show memory. The launch path uses this to re-seed the panes the user toggled by hand in a previous session (ISS-049), so a pane that was closed stays closed across restarts instead of riding back in on the first content transition. |
withTabFactory(?\Closure $v): self | P-TABS.d: install the tab strip's session factory (field only — the routing lands in P-TABS.e). |
withCompactorConfig(?CompactorConfig $v): self | |
withContextLedger(?\SugarCraft\Code\Context\Pruning\ContextLedger $v): self | See $contextLedger. |
setPaneSide(Pane $pane, Side $side, ?int $index = null): self | Dock pane on side — moving it there when it already sits in a slot. |
togglePaneDocking(Pane $pane): self | Dock pane on its home side, or undock it when it sits in any slot. |
layoutReset(): self | Return the dock to the launch default (defaultDock()). |
isDocked(Pane $pane): bool | Whether pane currently occupies a dock slot on either side. |
autoEnablePanes(): self | Dock every roster pane whose predicate just turned true, once per pane per process, on its default side (Pane::dockSide()). |
paneCycleOrder(): array | The panes Tab can focus, in visual order: Chat, then the left column's slots top-to-bottom, then the right column's. |
cyclePaneFocus(int $direction): self | Move focus one step along paneCycleOrder() — +1 forward, -1 backward, wrapping at both ends. The spelling is direction, not delta: the caller says which way the user reached, the sign carries it. |
layoutBlob(): array | The blob the layout setting stores: the dock manifest plus — only when non-empty, so a never-toggled session's blob stays byte-identical to the pure manifest — the panes the user touched by hand (ISS-049). \SugarCraft\Code\Cli\Bootstrap::dockFromUserConfig() reads the manifest through the key paths \SugarCraft\Constraints\Dock\DockLayout::fromArray() knows (unknown keys are ignored), and the sibling reader folds userToggled back onto the launch model. |
theme(): Theme | The colour theme the SHELL's chrome paints with. |
applySkillsToSystemPrompt(string $baseSystemPrompt): string | Apply enabled skills to the base system prompt. |
findSkillsForTask(string $task): array | Find skills that match a task description. |
userInvocableSkills(): array | Filter to the registry's user-invocable skills. |
dispatchSkill(Skill $skill, AgentWorkerPool $pool, string $task, int $timeoutSeconds = 0): ?AgentResult | Dispatch a matched skill according to its declared execution context. |
withMessage(Message $msg): self | Add a message to the conversation. |
init(): ?\Closure | The startup Cmd: ask the terminal what colour it paints on and what keyboard protocol it speaks, batched with whatever the hosted Chat wants to run. |
update(CoreMsg $msg): array | Update the state from a message. Returns [newApp, command] where command is a Cmd to execute or null. |
frameMouseMode(): MouseMode | The mouse-tracking mode this shell's frames declare to the runtime. |
static chromeClickTracker(): ZoneClickTracker | |
static paneDragController(): PaneDragController | |
static resetPaneDragController(): void | Drop any gesture in flight — the suite's isolation seam (a test that builds frames without driving a full gesture must not inherit one), and the shape Escape takes below. |
adoptPaintedDockFrame(?array $frame): void | Hand the just-painted dock band back to the model (TUIARCH-02 phase 2). The paint step is the ONLY caller: \SugarCraft\Code\Tui\Renderer adopts the frame it measured every frame, and its full-band dashboard/overlay tails adopt null. Writing through the painted model — instead of the retired process static — means the measurement belongs to the instance it was painted from and travels with its rebuilds. |
paintedDockFrame(): ?array | The band as the last frame painted onto this model measured it, or null when no measured frame is standing. |
editSettingsFile(): array | e in the settings view (N-P5, "open the file in $EDITOR"): the highlighted file on the Files tab, else the file the chosen tier saves to, opened in the user's editor through a SettingsFileEditor Cmd (the terminal is handed over and given back). What the file holds now is read first — one small read on an explicit request, like previewSettings() — so the answer can say what the edit changed. |
runSettingsProfile(): array | Enter on the profile prompt: export what this launch's files and session set (SettingsProfile::values()) to the path typed, or read the profile there to stage it. Both are Cmds — file I/O — answered with a SettingsProfileMsg. |
grantProjectTrust(): array | The confirmed trust action (N-P2's dormant SettingsWriter::grantTrust(), wired): add this launch's project root to the trust list the view is asking about, in the user's config.json. The write is a Cmd, answered with a SettingsSavedMsg like a save; it applies from the next launch. |
consumeShellCmd(object $cmd): array | Act on a command object the shell's keyboard layer produced. |
dispatchKey(KeyMsg $msg): ?array | Apply a keypress through KeyboardHandler, reporting the shell's own \SugarCraft\Code\Tui\Commands\KeyCmd. |
dispatch(Msg $msg): array | The engine-facing half of update(): answer a shell/engine message and report the Cmd it asks for. |
applyDockCommand(DockPaneMsg $msg): array | Run a /pane dock command: parse, move, acknowledge. |
focusedToolRowKeys(): array | The row-unit keys the SETTLED cursor stands on (W7-B), or the empty list while none is settled — the render seam's read of focusedUnitIndex(), in the identity the renderer keys rows by. The whole unit, not just its lead key: the highlight marks exactly the rows Ctrl+O will answer, so what the user sees and what the chord does never disagree. |
view(): string|View | Render the whole shell: menu bar, sidebars, chat pane, input, status. |
subscriptions(): ?Subscriptions | Subscriptions the Program should pump, delegated to the hosted chat. |
windowList(): ?WindowList | The deck projected as the shell's window list (P-TABS.g) — what the horizontal strip and the vertical Sessions pane both render, and what the OSC 2 title counts over. Null means no deck: every surface that consumes this treats null as "the strip is not armed" and paints nothing, the same shape the deck routing keeps for a single chat. |
SugarCraft\Code\Backend
EngineBackend final class
Bridges the chat-shell Backend seam to the full agent engine — a ProviderInterface driven by the Runtime, with tools, skills and hooks.
| Method | Summary |
|---|---|
__construct(private readonly ProviderInterface $provider, private readonly string $model, private readonly array $tools = [], private readonly array $skills = [], private readonly ?HookManager $hookManager = null, private readonly int $maxSteps = 1000, private readonly bool $hooksDisabled = false, private readonly ?SkillRegistry $skillRegistry = null, private readonly ?InstructionFileLoader $instructionLoader = null, private readonly ?string $root = null, private readonly ?PermissionGate $permissionGate = null, private readonly ?\Closure $permissionApprover = null, private readonly ?\Closure $clientCallSink = null, private readonly ?\Closure $clientCaller = null, private readonly ?MemoryStore $memoryStore = null, private readonly ?RulesState $rulesState = null, private readonly ?float $spendCapUsd = null, private readonly float $sessionSpendAtStartUsd = 0.0, private readonly ?\Closure $turnSpendProbe = null, private readonly ?SiblingSpendLedger $siblingSpend = null, private readonly ?CompactorConfig $compactorConfig = null, private readonly CacheHealthWatch $cacheHealth = new CacheHealthWatch(), private readonly ?\Closure $stepUsageObserver = null, private readonly ?int $maxConcurrentDelegations = null, private readonly ?string $sessionId = null, private readonly ?string $summaryModel = null, private readonly ?\SugarCraft\Code\Context\Pruning\ContextLedger $contextLedger = null, private readonly ?\SugarCraft\Code\Hooks\BuiltIn\SubAgentGrantHook $subAgentGrant = null, private readonly ?TurnInbox $turnInbox = null, private readonly ?int $wrapUpAtPercent = null, private readonly SessionPromptMemo $sessionPromptMemo = new SessionPromptMemo(), private readonly string|float|null $reasoningEffort = null, private readonly ?array $jsonSchema = null, private readonly ?string $agentInstructions = null, private readonly ?string $appendedSystemPrompt = null, private readonly ?string $serviceTier = null, private readonly ?\Closure $chunkUsageObserver = null) | |
static new(ProviderInterface $provider, string $model): self | |
contextWindow(): int | The real context window of the model this backend completes against — the one number \SugarCraft\Code\Chat's context tiers are percentages of (Phase 5 item 4). |
sessionPromptMemo(): SessionPromptMemo | The session's prompt memo (step 1.A-2) — shared by every clone of this backend, primed before each turn's fork. Exposed so an owner can drop a session's layers explicitly (SessionPromptMemo::forget()) on top of the refresh points the backend detects itself. |
refreshPromptLayers(): void | S-X03: re-freeze this session's prompt layers now — the owner's side of the refresh points completeAsync() detects itself; see RefreshesPromptLayers for why both exist. |
withSessionPromptMemo(SessionPromptMemo $memo): self | Run the clone against a memo of its own (ISS-021). Every ordinary clone shares the owner's single memo; a background turn whose history is fabricated (a \SugarCraft\Code\Memory\DreamPass pass over journal entries) must not record that history as the session's baseline, nor memoise its layers under the session — one observeTurn of a mismatched history would be read as a rewrite and re-walk the session's whole prompt. Hand such a clone a fresh memo instead. |
withTools(array $tools): self | |
servedModel(): ?string | The model this backend's requests actually go to, when its provider talks to one other than $model and has learned which: the SGLang server's served model on a default-id launch. Null otherwise, and for any provider that cannot say. |
model(): string | The model id this backend was BUILT with — the configured one, which servedModel() overrides when the provider has learned it talks to another. Read by Renderer's status-bar model segment as the fallback, the same order Tui\Renderer::modelLabel() applies. |
withModel(string $model): self | A copy that sends every request to $model (roadmap N-P3b; roadmap 4.1-1 reuses it for a sub-agent's model). |
withServiceTier(?string $word): self | The same engine on the service tier named by $word — the configuration word ('default', 'fast') or null for unset; see $serviceTier. The provider leg is overlaid only when the pair shapes the tier: a shaper gets its own wire value resolved against the CURRENT model (or null cleared for the default word), and a non-shaper is left untouched so its wire bytes never change. |
serviceTier(): ?string | |
withHostPermissionMode(?PermissionMode $mode): self | The same engine with its provider bound to the host gate's current mode (C-PRV-4.a). A provider that carries no permission dial of its own rides the copy EXACTLY as it is — the object is shared, never touched — so this seam can stand at every turn entry without ever disturbing an HTTP provider's bytes. |
withReasoningEffort(string|float|null $effort): self | The same engine, asking every request for $effort (roadmap 4.1-1) — see $reasoningEffort. Null asks nothing. |
reasoningEffort(): string|float|null | |
withJsonSchema(?array $schema): self | |
jsonSchema(): ?array | The JSON Answer Contract this backend's turns ask for, if any. |
withAgentInstructions(?string $instructions): self | |
agentInstructions(): ?string | The active primary agent's instruction body, if one is applied. |
withAppendedSystemPrompt(?string $rules): self | |
appendedSystemPrompt(): ?string | The operator's --append-system-prompt rules text, if this launch gave it. |
honoursReasoningEffort(): bool | Whether a request's \SugarCraft\Code\Providers\CompleteRequest::$reasoningEffort reaches this backend's provider at all. Only SGLang reads it today (bare, or as a fallback chain's primary, which every request goes to first); every other provider drops the field, so Task leaves a preset's effort off there and says so rather than run it as if honoured. |
servesOneModel(): bool | Whether this backend's provider talks to a server that runs ONE model whatever a request names (SGLang, bare or as a fallback chain's primary), so a different model id can never be honoured on it — the request would reach the same model under a wrong label, or be refused by the server. Answered from the provider's type alone: no I/O. Task runs a delegation that asks for another model on the session's own model there (see servedModel() for the name it serves). Every other provider names its model per request and may accept an id no table here knows. |
sessionId(): ?string | The session this backend's turns run as, or null — see $sessionId. |
provider(): ProviderInterface | The provider this engine completes against — read by \SugarCraft\Code\Agents\EngineExecutor to refuse a workflow stage on the offline echo fallback rather than pass echoed text off as work. |
tools(): array | The tools this engine was built with, UNBOUND — the list a delegated sub-agent inherits when its preset declares no grant of its own. |
promptTools(): array | The tool list the NEXT request actually carries (P-CTX.a): the launch list as turnTools() shapes it for a turn — merged config limits applied, ledger-bound tools included or dropped by the session's pruning mode, engine-delegating copies bound. tools() is the UNBOUND launch list; /context must price what ships, not what was built, so the tool-schema and MCP figures ride this accessor — the same call promptSectionSizes() folds into the session App. |
withSkills(array $skills): self | |
skills(): array | The prompt skills every turn's sessionApp() is spliced onto (ISS-035): the read pair of withSkills(), public because the palette's Ctrl+S enablement must dedupe against what is already shipped — a skill enabled mid-session belongs to this list, not only to the launch filter's. |
withSkillRegistry(SkillRegistry $skillRegistry): self | Attach the discovered SkillRegistry (built-in + user + project + foreign-imported skills, see \SugarCraft\Code\Skills\SkillManager::loadAll()) so it reaches App::$availableSkills on every complete() call — the seam \SugarCraft\Code\Cli\Bootstrap uses to make skills discovered from the agents-spec, Claude and opencode trees — project and user, both opencode user trees included (see \SugarCraft\Code\Skills\ForeignSkillDiscovery) actually visible to a real bin/candy-code run instead of only to their own unit tests. |
skillRegistry(): ?SkillRegistry | The SkillRegistry attached by withSkillRegistry(), or null when none was. The mirror of instructionLoader() — the -p one-shot path reads it so a typed /skill-name rewrite and a $name mention resolve against the SAME registry the launch's backend (and the Skill tool at self::complete()) was built with, never a second fresh discovery pass (C-WEB-2.c). |
instructionLoader(): ?InstructionFileLoader | The session's shared InstructionFileLoader, or null when none was attached. The mirror of withInstructionLoader() — TaskTool's delegation path reads it to re-point the run's tools (ISS-065). |
withInstructionLoader(InstructionFileLoader $instructionLoader): self | Attach the session's shared InstructionFileLoader so it reaches App::$instructionLoader on every complete() call — the seam that makes a repo-root CLAUDE.md/AGENTS.md actually reach the model's system prompt on a real bin/candy-code run rather than only on an on-touch Read/Edit/Glob of that same directory. |
withHooks(HookManager $hookManager): self | |
withPermissionGate(PermissionGate $permissionGate): self | Attach the 6-mode PermissionGate — Phase 1 item 2's consolidation seam, sibling to withHooks(). |
permissionGate(): ?PermissionGate | The gate this backend was built with, or null when it has none. |
hookDispatcher(): ?HookDispatcher | The session's hook dispatcher over the hooks it was given — the same registry dispatchTurnHooks() judges tool calls against, handed out so collaborators that are NOT tools can announce lifecycle events the way the turn path does (C6: the workflow engine's stage events). Null exactly when the backend was built without a HookManager; the dispatcher is cheap to re-mint, so no memo. |
withSubAgentGrant(?\SugarCraft\Code\Hooks\BuiltIn\SubAgentGrantHook $grant): self | Hold every call the turns of this copy make to a delegated sub-agent's own tool declaration (step 4.2) — see \SugarCraft\Code\Hooks\BuiltIn\SubAgentGrantHook for why the name-narrowed roster alone left Bash(git *) meaning "any Bash". |
withPermissionApprover(\Closure $approver): self | Attach the approver that settles an ASK — from PermissionGateHook or from any other PreToolUse hook — into a real allow/deny. |
withClientCallSink(\Closure $sink): self | Attach the parent-side listener for client_call frames (C-TOOL-6.h). The sink is called as fn(PendingClientCall $pending, \Closure $answer): void, where $answer takes (string $content, bool $isError) and settles the call exactly once — first answer wins, later ones no-op. With no sink bound, the parent answers every call at once: "no client is attached to serve …", which is the fork-channel twin of the proxy's own no-caller refusal. |
withClientCaller(\Closure $caller): self | Bind the child-side caller onto this engine's \SugarCraft\Code\Tools\RelaysClientToolCalls tools (C-TOOL-6.h). Set by the forked child from its ChildChannel::clientCaller(); never set from outside the child, which is why an unforked turn has none and its proxies refuse. |
withoutHooks(): self | Escape hatch for callers that deliberately want an UNGUARDED engine — no built-in hooks, no custom manager. Everything else is safe-by-default (see resolveHookManager()), so opting out is an explicit choice. |
withRoot(?string $root): self | Anchor this backend's turns at $root, so Runtime's environment block and its \SugarCraft\Code\Hooks\HookContexts name the same directory the tools withTools() received are jailed to. |
withMemoryStore(?MemoryStore $memoryStore): self | The memory store whose project-scope notes reach the model's system prompt. @see App::$memoryStore |
rulesState(): ?RulesState | The session's rulebook toggle set. @see App::$rulesState |
withRulesState(?RulesState $rulesState): self | Install the launch's rulebook toggle set, for the per-turn carry complete() makes onto the App. |
withCompactorConfig(?CompactorConfig $compactorConfig): self | The compaction budgets this backend's turns are priced against. Null restores the default (CompactorConfig::new()). |
compactorConfig(): CompactorConfig | The compaction budgets the next turn's App is built with — the configured one, else the one the compaction.* / contextPruning.* settings describe (CompactorConfig::fromSettings(), roadmap N-P4b; CompactorConfig::new() when none is set) — with the per-model absolute caps for this backend's model applied (CompactorConfig::forModel(), roadmap 2.9). With no override naming the model that is the configured instance itself. |
withMaxSteps(int $maxSteps): self | |
withWrapUpAt(int $percent): self | Roadmap 4.7-2 (Zed's sub-agent context guard): once a request this backend's turn SENT used $percent of the context window or more, the model is told once to wrap up or hand off; a request at WRAP_UP_STOP_MARGIN points past it after that stops the run. 0 turns it off; completeTranscript() uses SUB_AGENT_WRAP_UP_PERCENT unless this chose otherwise. |
withTurnInbox(?TurnInbox $inbox): self | The same engine, delivering $inbox's messages into its turns at each step boundary — see $turnInbox. Bound by \SugarCraft\Code\Tools\BuiltIn\TaskTool on the run it delegates; null takes it off. |
withSpendCap(?float $capUsd, float $sessionSpendAtStartUsd = 0.0): self | The per-dispatch install of E20's mid-turn spend cap: the dollar ceiling plus the session spend the turn STARTS at, as a pair. Returns a clone; the cap is a launch-again decision, never a mutation of the backend a previous turn is still running. |
withSiblingSpend(?SiblingSpendLedger $ledger): self | The same engine, recording each step's spend onto $ledger and reading its siblings' spend off it at every cap check — see $siblingSpend. Bound by \SugarCraft\Code\Tools\BuiltIn\TaskTool on the run it delegates; null takes it off. |
withStepUsageObserver(?\Closure $observer): self | The same engine, reporting each step's usage to $observer as it is billed — see $stepUsageObserver. Null takes it off. |
withChunkUsageObserver(?\Closure $observer): self | The same engine, reporting each streamed chunk's usage to $observer as it arrives — see $chunkUsageObserver. Null takes it off. |
withMaxConcurrentDelegations(?int $slots): self | The same engine, capping each turn's concurrent delegated runs at $slots (clamped to at least 1) — see $maxConcurrentDelegations. Null caps nothing — the \SugarCraft\Code\Agents\AgentPoolConfig default is itself uncapped. |
mainMailbox(): ?MailboxTurnInbox | The session's own agent's mailbox (roadmap 4.4), drained at the main turn's step boundaries so a sub-agent's SendMessage reply reaches it without a Subagents list|wait — or null with no session, no owned home, or a session id no mailbox can be named by. |
withSessionId(?string $sessionId): self | The same engine, running its turns as session $sessionId — see $sessionId. A blank id is no session. |
withContextLedger(?\SugarCraft\Code\Context\Pruning\ContextLedger $ledger): self | The same engine, running its next turn over the session ledger $ledger (roadmap 2.2-2) — see $contextLedger. Null runs without one. |
contextLedger(): ?\SugarCraft\Code\Context\Pruning\ContextLedger | The session ledger the next turn starts from, or null — see $contextLedger. |
withWorktreeRoot(string $worktreeRoot): self | Confine this backend to a sub-agent's git worktree: every path-resolving tool is re-jailed to $worktreeRoot, and BashEscapeDenyHook is registered so Bash commands that name paths outside it are refused. |
complete(array $history, ?callable $onToken = null, ?callable $onEvent = null, ?callable $onReasoning = null, ?callable $onHeartbeat = null): Message | |
completeTranscript(array $messages, ?callable $onEvent = null, ?callable $onReasoning = null, ?callable $onHeartbeat = null, ?callable $onToken = null, ?callable $onStep = null, ?\Closure $stopRequested = null): TranscriptTurn | complete() over TYPED history, answering with the turn's whole transcript as well as its reply — every assistant step with its tool calls and every tool result, which the root-Message history complete() takes cannot carry. It exists so a delegated run can be RESUMED: \SugarCraft\Code\Tools\BuiltIn\TaskTool persists the transcript of a run that ended without a report and feeds it back here to continue exactly where it stopped. |
promptSectionSizes(): array | The next request's system prompt per layer (roadmap 5.6, /context), built the way a turn builds its request: the session App WITH the turn's tools (ISS-063 — without them the tool-guidance layer measured empty while it shipped full) and the resolved hook manager (the permission-gate hook the plan-mode layer's lookup needs, which the bare manager never carried). Like summaryReply()'s App, this reuses the session's memo after the first prime rather than re-walking the repository map and instruction files. |
dumpSystemPrompt(): array | The next request's system prompt verbatim and the tools riding it (/context --raw, GAP-PRM-15), built the SAME way promptSectionSizes() builds its rows — the session App with the turn's tools (ISS-063's lesson: without them the dump would describe a request no turn ever sends) and the resolved hook manager — so the dumped bytes and the panel's row-bytes sum are equal by construction, and the dump test pins it. Fresh guard per call, as there. |
cacheBreaks(): int | How many prompt-cache breaks this session has seen — requests that read under half of the prefix the request before them had cached (CacheHealthWatch::observeReuse(), roadmap 3.B-5, DCP §13.2 P2-10). Read by /context. Every clone of this backend shares one watch, and a forked turn's count rides home on its result frame, so the hosted Chat's copy answers for every turn the session ran. |
lastCacheBreak(): ?array | The newest cache break as the cached share before and after it, in whole percent, or null when there has been none — see cacheBreaks(). |
static turnIdleTimeoutSeconds(?array $config = null): int | The turn's idle ceiling in whole seconds: the turnIdleTimeoutSeconds setting, else COMPLETE_TIMEOUT_SECONDS - roadmap N-P4a. |
completeAsync(array $history, ?callable $onToken = null, ?CancellationToken $cancellation = null, ?callable $onEvent = null, ?callable $onReasoning = null, bool $interactive = false, ?callable $onStep = null): PromiseInterface | Runs complete() - one or more real, blocking provider HTTP calls plus any tool execution the agentic loop drives - in a forked child so the caller's event loop (the TUI's render/input loop) never blocks on it. Without this, Program's futureTick()-scheduled Cmd execution calls this method's factory closure directly on the loop: the old implementation wrapped a *synchronous* complete() call in a React\Promise\Promise whose executor runs immediately (that's the Promise constructor's contract, not deferred), so the "async" call was really just a blocking one wearing a Promise - the whole terminal froze (no spinner animation, no keystrokes, no Ctrl+C) for the full duration of every provider round-trip. Forking moves that blocking work off the loop entirely; the parent only watches a non-blocking socket via Loop::addReadStream() for the result, so rendering and input keep flowing while a turn is in flight - same rationale as \SugarCraft\Code\Chat::executeToolsParallel()'s R14b fork fix, extended here to cross the ReactPHP loop boundary rather than just fanning out sibling tool calls. |
completeInteractive(array $history, ?callable $onToken = null, ?CancellationToken $cancellation = null, ?callable $onEvent = null, ?callable $onReasoning = null, ?callable $onStep = null): PromiseInterface | InteractiveTurn: completeAsync() with the turn's ASKs put to $onEvent as \SugarCraft\Code\Events\PermissionAsked and answered through their PendingAsk (roadmap 1.C-1, Appendix O §5.1). The child attaches a ChildChannel approver in place of whatever approver this backend carries; the parent owns the policy. $onStep takes the turn's step/usage frames (roadmap 1.C-4), as on completeAsync(). |
withSummaryModel(?string $model): self | A copy whose summaries — the in-turn step summary (roadmap 2.4-1) and summariseAsync() — go to $model instead of the turn's own (see $summaryModel). Null or blank is the turn's own model, the default, because that is the one whose prefix the provider has cached. |
summaryModel(): ?string | The model summaries go to, or null for the turn's own. |
summariseAsync(array $history, string $instruction, ?CancellationToken $cancellation = null, bool $flushMemory = false): PromiseInterface | SummarisesWithCache: the request a turn of $history would send — this backend's system prompt, its tool schemas, the history converted the way completeAsync() converts it — plus $instruction as the final user row, answered by the first assistant message (roadmap 2.4-2). |
static subAgentTotals(array $encoded): array | A beat's running totals, each 0 when absent or out of shape — kept as the codec's public entry point; the rules live on SubAgentActivity::totals() with the rest of the v2 validator. |
SugarCraft\Code\Cli
Bootstrap final class
Wires up the CLI's shared, side-effecting collaborators: backend selection, the built-in coding tools, and the real on-disk SessionStore/MemoryStore/InstructionFileLoader that back /branch, /rewind, and /memory (P6.S9/S11/S12/S15).
| Method | Summary |
|---|---|
static launchNoticeLimit(): int | How many launch notices this launch seats on the transcript: notices.transcriptLimit when it is an int of at least 0 (0 seats none, leaving the one "and N more" row), else LAUNCH_NOTICE_LIMIT. |
static applyMediaRenderMode(array $userConfig): void | Resolve the launch's image render mode and hand it to \SugarCraft\Code\ToolResult::setRenderMode() (W2.2). |
static observabilitySink(): \SugarCraft\Code\Observability\EventSink | Build the launch's OBS-1 event sink (roadmap: typed spans from the src/Events/* DTOs over OTLP/HTTP-JSON, hand-rolled — no open-telemetry packages on a TUI tree). |
static chat(?string $root = null): Chat | Build the fully-wired Chat model the CLI binary hands to Program. |
static tabChat(?string $root, ?string $sessionId): Chat | P-TABS.d: the tab strip's session factory — one Chat per tab, built on the SAME workspace the launch described (the sharedWorkspace() memo), so opening a tab costs no re-scan of config, skills, hooks or agents. |
static workspace(?string $root = null): \SugarCraft\Code\Host\WorkspaceContext | The non-UI half of chat(): everything a session needs from its project root that is not a screen, as one \SugarCraft\Code\Host\WorkspaceContext (roadmap O-2a, Appendix O §4.3). |
static outboundWebhookEndpoints(array $userConfig): array | C-AGT-5.f: the webhooksOut user-tier map, validated for launch. Parsing lives in \SugarCraft\Code\Automation\OutboundWebhookConfig::parse() (https-only except literal loopback, secrets of at least 16 bytes, known event names only); this method only decides *where* the setting is read and turns a parse refusal into the exit-2 launch refusal. Absent key means dark, exactly like an empty map. |
static channelsDiscordSettings(): array | The channels.discord policy tree, user tier only; the full D6 rationale rides ChannelsSettings::userTierMap(). Never throws. |
static channelsMsteamsSettings(): array | The channels.msteams policy tree, user tier only; rationale rides the same door. Never throws. |
static workflowEngine(?string $root, PermissionGate $gate, ?SkillRegistry $skills = null): WorkflowEngine | The WorkflowEngine /workflow dispatches onto, reading workflows from this user's ~/.candy-code/workflows and, when the launch has a root, that project's .candy-code/workflows. |
static projectTierRefusals(): array | Every project-tier directory this launch declined to read, keyed by the configured path, mapped to why. |
static reportProjectTierRefusals(): void | Tell the user, once per refused directory, that a project directory their repository ships was not read. |
static bundles(?string $root): array | The installed plugin bundles this launch reads, keyed by the exact (root, pluginPaths) pair it was last asked about. |
static agentManager(?string $root = null, ?SkillRegistry $skills = null): AgentManager | The AgentManager a launch delegates through, with the run's roster already registered. |
static agentRoster(string $root, string $provider, string $model): array | Every agent a launch can delegate to: the six built-in AgentDefinition templates, then any .md+frontmatter preset discovered under {root}/.candy-code/agents or ~/.candy-code/agents. |
static foreignAgentPresets(string $root): array | The agent presets other coding CLIs left on disk — Claude Code's .claude/agents and opencode's .opencode/agents, project tier and user tier — mapped onto \SugarCraft\Code\Agents\AgentPreset and keyed by filename stem, the same key space agentPresets() uses. |
static agentPresets(string $root): array | The native agent presets on disk, project directory first so a checked-in preset overrides a same-named one in the user's home. |
static app(?string $root = null, ?string $tuiErrorLog = null, ?string $initialPrompt = null): App | Delegates to LaunchContext::app() — the body moved in the S1b composition split (W7-E C5); this keeps the door the binary and the settings-schema reader citations name. |
static dockFromUserConfig(): ?DockLayout | Delegates to LaunchContext::dockFromUserConfig() — body moved in W7-E C5. PUBLIC since the same commit: the moved app() body reaches this door, and src/App/App.php's citation names it as the launch's loader, while DockPersistenceRoundTripTest keeps reflecting it here. |
static paneAutoShowFromUserConfig(): PaneAutoShow | Delegates to LaunchContext::paneAutoShowFromUserConfig() — body moved in W7-E C5. PUBLIC since the same commit: the moved app() body reaches this door, and DockPersistenceRoundTripTest keeps reflecting it here. |
static provider(): array | Delegates to LaunchContext::provider() — the body moved in the S1b composition split (W7-E C3); this keeps the door (and its visibility) every caller and the settings-schema reader citations name. |
static agentPoolConfig(?string $providerName = null): \SugarCraft\Code\Agents\AgentPoolConfig | The pool configuration this launch hands \SugarCraft\Code\Chat (E652). Everything else on \SugarCraft\Code\Agents\AgentPoolConfig keeps its documented default; this method exists to carry what only the launch can answer: which provider the forked workers inherit, and the subagentMaxConcurrent setting (roadmap N-P4f) — the pool width and the engine's per-batch Task cap, read from the merged config here. |
static workerProviderSpec(?string $providerName = null): ?array | The serializable provider SPEC (not an instance) forked sub-agent workers are handed at startup (E652), built from the SAME selection provider() uses for the hosted backend: the default config of the selected provider plus the launch's model override. The worker constructs its own provider child-side from this array — ProviderFactory::create() there, and ['type' => 'echo'] honoured as the one offline spelling. |
static backend(?string $root = null, ?SkillRegistry $skills = null, ?PermissionGate $gate = null, bool $consolePermissionPrompt = false, ?RulesState $rulesState = null, ?AgentManager $taskManager = null, ?\SugarCraft\Code\Agents\AgentWorkerPool $taskPool = null): Backend | Backend selection, in priority order: |
static backendFor(string $providerName, ?string $root = null, ?SkillRegistry $skills = null, ?PermissionGate $gate = null, bool $consolePermissionPrompt = false, ?RulesState $rulesState = null, ?AgentManager $taskManager = null, ?\SugarCraft\Code\Agents\AgentWorkerPool $taskPool = null): Backend | |
static useMaxTurns(?string $maxTurns): void | Delegates to LaunchContext::useMaxTurns() — the store and its full doc-block moved to the launch-context shelf in the v4 S1b split; the seam stays here so every caller reaches its registration there. |
static maxTurns(): ?int | The --max-turns ceiling for this launch as a positive whole number, or null when the flag was not given. |
static resolvedMaxToolSteps(?array $config = null): ?int | The operator's per-turn provider-call ceiling — the --max-turns flag (maxTurns()) if given, else the settings key below — or null when no usable one was set - F2 (spawn-latency plan), flag half added by COMPARISON.md §6.5 AUT-5. |
static resolvedReasoningEffort(): ?string | PRV-2 (§6.5): the configured reasoningEffort as the name of one Effort tier, or null when it is absent or anything else. There is deliberately no flag for it: the roster in Cli/ArgvParser.php is frozen for this shape of knob, and /effort is the live door anyway. |
static providerOverrides(): array | The providers map from the layered settings reader (rv-enduser-1): name => partial config array, each entry needing at least a string type to be honoured. Entries without one are dropped silently here and reported by availableProviders() when the palette asks, so a malformed row costs a name, never a launch. |
static providerConfigFor(string $name, ProviderFactory $factory): array | Delegates to LaunchContext::providerConfigFor() — the body moved in the S1b composition split (W7-E C3); this keeps the door (and its visibility) every caller and the settings-schema reader citations name. |
static availableProviders(): array | Every provider name currently selectable, for the Ctrl+P palette's Switch Model action: the built-in provider types ProviderFactory::availableTypes() knows about, plus every name declared under 'providers' in the project's .candy-code/config.dev.json (e.g. 'dev-sglang') - reusing ProviderFactory's existing lookups rather than adding new discovery logic. Silently returns just the built-ins when that config file is absent/unreadable/invalid, matching ProviderFactory::projectProviderConfig()'s own tolerance for a missing project config. |
static userConfigPath(): string | ~/.candy-code/config.json — per-user persisted UI choices (provider/theme, written by the Ctrl+P palette's Switch Model/ Switch Theme actions; layout, written by the shell; and whatever the settings editor saves on the "You" tier, the per-provider models among them) plus hand-authored settings, such as the instructions glob array forcedInstructions() reads. Distinct from ProviderFactory::defaultConfigPath()'s project-level .candy-code/config.dev.json dev/test fixture — that one is checked into the repo and shared; this one is a real per-user runtime state file, same directory convention as sessionStore()/memoryStore(). |
static useConfigPath(?string $path): void | Delegates to LaunchContext::useConfigPath() — the store and its full doc-block moved to the launch-context shelf in the v4 S1b split; the seam stays here so every caller reaches its registration there. |
static useSessionLaunch(bool $continue, bool $resume = false, ?string $target = null): void | Delegates to LaunchContext::useSessionLaunch() — the store and its full doc-block moved to the launch-context shelf in the v4 S1b split; the seam stays here so every caller reaches its registration there. |
static useIncognito(bool $incognito): void | Delegates to LaunchContext::useIncognito() — C-SES-7.c: bin registers --incognito here exactly as it registers the launch mode, and every session-opening surface reads the one static. |
static incognito(): bool | Whether this launch keeps nothing — LaunchContext::incognito(). |
static useRestricted(bool $restricted): void | Register --restricted (C-SEC-7.b) — the flag's one launch notice is recorded HERE, at the seam that makes the restriction real, for the same reason the bypass-mode notice rides its resolution rather than the TUI paint: a launch that narrowed its tools without saying so is indistinguishable, from the model's end, from a launch that failed to wire them. Transcript AND stderr (the funnel's standing both-channel law) — a -p run pipes its answer elsewhere and the operator must still see what was taken away. |
static restricted(): bool | Whether this launch cannot run code — LaunchContext::restricted(). |
static useSafeMode(bool $safeMode): void | Register --safe-mode (C-SEC-7.b), with the same one-launch-notice discipline as useRestricted() — the flags can be combined, and each states its own narrowing because each can be set without the other. |
static safeMode(): bool | Whether this launch ignores all trust — LaunchContext::safeMode(). |
static pinPromptHistoryPath(?string $path): void | Delegates to LaunchContext::pinPromptHistoryPath() — the store and its full doc-block moved to the launch-context shelf in the v4 S1b split; the seam stays here so every caller reaches its registration there. |
static promptHistory(): PromptHistory | The cross-session prompt file ↑/↓ recall reads and Enter appends to. |
static sessionLaunchError(): ?string | Why the session --resume <target> named cannot be opened, or null when it can (or when no target was named). bin/candy-code asks before the TUI takes the terminal, so a typo is a usage error rather than a silent fresh session. Since D1 (RS-DRIVER a) this is also the pre-flight that collides a --session-id preset against the store — same reason: a driver that asked for a taken address must be told, not silently re-pointed. NonInteractive::run() asks it on the -p path. |
static openSession(SessionStore|EnhancedSessionStore $store, string $provider = 'candy-code', string $model = 'unknown'): array | Open the session this launch runs in, as useSessionLaunch() registered it, with the conversation to put back on screen. |
static useModel(?string $model): void | Delegates to LaunchContext::useModel() — the store and its full doc-block moved to the launch-context shelf in the v4 S1b split; the seam stays here so every caller reaches its registration there. |
static useTuiErrorLog(?string $destination): void | Delegates to LaunchContext::useTuiErrorLog() — the store and its full doc-block moved to the launch-context shelf in the v4 S1b split; the seam stays here so every caller reaches its registration there. |
static usePermissionMode(?string $mode): void | Delegates to LaunchContext::usePermissionMode() — the store and its full doc-block moved to the launch-context shelf in the v4 S1b split; the seam stays here so every caller reaches its registration there. |
static useMaxCost(?string $maxCost): void | Delegates to LaunchContext::useMaxCost() — the store and its full doc-block moved to the launch-context shelf in the v4 S1b split; the seam stays here so every caller reaches its registration there. |
static readUserConfig(): array | Reads the persisted user config, tolerantly: a missing, unreadable, or invalid-JSON file returns [] rather than throwing - there is nothing yet to persist on a fresh install, and a corrupt file shouldn't block the CLI from starting. |
static readUserConfigWithoutProjectTier(): array | readUserConfig() WITHOUT the project tier — what the user's own files (and the session and managed tiers) say. For a key a trusted project may only switch OFF (\SugarCraft\Code\Permissions\ReadOnlyCommands::autoAllowEnabled()): the merged value lets the project narrow it, this one stops the project widening it back. |
static userSettingsDirOrNull(): ?string | The directory LayeredSettings::USER_FILE is read from, or null when this process cannot establish whose home it is. |
static useProjectRootForSettings(?string $root): void | Name the project whose .candy-code/settings.* files this process may consider — called by the four entry points that resolve a $root (chat(), app(), backend(), backendFor()). |
static projectSettingsTrusted(string $root): bool | Whether the operator opted this project root in to contributing settings — projectCommandShellIsTrusted()'s shape for LayeredSettings::PROJECT_SETTINGS_TRUST_KEY, with the same fail-closed-on-every-uncertainty behaviour and the same once-per-process freeze. |
static writeUserConfig(array $patch, array $unset = []): void | Read-merge-write $patch into the persisted user config, so a single call only ever touches the keys it names (e.g. switching the theme doesn't clobber a previously-persisted provider choice). This is the ONE door through which the CLI writes its settings file; the private helpers below it only resolve, lock and read. |
static mutateUserConfig(\Closure $change): void | The read-merge-write of writeUserConfig() with the caller's decision INSIDE the lock: $change receives the strict-read config as it stands once the cross-process lock is held and answers [patch, unset] (or null to write nothing). A caller that derived its patch from a read taken BEFORE the lock (login merging one provider into providers) lost a concurrent writer's sibling entry; deriving it here cannot. |
static skillRegistry(string $root): SkillRegistry | Discover every skill reachable from $root and hand back the populated registry: built-in (src/Skills/BuiltIn), user (~/.candy-code/skills), project ({$root}/.candy-code/skills), and foreign imports from other coding CLIs' conventions — {$root}/.agents/skills, ~/.agents/skills, {$root}/.claude/skills, ~/.claude/skills, {$root}/.opencode/skills, ~/.opencode/skills, ~/.config/opencode/skills (see \SugarCraft\Code\Skills\ForeignSkillDiscovery). |
static promptEnabledSkills(SkillRegistry $registry): array | The skills whose FULL BODIES the system prompt carries every turn. |
static skillSkips(): array | Every SKILL.md this process's skill scans could not read, keyed by path. |
static reportSkillSkips(): void | Tell the user, once and in one line, that some skill files were skipped. |
static reportMemorySkips(?string $root): void | Tell the user, once and in one line, that some of their memory notes could not be read and are being skipped. |
static reportPromptBudgetDeferrals(?string $root, ?SkillRegistry $skills = null): void | Tell the user, at launch, which instruction files and enabled skill bodies the system prompt leaves out. |
static reportNonsenseLimits(?string $root = null): void | Tell the user, at launch, that maxToolSteps or maxOutputTokens holds a value the resolvers will not use. |
static reportTuiErrorLogFallback(): void | Tell the user when this TUI session's diagnostics are not going to the home log. |
static commandSkips(): array | Every *.md command file this process's command walks could not read, keyed by path (E172). |
static hooks(?PermissionGate $gate = null, ?string $root = null): HookManager | The launch's PreToolUse/PostToolUse chain: the built-in guards, then whatever hookFiles() found on disk, then the permission gate. |
static projectCommandShellIsTrusted(string $root): bool | Whether the operator has opted this project root in to running the ` !cmd form of a command file under <root>/.candy-code/commands` — projectMcpIsTrusted()'s shape for TRUSTED_PROJECT_COMMANDS_CONFIG_KEY, with the same fail-closed-on-every-uncertainty behaviour and the same once-per-process freeze. |
static trustedBundleCommandNames(): array | The bundle names the operator opted in under TRUSTED_BUNDLE_COMMANDS_CONFIG_KEY (C-SEC-3.b) — the ANSWER list chat() hands Chat, which forwards it to \SugarCraft\Code\Commands\CommandShellPosture::optedIn(). Empty by default: the blanket refusal of a bundle's shell forms is the shipped posture until the operator names a bundle, and --safe-mode answers empty whatever the config says (trustedOriginNames()). |
static mcpPromptShellServers(): array | The MCP server keys the operator opted in under MCP_PROMPT_SHELL_CONFIG_KEY (C-SEC-3.b), same shape and same freeze as trustedBundleCommandNames(). |
static permissionGate(bool $interactive = false, bool $announceBypassMode = true, string $consoleSurface = self::PERMISSION_SURFACE_BACKGROUND): PermissionGate | The launch's PermissionGate — Phase 1 item 2's "constructed from the same config source as sub-agents". |
static projectNarrowingRuleSignatures(): array | Signatures (action pattern) of the rules projectNarrowingRules() loaded this process, for the tier column of /permissions. Keyed-set so a repeated gate build is idempotent. |
static resetProjectNarrowingRulesForTesting(): void | Drop the per-process project-rule signatures. Launch code never calls this; the test suite does, because each test owns a different fake project and the roster has to answer only for the current one. |
static permissionSettingsLayer(string $path): array | The permission keys of ~/.candy-code/settings.json — Phase 6 item 4's permission/permissionMode settings block. |
static permissionRules(array $config, ?\Closure $report = null, RuleSource $source = RuleSource::User, ?string $file = null): array | EVERY COMPLAINT HERE GOES TO BOTH CHANNELS — see warnPermissionConfigInTranscript(). A dropped rule is a SILENT WIDENING: PermissionRule degrades a malformed pattern to a name no real tool matches, so a Deny typo'd this way denies NOTHING and the session runs wide open for as long as it lasts. That is the one thing on this path a user has to learn while the session is still running, and stderr under the alternate screen is precisely where they cannot. |
static launchNotices(): array | The launch warnings chat() seeds the transcript with — see warnPermissionConfigInTranscript(). |
static launchNoticesDropped(): array | The clipped messages that fell past LAUNCH_NOTICE_LIMIT this launch — the sentences behind the synthesised "...and N more" row. The store and its set-not-counter law live with the shelf in LaunchNotices::droppedMessages(). |
static mcpConfigDecision(?string $root = null): array | Where the project's MCP config is, what it declares, and whether this launch may act on it — the routing seam for McpDecision, which computes the verdict from paths and trust records this class still owns. |
static mcpDisabled(): bool | Whether MCP starts at all this launch — the environment switch and the user-tier setting, read through McpDecision::mcpDisabled(). |
static mcpServerInventory(?string $root = null): array | The panel's table of declared servers, computed by McpDecision::mcpServerInventory() from this launch's decision. |
static trustProjectMcp(?string $root = null): array | Opt one repository's project-tier MCP servers in, through McpDecision::trustProjectMcp(), recording the choice in the operator's own settings file. |
static pendingProjectTrust(?string $root): array | C-SEC-5.a: which trust targets this root declares but does not yet hold — the census behind the one prompt. Reads the four trust doors and the memo client's pin refusals through ProjectTrustCensus; never launches, never writes. The declares probes are deliberately narrow: Commands counts only a file with a ! form that COULD run (\SugarCraft\Code\Commands\CommandSpec::hasShellSubstitution()), or every repository shipping a plain command file would be asked. |
static mcpPinRefusals(?string $root = null): array | C-SEC-5.a: the servers this process's memo client refused — pins that drifted from what mcp trust fingerprinted. Read through McpDecision::mcpPinRefusals(), memo-only: a cold process has nothing to refuse and this never builds a client to find out. |
static grantProjectTrust(TrustTarget $target, string $root, ?\SugarCraft\Code\Config\Settings\SettingsWriter $writer = null): array | C-SEC-5.a: THE ONE GRANT DOOR for one census row. mcp and mcp-pin go through trustProjectMcp() — grant and pin record land together, because a pin cannot be approved apart from the list it keys on; every other target goes through \SugarCraft\Code\Config\Settings\SettingsWriter::grantTrust(), the settings editor's already-wired confirmed action. Both doors write the OPERATOR's own config only — a project can never grant itself through this (or any) path, the property \SugarCraft\Code\Protocol\TrustAsks is built on. |
static mcpLivenessSnapshot(?string $root = null): ?array | Whether the servers this launch's decision names are actually live, read from the client memo this class keeps — computed by McpDecision::mcpLivenessSnapshot(). |
static mcpConfigChangedSinceLaunch(?string $root = null): ?bool | Whether either MCP tier's bytes drifted since this launch built its client, read through McpDecision::mcpConfigChangedSinceLaunch() against the per-tier digests this class stores at client-build time. |
static claudeMcpGrant(): ?array | The operator's claude-server MCP grant, read through McpDecision::claudeMcpGrant(). |
static mcpClient(?string $root = null): ?McpClient | The launch's MCP client, with its configured servers STARTED, or null when this project has no usable .mcp.json. |
static mcpTools(?string $root = null): array | The model-facing McpToolBridge for every tool the launch's MCP servers advertise — empty when there is no config, which is the common case. |
static mcpToolShape(?string $root = null): ?McpToolShape | The launch's frozen bridge/dispatch split, or null while no client exists. |
static userScriptTools(?string $root = null): array | The model-facing UserScriptTool for every valid file in the user's ~/.candy-code/tools/ directory — the USER tier only, and the project tier is never consulted (C-TOOL-6.e): a repository must not be able to mint tools, for the same reason mcpConfigDecision() caps what a project .mcp.json can do. |
static stopMcpServers(): void | Delegates to LaunchContext::stopMcpServers() — the shutdown shelf moved to the launch-context in the v4 S1b split; this seam keeps the public contract. |
static readLedger(?string $root = null): ReadLedger | The launch's ONE read ledger for $root (roadmap 3.I-2, EDT-1): the instance handed to every \SugarCraft\Code\Tools\Catalog\ToolBuildContext built this process makes for that root AND to the post-edit format hook, so a formatter's rewrite recorded by the hook is the same picture Read, Edit, Write and ApplyPatch consult — that identity is the feature, and it is what widened the ledger's scope from per-tool-build to per-launch. |
static backgroundShells(?string $root = null): BackgroundShellRegistry | The launch's background-shell tables (SHL-1), per process and per root — the readLedger() shape for the same reason: Bash, ShellOutput and ShellStop must consult ONE table per build, a forked tool child records into its copy, and the parent merges the copy back through the tools' \SugarCraft\Code\Tools\CarriesSessionState exports. |
static stopBackgroundShells(): void | Delegates to LaunchContext::stopBackgroundShells() — the shutdown shelf moved to the launch-context in the v4 S1b split; this seam keeps the public contract. |
static lspClient(?string $root = null): ?LspClient | The language servers the user configured under lsp (step 3.F), started once and shared by every tool, hook and forked turn of this launch — or null when none is configured or none would start. |
static stopLspServers(): void | Delegates to LaunchContext::stopLspServers() — the shutdown shelf moved to the launch-context in the v4 S1b split; this seam keeps the public contract. |
static lspTool(?string $root = null, ?LspClient $client = null): LspTool | The model-facing LspTool, wired to the launch's language servers. |
static egressProxy(): ?EgressProxyProcess | THE LAUNCH'S EGRESS PROXY (C-TOOL-4.g) — started at most once per process image, when (and only when) the user-tier bashSandbox reads allowlist on a Linux jail host. Bootstrap::tools() calls it as its FIRST statement, so the proxy exists before any tool child is forked and every fork inherits the live unix socket path the jail re-binds; the memo answer (including the resolved-null one for off/on/ no-network/Darwin launches, which never need a relay) is shared by \SugarCraft\Code\Tools\Sandbox\SandboxFactory::fromSetting(), which only ever reads the shelf — a doctor probe cannot spawn. |
static tools(?string $root = null, ?InstructionFileLoader $loader = null, ?SkillRegistry $skills = null, ?LspClient $lsp = null, bool $rgAvailable = false, bool $fdAvailable = false, ?RulesState $rulesState = null, ?AgentManager $taskManager = null, ?\SugarCraft\Code\Agents\AgentWorkerPool $taskPool = null): array | Build the built-in coding tools, filtered for the session — the whole model-facing tool array. The body moved to LaunchContext::tools() in the S1b composition split (W7-E); this stays the public door every caller and census reaches, and forwards every argument untouched. |
static installSecretEnvAllowlist(?array $config = null): void | Install the operator's secretEnvAllowlist on ProcessContainment::useSecretEnvAllowlist(). |
static unfilteredTools(?string $root = null, ?InstructionFileLoader $loader = null, ?SkillRegistry $skills = null, ?LspClient $lsp = null, bool $rgAvailable = false, bool $fdAvailable = false, ?RulesState $rulesState = null): array | The exact array LaunchContext::unfilteredTools() builds, before the session's allowedTools/disabledTools filter. The body moved in the S1b composition split (W7-E C2); this stays the public door — AgentManager::resolveGrantedTools() and the ledger-sharing tests name it here — and forwards every argument untouched. |
static filterToolSet(array $tools): array | Apply the user's allowedTools / disabledTools settings to the model-facing tool set — Phase 6 item 3's tools.allow / tools.deny. |
static instructionLoader(?string $root = null): InstructionFileLoader | The one session-lifetime InstructionFileLoader shared by the backend and the Read/Edit/Glob tools, so a root CLAUDE.md/AGENTS.md is read (and its @imports expanded) once per session rather than once per consumer. |
static requireRoot(?string $root): string | The directory a run is rooted at: the caller's --root, else the process working directory. |
static forcedInstructions(): array | The user-configured forced-instruction glob patterns, read from the "instructions" key of ~/.candy-code/config.json. |
static projectForcedInstructions(): array | Forced-instruction patterns that reached the merged config BEYOND the user-tier list forcedInstructions() reads — i.e. anything a PROJECT-tier settings file could contribute. User-tier-only today: instructions is not in PROJECT_TIER_KEYS, so this is empty on every real launch; it exists so the loader's refusal of absolute and ~ patterns FROM THE PROJECT TIER is a wired rule rather than dead code (C-CTX-4.c), and it is the seam InstructionFileLoader::loadForced() consumes. |
static excludedInstructions(): array | The operator's instructionsExclude patterns — every instruction file whose checkout-relative spelling matches one of them is skipped by InstructionFileLoader and RECORDED in its refusedPaths rather than silently dropped. Malformed entries degrade to "that one pattern is ignored" exactly as forcedInstructions() does, because both lists are hand-authored in a config file; a pattern that will not compile matches nothing, so exclusion fails OPEN — this key removes context the operator asked to remove and never removes more on a parse ambiguity. |
static sessionStore(bool $prune = true): EnhancedSessionStore | Real, on-disk session store backing /branch, /rename, and /rewind. |
static sessionRetentionDays(): int | How many days an unnamed session survives without being touched, from CANDY_CODE_SESSION_RETENTION_DAYS, else the sessionRetentionDays setting (roadmap N-P4g). |
static seedSession(\SugarCraft\Code\Session\SessionStore|EnhancedSessionStore $store, string $provider = 'candy-code', string $model = 'unknown'): array | Give the CLI a real session row to run against, resuming the most recent one when the store already has sessions and creating one when it does not (§5 E1's sketch). |
static selectedProviderLabel(): array | Delegates to LaunchContext::selectedProviderLabel() — the body moved in the S1b composition split (W7-E C3); this keeps the door (and its visibility) every caller and the settings-schema reader citations name. |
static selectedProviderName(): ?string | Delegates to LaunchContext::selectedProviderName() — the body moved in the S1b composition split (W7-E C3); this keeps the door (and its visibility) every caller and the settings-schema reader citations name. |
static backendCommandTierIsSelected(): bool | Whether this run is on one of backend()'s two shell-out tiers — $CANDY_CODE_BACKEND_CMD or $CANDY_CODE_BACKEND_CMD_STREAM. |
static titleBackend(): ?Backend | A deliberately cheap Backend for Chat's one-shot session-title call, or null when this run has no provider to build one from. |
static summaryBackend(?Backend $main = null): ?Backend | The session's summary backend (Phase 5 item 6; roadmap 2.4-2), or null when this run has no provider to build one from. |
static summaryModel(): ?string | Delegates to LaunchContext::summaryModel() — the body moved in the S1b composition split (W7-E C3); this keeps the door (and its visibility) every caller and the settings-schema reader citations name. |
static advisorBackend(): ?Backend | The advisor backend (C-PRV-3.d, roadmap W24), or null — and null is the DEFAULT answer, deliberately, unlike its two siblings. |
static maxCostUsd(): ?float | The spend ceiling for this launch, in US dollars — from the --max-cost flag (useMaxCost()), else $CANDY_CODE_MAX_COST, else the maxCostUsd setting (persistedMaxCostUsd()) — or null for no cap (Phase 5 item 7, flag half of ISS-006). |
static keybindingsSetting(): array | The keybindings override map as the launch should apply it. |
static reportKeybindingCollisions(): void | Announce every registered keybindings override that landed on another binding's SHIPPED chord (rv6 follow-up to ISS-047). |
static reportSkippedClaudeSettingsEvents(): void | Drain the skip-and-record accumulators: an event a foreign Claude Code settings file names that \SugarCraft\Code\Hooks\HookEvent has no case for is skipped at parse (ClaudeSettingsHooks), and since C-EXT-1.b so are entries of an unsupported string type and entries carrying keys this dialect does not speak. All of it is announced HERE as ONE aggregate row whatever the count — the reportSkillSkips() contract. Reached from chat()'s drain block, which runs AFTER workspace() construction read every hook file, so one call sees every parse the launch made. Supersedes the old hard refusal for the CC dialect ONLY (R3's native hooks.yaml refusal is untouched — a foreign vendor's evolving event list must not brick every launch; that blast radius WAS the defect). |
static reportHomeDirectoryStandIn(): void | v1:m-1: say it out loud ONCE when this launch resolved ~ through the temp-directory stand-in (\SugarCraft\Code\Support\HomeDirectory::standInUsed()). The stand-in itself is unchanged — the loud paths that REFUSE on it (cli.refuse.no_home) stay exactly as they were; what was missing is that every NON-refusing reader kept working off /tmp/.candy-code with no signal that the home resolution had degraded. One row whatever the call count: the seam de-dupes by message identity. |
static reportHomeFromPasswd(): void | S-H03: the one-line stderr notice for the launches that never reach the TUI drain (-p/run, serve) when ~ resolved through the passwd database because $HOME and $USERPROFILE are both unset. Notice only — the directory is a real one and nothing refuses on it. Once per process (the seam de-dupes by message). |
static terminalGuidanceNotice(string $term, bool $tty, bool $consoleVtEnabled = false): ?string | The dumb-family test, split out as a pure function so the gate is pinned by a table instead of a fake terminal. THE FAMILY: '' (TERM unset — nothing was advertised), and any dumb…/unknown… prefix, case- and whitespace-insensitively. xterm, screen, vt100 and friends get nothing — a normal launch stays byte-unchanged, which is the polarity the existing transcript pins keep asserting. |
static consoleVtEnabled(): bool | Whether the Windows console on STDOUT has virtual-terminal processing on. Only ever true on native Windows; sapi_windows_vt100_support() with no second argument only asks, it does not switch the mode on. |
static reportTerminalGuidance(?bool $tty = null, ?bool $consoleVtEnabled = null): void | v2:a11y-F3: guide a launch on a TTY that can NOT speak TUI — before, TERM=dumb users met a wall of bytes with no pointer at the paths that work for them. Gated on the tty as well as the family: the -p/scripted shapes answer on pipes all day and need no advice. The $tty seam defaults to reading stdout for real (the sugar-readline q3 idleSleeper pattern — an injectable observation point so the positive half is pinned without minting a pty in the suite). |
static reportBundleRecommendations(?string $root = null, ?MarketplaceRegistry $registry = null, ?string $stampFile = null, ?string $installedRoot = null): void | C-EXT-4.d: the marketplace bundles that fit the project being opened, named at launch, once per project per marketplace pin, from local bytes only. |
static reloadKeybindings(): void | /keys reload: re-read the keybindings setting and re-apply it to the LIVE registry — plan_comparison TUI-4a. NO file watcher: the user edits the file and says the word, the same stance the MCP digest detection takes, and for the same reason — re-applying a repository- adjacent choice without being asked re-arms surprises the freeze closed. Absent launch digest (an embedder that never booted through chat()) means the first reload APPLIES rather than claiming anything. |
static macAltNotice(string $osFamily, bool $kittyCapable): ?string | plan_comparison TUI-5 stage 1: the Option-as-Meta hint for macOS launches. PURE so every quadrant is pinned on a Linux host. |
static terminalSpeaksKittyKeyboard(): bool | Whether the ambient terminal environment names a kitty-speaking emulator — delegated to MacAltNotice::terminalSpeaksKittyKeyboard(), which since C-TUI-7.b also reads the emulator identity variables that survive tmux, so a Mac inside tmux-on-kitty is no longer misread as needing the Option-as-Meta lecture. |
static memoryStore(?string $root = null): MemoryStore | Real, on-disk memory store backing /memory. MemoryStore's constructor requires its directory to already exist and be writable, so the directory is created here first. |
static memoryStoreOrNull(?string $root = null): ?MemoryStore | memoryStore(), or null if it cannot be opened. |
static trustedConfigDirPath(): string | configDirPath() for the two files that are SECURITY POLICY rather than preference — config.json (permission mode, permission rules, trustedProjectHooks) and hooks.yaml (shell commands run on tool calls) — and therefore the one path resolution that may not fall back to a directory anybody else can write. |
static capabilityPresent(string $binary, ?string $pathList = null): bool | Is $binary installed and executable? |
static systemConfigPath(): string | The managed tier's read target — \SugarCraft\Code\Config\LayeredSettings::SYSTEM_CONFIG_PATH unless a pin has aimed it elsewhere through useSystemConfigPath(). --config does NOT move this path: that override replaces layer 4 and nothing else, and the settings editor's doors never consult this method at all — no write seam in src/ resolves to the managed path, which \SugarCraft\Code\Tests\Config\ConfigWriteProducerDocumentationDriftTest pins as structure. |
static useSystemConfigPath(?string $path): void | Aim the managed-tier READ at another path, for pins; null (or blank, same law as useProjectRootForSettings()'s blank refusal) restores the fixed /etc/candy-code/config.json. Deliberately not an environment variable — see \SugarCraft\Code\Config\LayeredSettings::SYSTEM_CONFIG_PATH for why a movable managed path is the tier's own defeat. Not stored through LaunchContext: this is a test seam, not a launch flag, and keeping it here says so. |
static managedLayer(): array | THE MANAGED TIER SITS ON TOP OF THE SESSION TIER (G1-L7, CCOPS-6): the read-only machine-wide file (\SugarCraft\Code\Config\LayeredSettings::systemLayer(), aimed by systemConfigPath()) outranks the session tier as well — its whole purpose is a control the person being managed cannot undo by re-choosing in the settings view — while the environment and flags still outrank it, for exactly the stated SessionSettings reason. It carries only \SugarCraft\Code\Config\LayeredSettings::LAYERED_KEYS, so no unlayered permission key reaches a reader through it, and like the session tier it is laid on the merged result, not handed to LayeredSettings::merge(). Both halves of the tool-removal diff get it too, so a managed narrowing can never read as a project-tier removal — and can never be blamed on one. |
static useSessionLaunchPresetId(?string $sessionId): void | Delegates to LaunchContext::useSessionLaunchPresetId() — D1 (RS-DRIVER a): --session-id registers on the same launch-context seam as the mode/target pair, so the one funnel every session-opening surface reads is also the one that sees the preset. |
static sessionLaunchPresetId(): ?string | The id --session-id pre-allocated for this launch, if any. |
static useAgentPreset(?string $name): void | Register --agent <name> for this process — delegates to LaunchContext::useAgentPreset(), the launch-context shelf where the store lives beside the model and permission registers (C3, RS-AGENT). |
static trustedBundleChannelNames(): array | The bundle NAMES allowed to load their declared channel entrypoints in-process, frozen for the life of this process — the third gate on that door, and the only one a bundle can never touch, since the list is read exclusively from the user's own configuration file. |
Subcommands final class
The real CLI subcommands — mcp list, session list|show|rename|delete| pin|unpin|archive|unarchive, models, doctor, bundles list|install, serve, self-update, usage and completion bash|zsh|fish (Phase 4 item 6; the session verbs past list/delete are Appendix P §3.4; serve is Appendix O §4.7, its body in Serve — the one verb that keeps running rather than answering, and still constructs no Program; attach is Appendix O §4.9, its body in Attach — the one verb that DOES run the TUI, over a running server's session, and only once it has connected; acp is roadmap 5.9, its body in Acp — the one verb whose stdin and stdout belong to another program, an editor speaking the Agent Client Protocol, and which runs turns without a screen); self-update is DST-3, its body in SelfUpdate — the one verb that rewrites the file it was launched from (a phar-only swap, sidecar-verified before the rename, with a one-shot --rollback).
| Method | Summary |
|---|---|
static dispatch(ParsedArgs $args): int | Run the subcommand $args carries and return the process exit code. |
static setLoginSeamsForTesting(?\Closure $spawn, ?\Closure $keyRead, ?\Closure $tty = null): void | |
static resetLoginSeamsForTesting(): void | |
static setLspInstallSeamForTesting(?\Closure $seam): void | |
static resetLspInstallSeamForTesting(): void |
SugarCraft\Code\Providers
SglangProvider final readonly class
| Method | Summary |
|---|---|
__construct(private string $baseUrl, private string $model, private ?string $apiKey, private Client $httpClient, private ?ToolCallParserInterface $toolCallParser = null, private string|float|null $reasoningEffort = null, private array $extraTemplateKwargs = [], private ?string $sessionAffinityId = null, private ?\Closure $serverInfoLoader = null, private ?bool $supportsVision = null, private ?int $contextWindowOverride = null) | |
static openAiCompatible(string $baseUrl, string $model = self::DEFAULT_MODEL, ?string $apiKey = null, ?ToolCallParserInterface $toolCallParser = null, string|float|null $reasoningEffort = null, array $extraTemplateKwargs = [], ?string $sessionAffinityId = null, bool $discoverServerInfo = false, ?bool $supportsVision = null, ?int $contextWindowOverride = null): self | |
serverInfo(): ?SglangServerInfo | What the server said about itself, read once per provider and memoised - null when no loader is armed or the read failed. |
servedModel(): ?string | The served model this provider adopts, for the TUI's labels - read from what serverInfo() has ALREADY memoised (the parent's first frame normally loads it, via contextWindow()), else from what a forked turn child reported (noteServedModel()). Never runs the loader: see ReportsServedModel::servedModel(). |
noteServedModel(string $servedModel): void | Remember the served name a forked turn child discovered, so the parent's labels can show it. Kept apart from the info memo on purpose: it is a label fact, and it neither marks discovery as done nor changes what addressedToServedModel() sends. |
static defaultToolCallParserFor(string $model): ToolCallParserInterface | The parser used when the operator named none, chosen from the MODEL: DSML wrapped around the OpenAI-array parser for the DeepSeek-V4 family, the OpenAI-array parser alone otherwise. The one definition of that rule - ProviderFactory::createSglang() asks it at build time for a configured model, resolvedToolCallParser() at request time for an adopted served one. ProviderFactory's private defaultToolCallParserFor() docblock carries the argument for arming DSML by default on that family. |
static argumentDecoder(): \Closure | W1.A6 (§12 D6): the truncation-aware function.arguments decoder, handed out so a parser built *outside* this class still reports the §12 D5 MiniMax </parameter> truncation instead of silently degrading to no arguments. |
name(): string | |
shapesEffortFor(string $model): bool | |
catalogKey(): ?string | PRV-1 (§6.5): the configured base, normalized for memo identity. |
listModels(): ?array | PRV-1: one bounded GET {base}/models; the server's answer or null. |
listModelsAsync(?callable $sender = null): PromiseInterface | C-PRV-5.c: the async sibling of listModels() — same bounded read on the event loop, resolves to exactly what the sync ask returns, never rejects. $sender is the endpoint's test seam; production callers pass nothing. |
supportsStreaming(): bool | |
acceptsAssistantPrefill(string $model): bool | Roadmap 2.7-2: every model SGLang serves continues a final assistant turn on continue_final_message (see buildParams()), so a length-stopped or dropped reply is continued exactly. |
supportsFunctionCalling(): bool | |
supportsDocuments(): bool | Whether an attached image may go out as an image_url part. The provider block's supportsVision wins when set; otherwise the SERVER answers - /model_info's has_image_understanding, read by the same memoised discovery as the context window - and a server that did not say (discovery off, failed, or an older SGLang) counts as no vision. Erring that way costs an image its pixels, never the turn: the image becomes a named text placeholder and the user is told (\SugarCraft\Code\Backend\EngineBackend::toTypedMessages()), where a guessed "yes" would send a text-only model a part its chat template rejects. |
supportsVision(): bool | |
supportsJsonSchema(): bool | True because buildParams() forwards CompleteRequest::$jsonSchema as response_format.json_schema.schema, which a live round-trip against the skynet2 SGLang v0.5.16 / MiniMax-M2.7 deployment (2026-08-10) confirmed actually binds output to the schema: the same prompt returns free prose without response_format and schema-conforming JSON with it. |
contextWindow(): int | W1.A6 (§12 D8), now MODEL-AWARE - and it had to become so, because the single figure it used to return was measured on a model this server no longer runs. |
costPer1kTokens(string $model, string $direction): float | |
complete(CompleteRequest $request): CompleteResponse | |
completeStream(CompleteRequest $request): \Generator | |
embeddings(EmbeddingsRequest $request): EmbeddingsResponse | A transport failure or a 2xx body that is not an embeddings payload THROWS instead of returning an empty list. The old silent [] made an outage (model not loaded, 5xx, refused connection) look exactly like "no results", so a semantic-search consumer degraded without ever telling the user why. The wrap mirrors complete()'s: the server's own error.message when it sent one, code 0, and the Guzzle exception as previous so TransientFailure::isTransient() still classifies 5xx/429/ connect as transient and 400 as permanent. A present-but-empty data: [] remains a legitimate empty result. |
static isDeepSeekV4(string $model): bool | True when a model id names the DeepSeek-V4 family. |
static isQwen3Next(string $model): bool | True when a model id names the Qwen3.8 family - the ids the skynet2 deployment serves as Qwen/Qwen3.8-Flash-Next and the bare alias Qwen3.8-Flash-Next (qwen.md E-70). |
static placeSystemRows(array $rows, ?string $systemPrompt): array | The one placement rule for system content on an OpenAI-shaped wire (step 1.A-1), shared with CustomProvider: rows already formatted by a provider's formatMessages(), the request-level prompt, out comes the body's messages list. |
static systemNoticeContent(string $content): string | A mid-history system row's content as the user-role notice that carries it: fenced in <system-notice> so the model reads it as the harness speaking, not the user. The notice's own fence name is neutralised inside the payload (same terminator rule as \SugarCraft\Code\Context\PromptFence::escape()), so quoted text — a queued prompt, an error message — cannot close it early. |
parseUsage(array $usage): Usage | Parses this endpoint's usage object into the provider-counted token BUCKETS (prompt_plan.md P4.S2). The single place this provider reads usage fields, so parseResponse() and any later carrier agree by construction about what the server actually said. |
static errorBodyMessage(GuzzleException $e): ?string | §Q8 (qwen.md; E-56): lifts the server's own clean error sentence out of a failed SGLANG HTTP response, or returns null when there is nothing clean to show. |
sessionAffinityHeaderValue(?string $sessionId): ?string | The wire value for one session id: full 64-char lowercase hex, or null when there is no session to be affine to (null or blank id). |
sessionAffinityHeaders(?string $requestSessionId = null): array | The per-request headers option at a post() site: [] or the one affinity header — for the request's own session id when it names one (step 0.13-a), else the host class's $sessionAffinityId. |
SugarCraft\Code\Workflows
WorkflowEngine final class
Executes workflows sequentially, stage by stage.
| Method | Summary |
|---|---|
__construct(private readonly WorkflowRegistry $registry = new WorkflowRegistry(), private readonly AgentWorkerPool $pool = new AgentWorkerPool(), private ?AgentManager $agentManager = null, private readonly string $model = 'claude-sonnet-4-6', private readonly string $provider = 'anthropic', private readonly ?PermissionGate $permissionGate = null, private readonly ?string $environmentRoot = null, private readonly ?array $toolRegistry = null, private ?HookDispatcher $hookDispatcher = null) | |
model(): string | The model every stage's agent is dispatched on. |
provider(): string | The provider label every stage's agent carries. |
permissionGate(): ?PermissionGate | The gate this engine's sub-agents carry, or null when none was given. |
setAgentManager(AgentManager $agentManager): void | Attach the AgentManager that parallel-stage sub-agents register with. |
setAgentRoster(?iterable $roster): void | P1-6: the agent roster a task's preset: <name> resolves against — the list \SugarCraft\Code\Cli\Bootstrap::agentRoster() builds (built-ins < foreign < native project < native user presets), the same tiers Task resolves names in. Without one the engine falls back to its AgentManager's roster; with neither, a plan naming a preset is refused before anything is dispatched. Null clears it. |
setAgentRosterSource(?\Closure $source): void | P1-6 / C5: setAgentRoster(), deferred — $source is called (once) the first time a preset has to be resolved or named, so a host can wire the session's roster (which reads preset files from disk) without paying for it on a run that names no preset. A source that throws leaves the engine with no roster, which refuses a preset run loudly. |
presetNames(): ?array | C5: the preset names a preset: may name on this engine — for WorkflowLinter::lint()'s $presetNames — or null when the engine has no roster at all (the lint then leaves the engine's pre-flight to refuse). Sorted. |
static presetsNamedBy(Workflow $workflow): array | C5: every preset name $workflow's tasks name, at any depth (stage, agents, pipeline steps, verification, map steps) — empty when none does, so a caller asks the roster only when it must. |
setCpuCount(?int $cpus): void | Pin the CPU count the default parallel width is computed from (P0-3: an unset maxConcurrent runs min(16, max(1, cpus - 2)) agents at once). Null restores host detection. A mutable-service setter for the setAgentManager() reason. |
concurrencyFor(Workflow $workflow): ?int | The width a parallel stage of $workflow runs at (P0-3): the explicit maxConcurrent when one is set, null (no cap) for an explicit 0, and Workflow::defaultConcurrency() of the host's CPUs when unset. |
agentManager(): ?AgentManager | The AgentManager parallel stages route through, or null when none is set. |
bindEngineBackend(EngineBackend $engine): void | Point this engine's stages at the session's CURRENT backend, so every stage agent runs that backend's real tool loop (EngineExecutor). |
bindHookDispatcher(?HookDispatcher $hookDispatcher): void | Late and mutable for the same reason as bindEngineBackend(): the session build site owns the hook chain and hands it over only after the launch workspace closes, through \SugarCraft\Code\Hooks\HookManager::armWorkflow(), before the engine's first run. Null keeps the constructor's documented unarmed contract — the engine announces nothing. The CLI verb seat never calls this, so a headless run stays byte-identical to the shape it has always had. |
run(string $workflowPath, array $context = [], ?CancellationToken $cancellation = null, ?int $budgetTokens = null): WorkflowResult | Load a workflow from the registry and execute it with the given context. |
runFromPhp(callable|string $workflowClass, array $context = []): WorkflowResult | Execute a workflow directly from a class name or callable that returns a Workflow. |
runWorkflow(Workflow $workflow, array $context = [], ?CancellationToken $cancellation = null, ?int $budgetTokens = null): WorkflowResult | Execute a Workflow value the CALLER built — the model-authored plan the Workflow tool parses with WorkflowRegistry::fromYamlString() (roadmap 4.10-2) — through the same stage loop, declaration checks and fail-fast rule as run(). |
runPlan(Workflow $workflow, string $planYaml, array $context = [], ?CancellationToken $cancellation = null, ?int $budgetTokens = null): WorkflowResult | P1-8: run a Workflow-tool (model-authored) plan AS A RESUMABLE RUN. |
resumePlan(string $runId, ?Workflow $workflow = null, ?string $planYaml = null, ?array $context = null, ?CancellationToken $cancellation = null, ?int $budgetTokens = null): WorkflowResult | P1-8: resume Workflow-tool run $runId with $workflow — the plan as it stands now, possibly edited; null re-reads the stored plan, which is what /workflow resume <runId> does. |
runRecordDirectory(): string | P1-8: the directory this engine keeps run records in (.running/ under the registry's user tier) — capture files live in <runId>.stages/ under it (stageCapturePath()). |
setAnnouncementSink(?\Closure $sink): void | P2-2: stream every announcement as it is made — $sink($line, $meta) with $meta = ['kind' => announce|truncation|casualties|budget|ceiling, 'stage' => ?string, 'workflowId' => string]. Called synchronously on the run's own path; a sink that throws is the caller's bug and is swallowed so it can never break the run. Null (the default) streams nothing — the lines are still collected on WorkflowResult::$announcements. |
setRunStartedSink(?\Closure $sink): void | Tell the caller a Workflow-tool run's ID the moment it exists, while the run is still in flight. The ID otherwise reaches the caller only in the final result, so a process killed mid-run (the model path exits 143 with no pause record) would leave the user nothing to resume by. The plan is stored at claim time, so the ID is resumable from this point on. |
pause(string $workflowId): void | Persist the current state of a workflow so it can be resumed later. |
resume(string $workflowId, ?CancellationToken $cancellation = null, ?int $budgetTokens = null): WorkflowResult | Reload a paused workflow from its persisted state and continue execution. |
listWorkflows(): array | List all available workflows from the registry. |
status(string $workflowId): WorkflowStatus | Return the current status of a workflow run. |
captureStageOutput(string $interruptId, int $stageIndex, StageResult $stageResult): string | S3: write a captured stage's FULL output to the run-scoped capture file, and return the text downstream stages see in its place: the file's path, up to CAPTURE_PREVIEW_BYTES bytes of the output, and — when the output was longer — a marked truncation naming the file's size. The write publishes by rename, the same discipline as the pause file: a reader never sees half a capture. |
static stageCapturePath(string $pauseDir, string $interruptId, int $stageIndex, string $stageName): string | Where a captured stage's output lands: a run-scoped directory beside the pause record — <pause-dir>/<id>.stages/<index>-<stage-slug>.txt. Public so a reader (a test, a follow-up agent told the path) can resolve the layout from the run's own facts, not from a second copy of the naming rule. Capture files OUTLIVE the run's clean terminal: withdrawal removes the pause record, not the work products — see WORKFLOWS.md. |
setSignalPauseHandler(?\Closure $observer): void | Install (or clear with null) the observer the SIGINT/SIGTERM handler consults on a cooperative pause — see self::$signalPauseHandler. Call BEFORE the run that may be signalled; the handler reads the property at signal time. |
WorkflowRegistry final class
Discovers and loads workflow definitions from PHP DSL files.
| Method | Summary |
|---|---|
__construct(private readonly string $workflowsPath = '~/.candy-code/workflows/', private readonly ?string $projectWorkflowsPath = null, private readonly ?string $projectRoot = null, private readonly ?string $userHome = null) | |
workflowsPath(): string | The user's own workflow directory, tilde expanded and without its trailing slash. |
projectWorkflowsPath(): ?string | The project's checked-in workflow directory, expanded, or null when this registry was built without one. |
load(string $name): Workflow | Load a workflow by name from the filesystem or registered sessions. |
list(): array | List all available workflow names from the filesystem. |
userTierRefusal(): ?string | Why this registry refuses to read its user tier's directory, or null when it does not refuse it. |
projectTierRefusal(): ?string | Why this registry refuses to read its project tier's directory, or null when it does not refuse it. |
register(Workflow $workflow): void | Register a workflow in-memory for the current session. |
loadYaml(string $name): Workflow | Load a workflow definition from a YAML file. |
fromYamlString(string $yaml, string $source = '(plan)', string $defaultName = 'plan'): Workflow | A workflow from a YAML plan held in a STRING — the plan a model hands the Workflow tool (roadmap 4.10-2) — held to every check a .yaml file gets (buildFromYamlFile()): the same loader, so a plan the model writes and a file a user writes cannot mean two different things. |
Sub-namespaces not listed row by row
A type named here has no row on this page. Each line states how many public types its namespace holds in all, so a count here is the full count.
SugarCraft\Code\Acp: 6 public typesSugarCraft\Code\Agents: 54 public typesSugarCraft\Code\Agents\Board: 7 public typesSugarCraft\Code\Agents\Live: 17 public typesSugarCraft\Code\App: 63 public types, 1 of them with a row aboveSugarCraft\Code\App\Tabs: 6 public typesSugarCraft\Code\Attachments: 4 public typesSugarCraft\Code\Automation: 4 public typesSugarCraft\Code\Backend: 32 public types, 1 of them with a row aboveSugarCraft\Code\Background: 16 public typesSugarCraft\Code\Bundles: 7 public typesSugarCraft\Code\Channels: 6 public typesSugarCraft\Code\Chat: 1 public typeSugarCraft\Code\Chat\Handlers: 6 public typesSugarCraft\Code\Cli: 29 public types, 2 of them with a row aboveSugarCraft\Code\Cli\Serve: 3 public typesSugarCraft\Code\Commands: 38 public typesSugarCraft\Code\Commands\Specs: 4 public typesSugarCraft\Code\Config: 10 public typesSugarCraft\Code\Config\Settings: 21 public typesSugarCraft\Code\Config\Settings\Definitions: 14 public typesSugarCraft\Code\Config\Settings\Validator: 11 public typesSugarCraft\Code\Config\Trust: 2 public typesSugarCraft\Code\Context: 35 public typesSugarCraft\Code\Context\Compaction: 8 public typesSugarCraft\Code\Context\Pruning: 21 public typesSugarCraft\Code\Context\Pruning\Strategies: 6 public typesSugarCraft\Code\Context\Sections: 3 public typesSugarCraft\Code\Context\Triggers: 4 public typesSugarCraft\Code\Diagnostics: 3 public typesSugarCraft\Code\Events: 14 public typesSugarCraft\Code\Format: 3 public typesSugarCraft\Code\Goal: 5 public typesSugarCraft\Code\Hooks: 18 public typesSugarCraft\Code\Hooks\BuiltIn: 17 public typesSugarCraft\Code\Host: 30 public typesSugarCraft\Code\Host\ClientTools: 3 public typesSugarCraft\Code\Host\Commands: 66 public typesSugarCraft\Code\Host\SessionHost: 5 public typesSugarCraft\Code\LSP: 13 public typesSugarCraft\Code\Lint: 4 public typesSugarCraft\Code\MCP: 31 public typesSugarCraft\Code\MCP\Serve: 2 public typesSugarCraft\Code\Media: 15 public typesSugarCraft\Code\Media\Capability: 4 public typesSugarCraft\Code\Media\Sd: 16 public typesSugarCraft\Code\Media\Video: 5 public typesSugarCraft\Code\Media\Voice: 7 public typesSugarCraft\Code\Memory: 20 public typesSugarCraft\Code\Messages: 6 public typesSugarCraft\Code\Notebook: 2 public typesSugarCraft\Code\Observability: 10 public typesSugarCraft\Code\Palette: 5 public typesSugarCraft\Code\Permissions: 34 public typesSugarCraft\Code\Protocol: 17 public typesSugarCraft\Code\Protocol\Methods: 23 public typesSugarCraft\Code\Protocol\Schema: 6 public typesSugarCraft\Code\Providers: 47 public types, 1 of them with a row aboveSugarCraft\Code\Providers\Concerns: 9 public typesSugarCraft\Code\Providers\ToolCallParser: 10 public typesSugarCraft\Code\RepoMap: 8 public typesSugarCraft\Code\Server: 11 public typesSugarCraft\Code\Server\Auth: 9 public typesSugarCraft\Code\Server\Http: 13 public typesSugarCraft\Code\Server\Pairing: 2 public typesSugarCraft\Code\Server\Push: 5 public typesSugarCraft\Code\Server\Workspace: 5 public typesSugarCraft\Code\Server\Ws: 6 public typesSugarCraft\Code\Session: 13 public typesSugarCraft\Code\Session\Gc: 5 public typesSugarCraft\Code\Session\Import: 9 public typesSugarCraft\Code\Share: 4 public typesSugarCraft\Code\Skills: 23 public typesSugarCraft\Code\Support: 54 public typesSugarCraft\Code\Support\Directories: 4 public typesSugarCraft\Code\Todo: 4 public typesSugarCraft\Code\Tools: 32 public typesSugarCraft\Code\Tools\BuiltIn: 44 public typesSugarCraft\Code\Tools\Catalog: 7 public typesSugarCraft\Code\Tools\Concerns: 6 public typesSugarCraft\Code\Tools\Edit: 18 public typesSugarCraft\Code\Tools\Sandbox: 10 public typesSugarCraft\Code\Tools\Script: 4 public typesSugarCraft\Code\Tools\UserTools: 3 public typesSugarCraft\Code\Tools\Web\Search: 8 public typesSugarCraft\Code\Tui: 37 public typesSugarCraft\Code\Tui\Commands: 11 public typesSugarCraft\Code\Tui\Components: 19 public typesSugarCraft\Code\Tui\DiffReview: 5 public typesSugarCraft\Code\Tui\DirectoryPicker: 2 public typesSugarCraft\Code\Tui\FirstRunWizard: 4 public typesSugarCraft\Code\Tui\MediaForm: 21 public typesSugarCraft\Code\Tui\MediaForm\Enum: 2 public typesSugarCraft\Code\Tui\MediaForm\Sections: 13 public typesSugarCraft\Code\Tui\Menu: 8 public typesSugarCraft\Code\Tui\MessagePicker: 3 public typesSugarCraft\Code\Tui\Settings: 15 public typesSugarCraft\Code\Tui\VideoPlayer: 5 public typesSugarCraft\Code\Tui\Window: 9 public typesSugarCraft\Code\Util: 5 public typesSugarCraft\Code\Workflows: 25 public types, 2 of them with a row aboveSugarCraft\Code\Workspace: 10 public types
Configuration
Settings come from five layers, read through LayeredSettings. On a key present in more than one file, the highest listed file wins; row 5 is the machine's and outranks the rest.
| # | File | Whose | Read when |
|---|---|---|---|
| 1 | <root>/.candy-code/settings.json | the project's, committed | the project root is listed in trustedProjectSettings and an entry point named it |
| 2 | <root>/.candy-code/settings.local.json | the project's, git-ignored | same gate as row 1 |
| 3 | ~/.candy-code/settings.json | yours, hand-authored | always, when $HOME resolves |
| 4 | ~/.candy-code/config.json | yours, partly written by the CLI | always, or at the file --config <path> names; with no resolvable home directory, a launch refuses |
| 5 | /etc/candy-code/config.json | the machine administrator; read-only to candy-code | always |
Project trust is opt-in. A cloned repository cannot change your settings, and its settings, hooks, .mcp.json and !`cmd` shell blocks are read only after you list the project root under the trustedProject* keys (see permissions and safety). A project's skills, rules and agent presets load from the repository without that listing; only a project skill's pre-approvals (allowed-tools) wait for trustedProjectCommands. Every key, its default and when a change takes effect are in docs/SETTINGS.md. Environment variables are in docs/ENVIRONMENT.md. Themes, keybindings and output styles have their own pages: THEMES.md and KEYBINDINGS.md.
Permissions and safety
Every tool call passes a PreToolUse hook chain, whose last entry is the PermissionGate. The gate decides in three steps: a circuit breaker that denies rm -rf / and rm -rf ~ in every mode, then your rules (first match wins), then the active mode. Set the mode with --permission-mode, CANDY_CODE_PERMISSION_MODE, or permissionMode in config, and switch it in the TUI with /permissions mode. Alt+M toggles plan mode only.
| Mode | Runs without asking | Asks, or is refused |
|---|---|---|
default | read tools such as Read, Glob and Grep, and read-only shell lines (ls, git log, grep and similar) | asks for writes, other shell commands and network calls; -p refuses them |
accept-edits | in-project Edit and Write, mkdir, touch and rmdir on paths below the working directory, and read-only shell lines | every other shell command asks, rm, mv and cp included, as does WebFetch |
plan | read-only Bash, and Markdown plans in .candy-code/plans/ | refuses everything else, and asks for WebFetch and WebSearch; the model leaves with PlanExit |
auto | calls the SafetyClassifier passes | a security finding asks; other flagged calls are refused, or reviewed by the title model with autoReview |
dont-ask | read-only tools, such as Read and Grep | refuses everything else, WebFetch included, without prompting |
bypass-permissions | everything, except the circuit breaker and your explicit deny rules | nothing |
Two notes. The circuit breaker and deny rules hold in every mode, bypass-permissions included. The Bash sandbox is off by default (bashSandbox). The security model is summarized in the security section, and the full gate is in docs/PERMISSIONS.md.
Commands
Slash commands are typed in the TUI or offered from the palette (Ctrl+P). The same names reach the agent as custom commands from .candy-code/commands, which the trust gate governs. The complete reference, with the frontmatter for custom commands, is in docs/COMMANDS.md.
76 slash commands, one row per spec file under builtin-commands/. The same rows sit in the marker block of docs/COMMANDS.md. Five are palette-only (Ctrl+P, not in the / popup): /new-picker, /docs, /pane-dock-left, /pane-dock-right and /generate-form. Arguments in the Takes column are the row's own argument hint.
| Command | Takes | What it does |
|---|---|---|
/new | [dir] | Start a fresh session, here or in a directory you pick |
/new-picker | — | Start a fresh session in a directory picked from a folder browser |
/close-tab | — | Close the tab deck’s current tab |
/sessions | [<query>] | List, search and manage sessions |
/session-pin | — | Pin the current session to the front of the list, or unpin it |
/session-delete | — | Open the session list to delete a session |
/model | [provider [model]] | Switch the active provider, or a provider and its model |
/effort | [low|medium|high|xhigh|max|auto] | Read or set the reasoning effort tier |
/fast | [on|off] | Read or set the fast service tier |
/share | [md|html|json] [path] | serve [--live] [days] | list | revoke [token] | Export the session to a file, or serve and revoke share pages |
/export | [md|html|json|jsonl|text] [file|--path <file>] | Export the transcript to a local file, raw bytes unredacted |
/docs | — | Open the documentation |
/exit | — | Quit the app |
/theme | — | Switch the color theme |
/settings | [search|reload] | Show every setting, its value, where it came from and when it applies |
/agents | [list|<name>|use <preset|default>|new <focus>|proposed|accept <name>] | List the agent roster, inspect one by name, open a running one's Agent View, or draft a preset and promote it with accept |
/mcp | <list|add|remove|login|reconnect|enable|disable> [server] | Manage MCP server auth (list/add/remove; login prints the CLI command) and session enable/disable |
/keys | [reload] | Show the keyboard shortcut reference (or press ?) |
/help | — | List every slash command |
/permissions | [mode <name> | revoke <n|all> | saved | forget <n|pattern>] | Show this session's permission mode, its rules and its grants; switch the mode or revoke a grant |
/notices | — | Show every warning this launch raised, un-capped and un-aggregated |
/status | — | Show where this session stands: version, model, context, spend, config, MCP, hooks, serve |
/doctor | — | Run the install checks and report every row |
/context | --raw [path] | Show what fills the context window: prompt layers, tools, history, cache |
/sweep | [n] | Prune the tool outputs since your last prompt (or the last n) from what the model sees |
/pruning | [auto|manual|off|default] | Show or set how this session prunes its context: auto, manual or off |
/compress | [focus] | Ask the model to compress a closed part of the conversation into a summary |
/decompress | [bN] | Send a compressed section in full again (no argument: list the sections) |
/recompress | [bN] | Restore the summary of a section /decompress took back |
/hooks | [log [n]] | List the hook chain: every registered hook, its matcher and state, plus matchers that failed to evaluate |
/rules | [name] | List the rule packs, or toggle one for this session |
/output-style | [name|off] | List the output styles, or select one for this session; off clears it |
/newrule | [focus] | Have the agent draft a project rule from this conversation |
/pane | dock <left|right>|toggle [name] | Dock a pane to a side, or toggle its docked state |
/layout | reset | Reset the pane layout to the launch default |
/pane-dock-left | — | Dock the focused pane to the left |
/pane-dock-right | — | Dock the focused pane to the right |
/editor | [text] | Compose the prompt in $VISUAL or $EDITOR |
/copy | [n] | Copy the last assistant reply, or its nth newest fenced code block, to the clipboard |
/compact | [--self] [focus] | Manually compact chat history to save context |
/clear | — | Clear the transcript, keeping this session |
/budget | [amount|off] | Show this session's reported spend, or cap it |
/usage | [sources|7|30|all] | Show the durable spend ledger folded by day, model and source |
/insights | [days] | Show insights on session activity and spend across the durable store |
/workflow | — | Run, pause, resume, or inspect a workflow |
/memory | — | Add, list, search, edit, import, clear, or restore memory entries, and show their history |
/instructions | [open <n|path>] | List the instruction files this session reads, and open one in the editor |
/skills | [installed|new <name> [description]|proposed|accept <name> [--replace]|reject <name>|enable <name>|disable <name>|reload|history <name>|undo <name>] | List the invocable skills, switch them on or off, review the dream pass drafts: accept or reject one, or step a learned skill back through its history |
/init | [focus] | Study this project and write or improve its AGENTS.md |
/branch | — | Fork the current session into a new branch |
/rename | [<name>|--auto] | Rename the current session |
/rewind | [n] [--chat|--files|--both] | Restore an earlier checkpoint: the conversation, the files, or both |
/undo | — | Take back the last turn, or revert the last auto-commit |
/redo | — | Step forward again over what /rewind or /undo took back |
/diff | [n] [--print] | Show what changed in the files since a checkpoint |
/review | [<tree-ish|A..B|A...B>|--pr <n>] | Review the diff against a revision and report findings without editing |
/security-review | [<ref>] | Security-review the diff against a revision and report findings without editing |
/commit | <message> | Commit all changed files, drafting the message when you give none |
/pr | [<focus>] | Push the current branch and open a pull request for it with gh |
/bg | <task> | Run a task in a background session |
/shells | [list|output <id> [cursor]|send <id> <keys…>|stop <id>] | List, read output from, and stop background shells |
/tasks | [list|tail <id>|stop <id>] | List background shells, background sessions and sub-agent runs; tail or stop a background shell |
/schedules | [list|add <name> <interval> <prompt>|enable|disable|delete <name>] | List, add, enable, disable, and delete scheduled prompt rows |
/loop | <interval> <prompt> | Re-run a prompt in this session every interval (this process only) |
/fork | <prompt> | Clone this conversation into a background session |
/websearch | <query> [--safesearch 0|1|2] [--time-range day|month|year] | Search the web via SearXNG |
/goal | [<condition>|clear] | Work until a condition is met, judged by the title model after every turn |
/grind | [<condition>|clear] | Like /goal, with a much longer budget of follow-up rounds |
/btw | <question> | Ask the title model a side question about this conversation, kept out of it |
/recap | — | Recap where this session left off and what is next (the away-recap, asked now) |
/handoff | [--remote <url>|focus] | Continue in a new session that starts from a state summary of this one |
/generate | <prompt> [--steps N] [--size WxH] [--seed N] [--save] | Generate an image on the configured SD server |
/generate-form | — | Open the interactive generation form (image and video tabs) |
/sendto | <file.png> [--to img2img|inpaint] [--mask FILE] | Import a saved PNG's parameters back into the generate form |
/play | <file|artifact-name> | Play a video artifact by name or a local clip by path in the full-screen player |
/rendermode | <mode> | Show or switch the media render mode (images repaint from the new word, the player starts from it) |
Commands with their own guides: /goal and /grind (writing a condition the judge can check), /share and /export (what each file holds and what is sent), /schedules, /workflow, and /memory and /instructions.
Tools
Every plain launch builds 38 built-in tools. The runtime name is the one a permission rule or allowedTools entry uses; the class is the file under src/Tools/BuiltIn/. The permission class is the one each tool declares with its #[BuiltInTool] attribute, or, for Task, BoardRead and BoardPost, which carry no attribute, the one ToolCatalog declares for them. read-only and no-ask tools never prompt; write-capable tools go through the mode's rules; mode default tools fall through to the mode's own answer. See PERMISSIONS.md.
| Tool | Class | Permission class | What it does |
|---|---|---|---|
Bash | Bash.php | write-capable | run a shell command with an optional timeout; run_in_background starts a background shell |
Read | Read.php | read-only | read a file with line ranges; a file too long for one page gets an outline |
Edit | Edit.php | write-capable | replace exact text in a file; one match is required, with looser fallback stages |
Glob | Glob.php | read-only | list paths matching a glob pattern |
Grep | Grep.php | read-only | search file contents with a regular expression |
Write | Write.php | write-capable | create a new file with the given content |
WebFetch | WebFetch.php | mode default | fetch the bytes served at one URL |
WebSearch | WebSearch.php | mode default | search the web through $CANDY_CODE_SEARCH_ENDPOINT (SearXNG) |
doctor | Doctor.php | mode default | probe what this build and deployment actually support |
Skill | SkillTool.php | read-only | load a skill body into context by name |
Lsp | LspTool.php | read-only | definitions, references, hover, symbols, code actions and diagnostics from a configured language server |
Memory | MemoryTool.php | no-ask | view, save, edit, delete and recall persistent memory notes |
RepoMap | RepoMapTool.php | read-only | ranked outline of the definitions the project references most, sized to a token budget |
Prune | Prune.php | no-ask | drop or distill its own finished tool outputs from what it is sent |
Todo | Todo.php | no-ask | the session checklist, rewritten whole on each call |
Compress | Compress.php | no-ask | replace a closed range of the conversation with a summary (on a turn started with /compress) |
Workflow | WorkflowTool.php | write-capable | run a model-authored YAML plan of staged sub-agents |
Recall | Recall.php | no-ask | bring back, word for word, a pruned tool output or a compressed section |
Team | TeamTool.php | no-ask | team task board for background teammates: claim, complete, dependencies and messages |
ApplyPatch | ApplyPatch.php | write-capable | add, change, move and delete several files in one *** Begin Patch call, all or nothing |
AskUser | AskUserTool.php | no-ask | put one question to the user, with optional choices, and wait for the answer |
PlanExit | PlanExitTool.php | no-ask | leave plan mode and put the written plan to the user for approval |
SendMessage | SendMessageTool.php | no-ask | message a sub-agent it launched, or its parent from inside a sub-agent |
Subagents | SubagentsTool.php | no-ask | list, wait for or cancel the sub-agents it launched, and read what they sent back |
InterruptAgent | InterruptAgentTool.php | no-ask | make a running sub-agent skip the rest of its current step and read a message first |
GenerateImage | GenerateImage.php | mode default | render a still image from a text prompt on the configured Stable Diffusion server |
GenerateVideo | GenerateVideo.php | mode default | render a short video from a text prompt on the configured video job server |
PtyRun | PtyRun.php | write-capable | run a terminal program on a pseudo-terminal, typing keystrokes and checking the screen it draws |
Ls | Ls.php | read-only | list one directory, name-sorted |
ShellOutput | ShellOutput.php | read-only | read output from a background shell |
ShellStop | ShellStop.php | write-capable | stop a background shell |
Schedule | ScheduleTool.php | mode default | create, list or delete schedules that fire recurring background prompts |
skills_search | SkillsSearch.php | read-only | find skills by keyword |
SkillWorkshop | SkillWorkshop.php | write-capable | save or amend a learned skill in the user tier |
Canvas | CanvasTool.php | no-ask | save a self-contained HTML page as a session artifact the web client can display |
Script | ScriptTool.php | write-capable | run a short PHP script whose only effects are tool calls |
ShellSend | ShellSend.php | write-capable | type keystrokes into an interactive background shell |
NotebookEdit | NotebookEdit.php | write-capable | replace, insert or delete one cell of a Jupyter notebook |
Conditional and wired tools
These are in the catalog but not in every launch's set. Task is present whenever the launch carries an agent manager (every live chat does).
| Tool | Class | Permission class | When it is offered |
|---|---|---|---|
mcp_list | McpListTool.php | read-only | when a launch defers an MCP server (lists the deferred tools and their schemas) |
mcp_call | McpCallTool.php | write-capable | when a launch defers an MCP server (runs one deferred tool) |
Advisor | AdvisorTool.php | no-ask | when advisorModel is set |
BoardPost | BoardPostTool.php | no-ask | only to the members of a parallel Task batch, to post to their shared board |
BoardRead | BoardReadTool.php | read-only | only to the members of a parallel Task batch, to read their shared board |
Task | TaskTool.php | write-capable | when the launch carries an agent manager (every live chat does) |
Tools with their own guides: Lsp (language servers and their install), RepoMap (the ranked symbol map), Prune, Compress and Recall (context management), Memory, GenerateImage and GenerateVideo, Workflow, and Schedule.
Sessions, checkpoints, undo and rewind
- Sessions. Each conversation is a session in
~/.candy-code/session.db./sessionslists and searches them,/renamenames one,/forkand/branchsplit a conversation,/handoffstarts a fresh session from a state summary, and/session-pinkeeps one at the top of the list. - Checkpoints. A checkpoint is taken for each turn that edits files.
/diffshows what changed since a checkpoint. - Undo and rewind.
/undotakes back the last turn, or reverts the last auto-commit./rewind [n] [--chat|--files|--both]restores an earlier checkpoint for the conversation, the files, or both./redosteps forward again over what was taken back. - Cost and pruning.
/usagefolds the durable spend ledger by day, model and source,/budgetcaps a session's spend, and/pruningsets how the session prunes its context. The context engine behind pruning and compaction is in docs/CONTEXT.md.
The FAQ answers the common versions of these questions: how do I undo what the agent changed, how do I keep a session from being pruned, and how do I cap the cost.
Hooks, skills, MCP and sub-agents
- Hooks. Sixteen hook events, starting with
PreToolUse. A hook returns allow, deny, modify or ask, and/hookslists the chain and its log. Full reference: docs/HOOKS.md. - Skills. A skill is a folder with a
SKILL.mdfile. Ten are built in./skillslists and toggles them, and theSkilltool loads one by name. Full reference: docs/SKILLS.md. - MCP. Servers listed in
.mcp.jsonare started after you trust the project, and/mcplists, adds, logs in to and removes them.candy-code mcp serveruns the stdio host. Full reference: docs/MCP.md. - Sub-agents. The
Tasktool runs a preset as a sub-agent, and/agentslists the roster and opens a running agent's view. Presets are authored as described in docs/AGENTS_AUTHORING.md; the roster is in docs/AGENTS.md. - Plugins. Claude-format plugin bundles, the surfaces they load and their precedence, and the bundle files that are declined are in docs/PLUGINS.md.
Background work, schedules and workflows
- Background work. Background shells and background sessions, how each is started, listed and stopped: docs/BACKGROUND.md.
- Schedules. A schedule is one prompt that repeats on a cadence. docs/SCHEDULES.md covers the rows, the cadence and the
Scheduletool. - Workflows. A named sequence of stages, each dispatching a sub-agent. The run, pause, resume and status flow is in docs/WORKFLOWS.md.
- Headless driving.
candy-code -pas a machine surface: the JSON and stream-json envelopes, the exit codes, and structured answers, in docs/FLEET-DRIVING.md.
Server, web UI and editors
candy-code serveruns sessions headless behind an authenticated WebSocket. It binds127.0.0.1by default; any other address needs--allow-remote. Pin the clients with--allowed-hostand--allowed-ips.candy-code attachconnects a terminal to a running server, and the CandyCodeWeb page drives the same sessions from a browser.candy-code acpruns the Agent Client Protocol on stdio for editors. docs/ACP.md has the setup for Zed. JetBrains IDEs and Neovim take the same command and argument in their own ACP agent settings, as the guide describes.
The wire protocol and its auth model are in docs/SERVER.md.
Maintenance: gc, usage and doctor
candy-code gc reports and reclaims disk used by the session store. The verbs run from a read-only look to a destructive purge, and the order below is the order to use them in. Only gc purge and gc vacuum write. gc vacuum writes only with --force; gc purge asks you to confirm at the terminal unless you pass --force, and in JSON mode it needs --dry-run or --force.
The session store is created on the first run. On a machine that has never started candy-code, the commands below stop with cannot open the session store, so start candy-code once first (even candy-code -p "hello").
candy-code gc status # where the bytes are (read-only)
candy-code gc sessions --sort size --limit 20 # one row per session, real bytes (read-only)
candy-code gc analyze --top 10 # ranking, growth and orphan counts (read-only)
candy-code gc purge --older-than 90d --dry-run # plan the purge; writes nothing
candy-code gc purge --older-than 90d --force # the same plan, applied
Always run --dry-run first and read the plan. gc purge needs at least one filter, strip or clean flag, and it never prunes a session that --keep-latest protects. Each flag is documented in docs/GC.md.
candy-code usageprints the durable spend ledger, the CLI form of the/usagecommand. See docs/USAGE.md.candy-code doctorruns the install checks and reports each row, including thesandboxrow that says whether the Bash jail is enabled./doctorruns the same checks inside a session.- Traces of each agent turn can go to an OpenTelemetry collector. What is sent, what never leaves the machine and what happens when the collector is down are in docs/OBSERVABILITY.md.
Troubleshooting and FAQ
- The TUI says "echo" and the model never answers: FAQ. Provider setup problems are in TROUBLESHOOTING.
candy-codeexits 2 immediately and will not start: TROUBLESHOOTING. The exit codes are listed at the top of that page.- Skills or MCP tools are missing, or a hook never fires: skills, MCP, hooks.
- Every Bash call is refused: TROUBLESHOOTING. Why a prompt appeared at all: FAQ.
- Session store errors: TROUBLESHOOTING. The full troubleshooting guide has more than twenty entries; start with docs/TROUBLESHOOTING.md.
Security model
- Model output is untrusted. Tool calls, edits and shell commands go through the permission gate; the circuit breaker, your rules and the mode decide each one.
- Project files are ignored until trusted. A project's settings, hooks and
.mcp.jsonare read only after you trust the project, and a changed MCP server definition is refused until you approve it again. - The server listens on loopback.
candy-code servebinds127.0.0.1by default, and every client must authenticate. Put TLS in front of it before you expose it. - Secrets are plain text on disk. Provider keys saved by
candy-code loginsit in~/.candy-code/config.jsonunless you pass--keychain. The session database is not encrypted. The storage options forloginare in docs/CREDENTIALS.md. - The Bash sandbox is opt-in. With
bashSandboxoff, a Bash call runs with your privileges. When it is on, Seatbelt runs on macOS and Bubblewrap on other systems.
The threat model, trust boundaries, supported versions and how to report a vulnerability are in docs/SECURITY.md.
Demos
VHS-recorded GIFs of every PHP example shipped with the app; the workflow YAML under examples/workflows/ ships without a recording. Six VHS tapes ship in .vhs/. Each tape is rendered to a GIF by the CI job in vhs.yml, which commits the result; the GIFs are not rendered by hand.
Permission
A permission prompt for a guarded tool call, answered withn, from examples/permission-prompt.php. Tape: permission.tape.
Key classes
The public classes a library user is most likely to touch, grouped by namespace under SugarCraft\Code\.
| Class | Method | Description |
|---|---|---|
Providers\ProviderInterface | complete(CompleteRequest): CompleteResponse | The single LLM abstraction: one batch completion |
Providers\ProviderInterface | completeStream(CompleteRequest): Generator | The same call, yielded as streaming chunks |
Providers\ProviderInterface | supportsStreaming(), supportsVision(), contextWindow(), costPer1kTokens(model, direction) | Capability and cost introspection, so callers do not guess |
Backend\EngineBackend | new(provider, model) | Factory; bridges the chat Backend seam to the agent engine |
Backend\EngineBackend | withTools(tools), withHooks(manager), withSkillRegistry(registry), withMaxSteps(n) | Fluent wiring of the agent loop; each call returns a new instance |
Backend\EngineBackend | complete(history, ?onToken, ?onEvent, …): Message | Runs one bounded agentic turn, emitting tool-lifecycle events |
Hooks\HookManager | registerBuiltIns(): void | Registers ProtectFilesHook, ConfirmRemoveHook and AuditHook |
Hooks\HookManager | preToolUse(HookContext): HookResult | Gates a tool call: allow, deny, modify or ask |
Hooks\HookManager | resolveAsk(ask, approved, feedback) | Settles an answered ask into a final allow or deny |
Skills\SkillRegistry | findForPrompt(prompt): array | Matches discovered SKILL.md files to the current turn |
Skills\SkillRegistry | forPaths(paths): array | Path-scoped skills for files a tool just touched |
Skills\SkillRegistry | isAutoInvocable(name), isUserInvocable(name), isContextFork(name) | Frontmatter flags, enforced |
Agents\AgentPreset | __construct(name, description, tools, disallowedTools, model, permissionMode, maxTurns, skills, mcpServers, …) | Readonly sub-agent descriptor: model, tool allow and deny lists, skills, MCP allowlist, effort, isolation |
MCP\McpClient | startServers(), stopServers() | Launches and tears down the configured stdio and HTTP MCP servers |
MCP\McpClient | listTools(), callTool(server, tool, args, …), callToolByName(tool, args) | Discovers and invokes MCP tools, filtered by the active preset's allowlist |
Permissions\PermissionGate | evaluate(ToolCall, ?projectRoot, ?sessionId): PermissionDecision | Evaluates a call against the active mode, behind the mode-independent circuit breaker |
Permissions\PermissionGate | mode(): PermissionMode | One of default, accept-edits, plan, auto, dont-ask, bypass-permissions |
Workflows\WorkflowEngine | run(workflowPath, context, …): WorkflowResult | Executes a YAML multi-stage agent pipeline |
Workflows\WorkflowEngine | runFromPhp(workflowClass, context): WorkflowResult | The same, from the PHP builder DSL |
Workflows\WorkflowEngine | pause(id), resume(id, …), status(id): WorkflowStatus | Stage-granularity pause and resume across a signal |
Session\SessionStore | createSession(id, provider, model, ?systemPrompt, ?name, …) | Opens a session row in the SQLite (WAL) store |
Session\SessionStore | addMessage(sessionId, message), addToolCall(sessionId, messageId, toolCall) | Appends a turn and its tool calls, foreign-key enforced |
Session\SessionStore | listSessions(limit), forkSession(id), renameSession(id, name) | Back the /sessions, /fork and /rename commands |
Session\SessionStore | pruneSessions(daysOld, ?exemptSessionId): int | Opt-in retention sweep; never drops a named or resuming session |
Where to go next
- The full docs index, with reading paths: docs/README.md. The user guide is README.md.
- Release notes and version tags: CHANGELOG.md, and the tags at github.com/sugarcraft/candy-code/tags.
- Source on GitHub: sugarcraft/candy-code. Runnable examples: examples/.
- Terms used across the docs are defined in GLOSSARY.md. The reasons the system prompt is layered as it is are in PROMPT_ENGINEERING.md. To build and contribute, start with CONTRIBUTING.md.
- Originally inspired by crush (Go). SugarCraft is developed as a native PHP project.