Debian Codegraph @

doc/clnkr.7.md

raw
1 % clnkr(7) Miscellaneous Information Manual
2
3 # NAME
4
5 clnkr - coding agent architecture
6
7 # DESCRIPTION
8
9 **clnkr** is a terminal coding agent with a model-command policy loop: send the
10 transcript to a model, parse one structured turn, execute approved bash
11 commands from accepted **act** turns, append command-result messages, and
12 repeat until **done**, clarification, step limit, cancellation, or policy
13 error.
14
15 The interactive CLI is documented in **clnkr**(1). This page documents
16 clnkr's act protocol, transcript structure, provider boundary, command
17 execution model, run metadata, and domain vocabulary.
18
19 # ARCHITECTURE
20
21 **Agent**
22 : The runtime object for one run. It owns the transcript, current working
23 directory, model, executor, environment snapshot, event sink, step limit, and
24 act protocol.
25
26 **Model**
27 : The provider connection used to send transcript messages to an LLM provider
28 and return a response.
29
30 **Provider adapter**
31 : The Anthropic, OpenAI Responses, or OpenAI-compatible Chat Completions path
32 between a provider API and clnkr's canonical protocol.
33
34 **Provider structured-output schema**
35 : The provider-facing schema for APIs that require different JSON wrappers,
36 tool-call records, or null-field shapes. Provider adapters project those
37 provider-specific responses into clnkr's canonical **act**, **clarify**, or
38 **done** turn. The schema includes completion verification fields for **done**
39 turns.
40
41 **CLI config resolver**
42 : The frontend-owned resolver that applies flag and **CLNKR_** environment
43 precedence, parses and normalizes base URLs, finds the API key, selects
44 provider semantics, and returns a **Resolved provider config**.
45
46 **Provider request semantics**
47 : The provider-domain vocabulary and validation for provider, provider API,
48 request options, model capability checks, and request-option validation.
49
50 **Executor**
51 : The host component that runs one bash action and returns a structured command
52 result.
53
54 **Machine-facing adapter**
55 : A **clnkrd** process used by an external tool to embed clnkr behavior behind
56 a stdio JSONL protocol. Its stdout, stderr, and event logs are ordinary
57 process artifacts that the caller must read and synthesize.
58
59 **Transcript**
60 : The ordered message history sent to the model.
61
62 **Transcript formatter**
63 : The **internal/core/transcript** boundary that formats host-authored
64 transcript blocks, including state messages, compact blocks, and bounded
65 command observations. Command-done events keep raw
66 stdout/stderr; the transcript receives bounded command result JSON.
67
68 **Context length backstop**
69 : Reactive provider context-window failure handling. When a provider reports
70 that the transcript exceeds the model context window, clnkr compacts older
71 transcript history through the existing transcript compaction path and retries
72 the failed model step once. Provider adapters classify the provider failure;
73 the driver supplies compaction and the run loop owns the failed-step retry
74 boundary.
75
76 **Session persistence**
77 : The **cmd/internal/clnkrapp** boundary service for frontend saved-session
78 operations. **cmd/clnkr** lists, saves, and resumes sessions; **cmd/clnkrd**
79 saves and resumes sessions. **internal/session** owns the local saved-session
80 file mechanics. A saved-session envelope contains transcript messages and run
81 metadata.
82
83 **Driver**
84 : The frontend coordinator around **RunWithPolicy**. It starts prompts,
85 routes compaction requests, chooses approval or full-send policy for a prompt,
86 turns policy hooks into frontend events, and passes replies back to the run.
87
88 **cmd/clnkr**
89 : The terminal adapter. It resolves CLI inputs, creates the agent and driver,
90 renders terminal output, reads human replies, and maps terminal outcomes to
91 exit status.
92
93 **cmd/clnkrd**
94 : The stdio JSONL adapter. It resolves non-interactive inputs, creates the
95 agent and driver, reads JSONL commands from stdin, writes JSONL events to
96 stdout, and writes diagnostics to stderr.
97
98 Object interactions:
99
100 ```text
101 +------------------+
102 | Frontend |
103 | clnkr / clnkrd |
104 +---------+--------+
105 |
106 | prompts, approvals,
107 | clarify replies, events
108 v
109 +------------------+
110 | Driver |
111 | frontend policy |
112 +---------+--------+
113 |
114 | run policy hooks
115 v
116 +------------------+ +-----+------------+ +------------------+
117 | Provider adapter |<-->| Agent |<-->| Executor |
118 | Anthropic/OpenAI | | run + transcript | | bash on host |
119 +------------------+ +-----+------------+ +------------------+
120 |
121 | owns/appends
122 v
123 +------------------+
124 | Transcript |
125 | canonical history|
126 +------------------+
127 ```
128
129 The main boundary is **Step** versus **RunWithPolicy**. **Step** prepares the
130 transcript for one model query, queries the model, records the response or
131 protocol failure, and returns the parsed turn. **RunWithPolicy** owns the
132 control loop: appending resource-state messages before queries, retrying after
133 protocol failures, dispatching turn policy hooks, executing approved act turns,
134 stopping on done, asking for a final summary at the step limit, and enforcing
135 step limits. In full-send runs, **RunWithPolicy** also applies an automated
136 completion gate before accepting **done** turns: it emits a completion-gate
137 event, appends guidance after rejected or challenged completions, and exits
138 after repeated invalid completions. **Run** is the full-send entry point; it
139 delegates to **RunWithPolicy** with a policy that approves act turns and leaves
140 clarify turns unanswered.
141
142 **Agent.Step** remains a single query/parse cycle. The context length backstop,
143 when configured by the driver, is handled by **RunWithPolicy** after a failed
144 step so the original user prompt is not appended a second time.
145
146 The frontend boundary is **Driver** versus command adapters. **Driver**
147 coordinates frontend interaction around **RunWithPolicy** by turning approval
148 and clarify policy hooks into frontend events and accepting replies. It does
149 not query the Model, parse Turns, or execute commands directly. **cmd/clnkr**
150 and **cmd/clnkrd** adapt terminal and stdio JSONL surfaces to the driver. The
151 command adapters use **cmd/internal/clnkrapp** for session persistence;
152 **internal/session** owns the saved-session file mechanics behind that boundary.
153
154 The configuration ownership boundary is **CLI config resolver** versus
155 **Provider request semantics**. The CLI resolver owns app inputs and user-facing
156 errors. Provider request semantics define provider/API names and validate
157 model/request-option combinations before adapters serialize requests. Provider
158 structured-output schemas and adapters own provider-specific response shapes
159 and projection into canonical turns.
160
161 Process orchestration is outside host policy. Bash is the model's only tool,
162 and **clnkrd** is an external stdio JSONL adapter, not in-session delegation
163 machinery. **/delegate** is ordinary user prompt text; the host does not
164 intercept it or map it to a **clnkrd** process. Tools, editors, wrappers, eval
165 harnesses, and automation can use the adapter directly. **Driver**,
166 **ShellExecutor**, provider adapters, provider request semantics, canonical
167 turns, and **Agent.Step** are unchanged by caller-specific orchestration.
168
169 # ACT PROTOCOL
170
171 Every accepted model response is a **turn**. There are three turn types:
172
173 **act**
174 : Ask the host to run one or more bash actions.
175
176 **clarify**
177 : Ask the user a non-empty question. Policies that can answer clarification
178 append the reply and continue the run; policies that cannot answer stop.
179
180 **done**
181 : Summarize completion with structured verification evidence and stop the run
182 successfully.
183
184 An **act** turn contains a **bash batch**. Each **bash action** contains a shell
185 command and a nullable working directory in canonical JSON. **Max steps** is
186 the execution cap; if a batch exceeds the remaining command budget, clnkr runs
187 only the commands that fit and then asks for a final summary.
188
189 A **canonical turn** is the internal JSON shape clnkr writes to the transcript
190 after a provider adapter validates model output into clnkr's turn space:
191 **act**, **clarify**, or **done**. A **provider turn** is the provider-specific
192 structured-output shape before that validation. When a compatibility adapter
193 accepts canonical response text directly, validation still produces the same
194 canonical turn stored in the transcript.
195
196 The CLI **--act-protocol** setting defaults to **auto**. The CLI resolves
197 **auto** after provider API selection. Anthropic Messages and OpenAI Responses
198 resolve to **tool-calls** because they support provider-native tool calls using
199 clnkr's **bash** tool schema. OpenAI Chat Completions and OpenAI-compatible
200 fallback endpoints resolve to **clnkr-inline**. The resolved runtime protocol
201 is always concrete: **clnkr-inline** or **tool-calls**.
202
203 **clnkr-inline** accepts provider-portable clnkr act JSON in assistant text.
204 **tool-calls** uses provider-native tool calls with clnkr's **bash** tool
205 schema for **act** turns, while **clarify** and **done** remain
206 schema-constrained JSON text. In unattended mode, inline structured output
207 omits **clarify**; tool-call mode uses tools for actions and a done-only text
208 schema.
209
210 Provider request options such as effort and output-token limits change provider
211 wire fields. They do not add turn types or change the canonical turn shape.
212
213 A **done** turn contains a non-empty summary, a **verification** object, and a
214 **known_risks** array. Verification status is **verified**,
215 **partially_verified**, or **not_verified**. **verified** completions include at
216 least one concrete check with command, outcome, and evidence.
217 **partially_verified** completions list remaining risks. This makes completion a
218 claim backed by transcript evidence instead of a summary-only stop signal.
219
220 Parser/schema validation happens before any run policy can accept a **done**
221 turn. In full-send unattended runs, **RunWithPolicy** also applies an automated
222 completion-quality gate before accepting structurally valid **done** turns. The
223 gate rejects or challenges incomplete or under-evidenced completions,
224 challenges one-check or claim/check mismatches once, appends guidance as a
225 normal user message, and emits a machine-readable completion-gate event.
226 Approval and interactive policies leave completion quality to the frontend or
227 user after parser/schema validation.
228
229 A **protocol failure** is a model response that cannot be accepted as exactly
230 one valid turn. When that happens, clnkr appends a **protocol correction** to
231 the transcript. The correction tells the model why clnkr ignored the previous
232 response and what shape to emit next.
233 Final-summary protocol failures record the invalid final response and return an
234 error instead of appending a protocol correction.
235
236 # TRANSCRIPT
237
238 The transcript includes human-authored messages and host-authored blocks.
239 Host-authored blocks use normal transcript roles because they are part of the
240 conversation sent to the model, but they are not user-authored text.
241
242 **User-authored message**
243 : A transcript message whose content came from the human user.
244
245 **Assistant message**
246 : A transcript message whose content came from the model. Accepted model turns
247 are stored as canonical assistant JSON. When a normal model query fails
248 protocol validation, clnkr stores the raw assistant response before appending a
249 protocol correction.
250
251 **Host block**
252 : A clnkr-authored transcript message.
253
254 **Command result block**
255 : A host block containing a JSON object with **stdout**, **stderr**,
256 **outcome**, and optional **command**, **feedback**, and **observation**. Exit
257 outcomes include **exit_code**. Other outcomes include **timeout**,
258 **cancelled**, **denied**, **skipped**, and **error**. Large command output
259 streams are compressed before they enter the model transcript. The executor and
260 command-done events keep raw stdout/stderr, while the transcript receives
261 bounded **stdout** and **stderr** strings with deterministic markers and
262 optional **observation** metadata. That metadata is emitted only for compressed
263 streams and records source, version, compression mode, and original, shown, and
264 omitted byte counts.
265
266 **Bash tool metadata**
267 : Optional transcript metadata beside message content. It records provider tool
268 calls, matching bash tool results, and provider/API-scoped replay items. Message
269 content is canonical clnkr transcript text; adapters use the metadata to replay
270 tool-call history without duplicating it as plain text.
271
272 **State message**
273 : A host message containing strict JSON current working directory state, for
274 example **{"type":"state","source":"clnkr","cwd":"/repo"}**.
275
276 **Resource state message**
277 : A host message with **"type":"resource_state"** containing JSON command and
278 model-turn budget state. It records **commands_used** and
279 **model_turns_used**. When a command budget is configured, it also records
280 **commands_remaining** and **max_commands**.
281
282 **Compact block**
283 : A host block containing a summary of older transcript history.
284
285 During compaction, clnkr replaces an older transcript prefix with one
286 **[compact]** tagged JSON block containing **source**, **kind**, and
287 **summary**. It keeps the recent tail starting at the selected
288 user-authored message and preserves the latest clnkr cwd state if that state
289 would otherwise be lost.
290
291 Run metadata is not a transcript message. It is emitted as a debug event and
292 persisted in saved-session envelopes outside the transcript messages so a run
293 can be inspected without adding configuration values to the model transcript.
294
295 # COMMAND EXECUTION
296
297 The executor runs commands with **bash -c**. It captures stdout, stderr, exit
298 code, and, when the shell state trap runs, the post-command working directory
299 and environment. It can also attach command feedback.
300
301 Provider request options affect model calls only. Once a model emits an
302 accepted **act** turn, command execution sees the same bash batch shape.
303
304 The executor always starts each command in its own process group so cancellation
305 can kill the shell and its children. A **base environment snapshot**, when set,
306 replaces the parent process environment as the base for the next command. The
307 executor still adds host control variables such as pager settings and the state
308 file path.
309
310 **Command result**
311 : The structured outcome of one bash action.
312
313 **Command outcome**
314 : The normalized completion state of a command: exit, timeout, cancelled,
315 denied, skipped, or error.
316
317 **Post-command state**
318 : The current working directory and environment snapshot captured after a
319 command runs.
320
321 **Base environment snapshot**
322 : The environment snapshot used instead of the parent process environment as
323 the base for command execution.
324
325 **Command feedback**
326 : Git-backed host feedback attached to a command result.
327
328 **Git baseline**
329 : The clean-worktree check recorded before a command runs.
330
331 Command feedback is emitted only when the command started from a clean git
332 baseline. The feedback contains changed file paths relative to the final
333 working directory and, for tracked changes, a combined unstaged plus staged
334 diff.
335
336 On cancellation, clnkr kills the command process group. Child processes should
337 not survive cancellation while they remain in that process group.
338
339 # PROVIDER BOUNDARY
340
341 clnkr treats provider APIs as adapters around one internal protocol.
342
343 Provider resolution is split. **cmd/internal/providerconfig** owns CLI
344 inputs: flag/env precedence, **CLNKR_** names, API key lookup, base URL parsing,
345 and user-facing configuration errors. **internal/providers/providerconfig** owns
346 provider-domain semantics: provider/API constants, provider request options,
347 model capability predicates, and request-option validation.
348
349 For OpenAI, clnkr can use the Responses API or an OpenAI-compatible Chat
350 Completions API. **provider-api=auto** selects Responses for known supported
351 OpenAI model names and model names matching OpenAI model-name patterns, and
352 keeps known non-OpenAI model-name patterns on Chat Completions.
353 OpenAI-compatible Chat Completions endpoints are requested with JSON-schema
354 structured output. For compatibility with servers that accept the schema
355 request but do not enforce clnkr's provider wrapper, the Chat Completions
356 adapter also accepts response text that is exactly one canonical
357 **clnkr-inline** turn.
358
359 For Anthropic, clnkr uses the Messages API and asks for structured JSON output
360 through the provider adapter.
361
362 **tool-calls** requires a provider API that can accept tools, return
363 tool calls with IDs, accept tool results, and let the adapter map calls/results
364 without prompt parsing. Anthropic Messages uses a custom **bash** tool. OpenAI
365 Responses uses a strict function tool named **bash**. OpenAI Chat Completions
366 is rejected for tool-call mode.
367
368 Provider adapters serialize validated provider request options. They do not
369 resolve **CLNKR_** environment variables, choose API keys, or parse CLI base
370 URLs. They still join provider endpoint paths against the configured base URL so
371 direct adapter construction and CLI config resolution follow the same request
372 path rules.
373
374 **Response**
375 : One provider reply plus usage, optional protocol failure, native bash tool
376 calls, and provider replay data.
377
378 **Raw response**
379 : Provider output retained with the response, especially for protocol failures
380 and tool-call replay debugging. Depending on the provider path, this may be
381 assistant text or a raw provider payload, and may be present on successful
382 tool-call responses.
383
384 **Usage**
385 : Token accounting for one model call.
386
387 **Refusal**
388 : A provider-declared refusal instead of usable model text.
389
390 **Structured output**
391 : JSON text requested through provider structured-output support. It normally
392 contains exactly one provider turn. The OpenAI-compatible Chat Completions
393 adapter may also accept exactly one canonical **clnkr-inline** turn as response
394 text. In tool-call mode, bash acts use native provider tool calls.
395
396 # RUN METADATA
397
398 **Run metadata** records the clnkr version, provider selection, model, system
399 prompt hash, act protocol, and provider request options. It is emitted once as
400 an **EventDebug** message containing JSON metadata and persisted with saved
401 sessions.
402
403 **Requested metadata**
404 : The provider request options after parsing, preserving whether the user
405 explicitly requested **--effort auto**.
406
407 **Effective metadata**
408 : The provider request options clnkr will put on provider calls after
409 validation and defaults.
410
411 Run metadata includes the selected **act_protocol**. Requested and effective
412 metadata use the same top-level JSON fields: **effort**, **output**, and
413 **anthropic_manual**. For effort, omitted and explicit **auto** are distinct in
414 requested metadata. Effective metadata omits the effort level for **auto**
415 because clnkr sends no provider effort field for it. For Anthropic, effective
416 metadata also records the Anthropic thinking mode and effective
417 **anthropic_max_tokens**.
418
419 # GLOSSARY
420
421 **Act proposal**
422 : The approval-mode prompt text shown before an accepted act turn executes.
423
424 **Act turn**
425 : A turn that asks the host to run one or more bash actions.
426
427 **Approval mode**
428 : A **RunWithPolicy** policy that asks before executing parsed act turns.
429
430 **Bash action**
431 : One shell command plus a working directory, represented as nullable
432 **workdir** in canonical JSON and omitted when empty in Go.
433
434 **Bash batch**
435 : The ordered list of bash actions in a single act turn.
436
437 **Bash tool call**
438 : A provider-native tool call using clnkr's **bash** tool schema, projected
439 into one bash action.
440
441 **Bash tool call ID**
442 : The opaque provider ID attached to a bash tool call and its matching
443 tool result.
444
445 **Bash tool result**
446 : The provider-native result paired with a bash tool call ID after execution,
447 denial, or skipping.
448
449 **Base environment snapshot**
450 : The environment snapshot used instead of the parent process environment as
451 the base for command execution.
452
453 **Canonical turn**
454 : The internal JSON shape used by core code and persisted assistant transcript
455 messages.
456
457 **CLI config resolver**
458 : The frontend-owned resolver that turns CLI inputs and **CLNKR_** environment
459 variables into a **Resolved provider config**.
460
461 **Command outcome**
462 : The normalized command result outcome type: exit, timeout, cancelled, denied,
463 skipped, or error.
464
465 **Completion gate**
466 : The full-send policy check that rejects or challenges structurally valid
467 **done** turns before accepting completion.
468
469 **Clarify turn**
470 : A turn that asks the user a non-empty question. Policies may answer and
471 continue, or stop when no answer is available.
472
473 **Done turn**
474 : A turn that summarizes completion and stops the run successfully.
475
476 **Driver**
477 : The frontend coordinator that turns policy hooks and top-level frontend
478 requests into terminal or JSONL interaction.
479
480 **Executor**
481 : The interface for running one shell command and returning a structured
482 command result.
483
484 **Effective metadata**
485 : The provider request state after validation, defaults, and provider-specific
486 mapping.
487
488 **Effort level**
489 : A provider-neutral effort request: **auto**, **low**, **medium**, **high**,
490 **xhigh**, or **max**.
491
492 **Manual thinking budget**
493 : The Anthropic-only legacy request for **thinking.type=enabled** with an
494 explicit token budget.
495
496 **Max output tokens**
497 : A provider request for the maximum response output token count.
498
499 **Final summary query**
500 : The done-only model query clnkr sends after the step limit is reached.
501
502 **Provider API**
503 : The OpenAI API surface selected for an OpenAI run: **auto**,
504 **openai-responses**, or **openai-chat-completions**.
505
506 **Provider request options**
507 : The provider-neutral request settings clnkr validates before constructing a
508 provider adapter request.
509
510 **Act protocol**
511 : How the model proposes command execution. User config accepts **auto**,
512 **clnkr-inline**, or **tool-calls**. Runtime surfaces receive only concrete
513 **clnkr-inline** or **tool-calls**.
514
515 **Provider base URL**
516 : The configured provider API root that provider adapters join with their API
517 endpoint paths.
518
519 **Provider request semantics**
520 : Provider-domain rules for provider/API names, model capability checks, and
521 request-option validation.
522
523 **Provider turn**
524 : The provider-specific structured-output wrapper that a provider adapter
525 projects into a canonical turn.
526
527 **Provider replay item**
528 : Provider/API-scoped data that must be sent back with later tool-call
529 history, such as an OpenAI Responses reasoning item.
530
531 **Recent tail**
532 : The un-compacted suffix of the transcript preserved during compaction.
533
534 **Resolved provider config**
535 : The app-facing result of config resolution: provider, provider API, model,
536 base URL, API key, act protocol, and validated provider request options.
537
538 **Requested metadata**
539 : The normalized provider request state derived from CLI inputs before provider
540 defaults and mapping.
541
542 **Resource state message**
543 : A host-authored transcript message with **"type":"resource_state"**
544 containing **commands_used**, **model_turns_used**, and optional command budget
545 fields.
546
547 **Run metadata**
548 : The version, provider selection, act protocol, system prompt hash, and
549 requested and effective request metadata for one run.
550
551 **RunWithPolicy**
552 : The run loop with policy hooks for approval and clarification interaction.
553
554 **Step**
555 : One model query plus protocol parsing cycle.
556
557 **Step limit**
558 : The maximum number of commands an agent run may execute before asking for a
559 final summary.
560
561 **Remaining step budget**
562 : The number of commands left before the step limit is reached.
563
564 **Turn**
565 : One structured model response in the agent protocol.
566
567 # SEE ALSO
568
569 **clnkr**(1), **clnkrd**(1), **clnkr**(3)