Repository navigation
Expand file tree
/
Copy pathplugins.html
More file actions
261 lines (227 loc) · 64.2 KB
/
Copy pathplugins.html
File metadata and controls
261 lines (227 loc) · 64.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- This file is generated by Nim. -->
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en" lang="en" data-theme="auto">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3code - plugins</title>
<!-- Google fonts -->
<link href='https://fonts.googleapis.com/css?family=Lato:400,600,900' rel='stylesheet' type='text/css'/>
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400,500,600' rel='stylesheet' type='text/css'/>
<!-- Favicon -->
<link rel="shortcut icon" href="data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAUAAAAF////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAIAAABbAAAAlQAAAKIAAACbAAAAmwAAAKIAAACVAAAAWwAAAAL///8A////AP///wD///8A////AAAAABQAAADAAAAAYwAAAA3///8A////AP///wD///8AAAAADQAAAGMAAADAAAAAFP///wD///8A////AP///wAAAACdAAAAOv///wD///8A////AP///wD///8A////AP///wD///8AAAAAOgAAAJ3///8A////AP///wAAAAAnAAAAcP///wAAAAAoAAAASv///wD///8A////AP///wAAAABKAAAAKP///wAAAABwAAAAJ////wD///8AAAAAgQAAABwAAACIAAAAkAAAAJMAAACtAAAAFQAAABUAAACtAAAAkwAAAJAAAACIAAAAHAAAAIH///8A////AAAAAKQAAACrAAAAaP///wD///8AAAAARQAAANIAAADSAAAARf///wD///8AAAAAaAAAAKsAAACk////AAAAADMAAACcAAAAnQAAABj///8A////AP///wAAAAAYAAAAGP///wD///8A////AAAAABgAAACdAAAAnAAAADMAAAB1AAAAwwAAAP8AAADpAAAAsQAAAE4AAAAb////AP///wAAAAAbAAAATgAAALEAAADpAAAA/wAAAMMAAAB1AAAAtwAAAOkAAAD/AAAA/wAAAP8AAADvAAAA3gAAAN4AAADeAAAA3gAAAO8AAAD/AAAA/wAAAP8AAADpAAAAtwAAAGUAAAA/AAAA3wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAADfAAAAPwAAAGX///8A////AAAAAEgAAADtAAAAvwAAAL0AAADGAAAA7wAAAO8AAADGAAAAvQAAAL8AAADtAAAASP///wD///8A////AP///wD///8AAAAAO////wD///8A////AAAAAIcAAACH////AP///wD///8AAAAAO////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A//8AAP//AAD4HwAA7/cAAN/7AAD//wAAoYUAAJ55AACf+QAAh+EAAAAAAADAAwAA4AcAAP5/AAD//wAA//8AAA=="/>
<link rel="icon" type="image/png" sizes="32x32" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAA3XAAAN1wFCKJt4AAAAB3RJTUUH4QQQEwksSS9ZWwAAAk1JREFUWMPtll2ITVEUx39nn/O7Y5qR8f05wtCUUr6ZIS++8pEnkZInPImneaCQ5METNdOkeFBKUhMPRIkHKfEuUZSUlGlKPN2TrgfncpvmnntnmlEyq1Z7t89/rf9a6+y99oZxGZf/XeIq61EdtgKXgdXA0xrYAvBjOIF1AI9zvjcC74BSpndrJPkBWDScTF8Aa4E3wDlgHbASaANmVqlcCnwHvgDvgVfAJ+AikAAvgfVZwLnSVZHZaOuKoQi3ZOMi4NkYkpe1p4J7A8BpYAD49hfIy/oqG0+hLomiKP2L5L+1ubn5115S+3OAn4EnwBlgMzCjyt6ZAnQCJ4A7wOs88iRJHvw50HoujuPBoCKwHWiosy8MdfZnAdcHk8dxXFJ3VQbQlCTJvRBCGdRbD4M6uc5glpY3eAihpN5S5w12diSEcCCEcKUO4ljdr15T76ur1FDDLIQQ3qv71EdDOe3Kxj3leRXyk+pxdWnFWod6Wt2bY3de3aSuUHcPBVimHs7mK9WrmeOF6lR1o9qnzskh2ar2qm1qizpfXaPeVGdlmGN5pb09qMxz1Xb1kLqgzn1RyH7JUXW52lr5e/Kqi9qpto7V1atuUzfnARrV7jEib1T76gG2qxdGmXyiekkt1GswPTtek0aBfJp6YySGBfWg2tPQ0FAYgf1stUfdmdcjarbYJEniKIq6gY/Aw+zWHAC+p2labGpqiorFYgGYCEzN7oQdQClN07O1/EfDyGgC0ALMBdYAi4FyK+4H3gLPsxfR1zRNi+NP7nH5J+QntnXe5B5mpfQAAAAASUVORK5CYII=">
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="nimdoc.out.css?v=2.4.0">
<!-- JS -->
<script type="text/javascript" src="dochack.js?v=2.4.0"></script>
</head>
<body>
<div class="document" id="documentId">
<input type="checkbox" id="nav-toggle" hidden>
<label for="nav-toggle" id="nav-burger">☰</label>
<label for="nav-toggle" id="nav-overlay"></label>
<div class="container">
<h1 class="title">3code - plugins</h1>
<div class="row">
<div class="three columns" id="page-toc">
<div class="page-toc-title">Contents</div>
<ul class="page-toc-list">
<li><a href="#introduction">Introduction</a></li>
<li><a href="#the-model-in-one-page">The model in one page</a></li>
<li><a href="#writing-a-plugincolon-the-short-manual">Writing a plugin: the short manual</a><ul>
<li><a href="#the-shape-of-a-module">The shape of a module</a></li>
<li><a href="#editing-data-in-place">Editing data in place</a></li>
<li><a href="#steering-tool-calls">Steering tool calls</a></li>
<li><a href="#registering-a-modelminusfacing-tool">Registering a model-facing tool</a></li>
<li><a href="#adding-a-subcommand-or-an-option">Adding a subcommand or an option</a></li>
<li><a href="#overriding-default-config-values">Overriding default config values</a></li>
<li><a href="#an-inminusprocess-gui-frontend">An in-process GUI frontend</a><ul>
<li><a href="#the-native-windows-gui-build">The native Windows GUI build</a></li>
</ul>
</li>
<li><a href="#long-work-and-interruption">Long work and interruption</a></li>
<li><a href="#beyond-nim">Beyond Nim</a></li>
</ul>
</li>
<li><a href="#hook-reference">Hook reference</a></li>
<li><a href="#strings-and-buffers">Strings and buffers</a></li>
<li><a href="#state-services-cancellation">State, services, cancellation</a></li>
<li><a href="#failure-handling">Failure handling</a></li>
<li><a href="#config-and-debug">Config and debug</a></li>
<li><a href="#abi-stability">ABI stability</a></li>
</ul>
</div>
<div class="nine columns" id="content">
<h2 id="introduction">Introduction</h2><p>A plugin is a native dynamic library (<tt class="docutils literal"><span class="pre">.so</span></tt> on Linux, <tt class="docutils literal"><span class="pre">.dylib</span></tt> on macOS, <tt class="docutils literal"><span class="pre">.dll</span></tt> on Windows) that 3code loads at startup and calls at fixed points in its lifecycle: the command line, prompts, tool calls, turns, sessions. There is no manifest, no registration call, no RPC protocol. The library exports C functions; the host probes for them; whichever hooks exist get called. Each <tt class="docutils literal"><span class="pre">dynlib</span></tt> carries its own runtime, so a plugin can be written in anything that speaks the C ABI, and the reference SDK makes Nim one-file simple.</p>
<p>Reach for a plugin when you want machinery on the <em>host</em> side of the agent: policy (veto writes to frozen paths, redact secrets from tool output), instrumentation (usage counters, audit logs, custom notifications), or a model-facing tool backed by your own code. For teaching the <em>model</em> something, a skill file is still the right tool: it costs nothing until used, while every plugin-registered tool schema rides along on every model request. Most plugins want both halves: a host-side hook implementation plus a small skill that tells the model how to drive it.</p>
<p>Plugins are native code running in-process with your full user rights. Install only libraries you trust, from sources you trust. The default sandbox already fences the model out of the lib directories, so an agent cannot install one for you.</p>
<h2 id="the-model-in-one-page">The model in one page</h2><p>Discovery and load:</p>
<ol class="simple"><li><tt class="docutils literal"><span class="pre">$XDG_DATA_HOME/3code/lib</span></tt> (<tt class="docutils literal"><span class="pre">~/.local/share/3code/lib</span></tt> on Linux)</li>
<li><tt class="docutils literal"><span class="pre">/usr/local/lib/3code</span></tt>, <tt class="docutils literal"><span class="pre">/usr/lib/3code</span></tt> (Linux; <tt class="docutils literal"><span class="pre">%ProgramFiles%\3code\lib</span></tt> on Windows)</li>
</ol>
<p>An optional <tt class="docutils literal"><span class="pre">[plugins] lib = path</span></tt> dir is scanned first. Files are sorted by name within each directory; on a stem collision the first match wins. A candidate that does not export <tt class="docutils literal"><span class="pre">tc_abi_version</span></tt>, or whose version differs from the host's, is skipped and noted in <tt class="docutils literal"><span class="pre">:plugins</span></tt>. Load order is the resulting sorted order, and load order is hook call order.</p>
<p>Everything else follows from one design decision: <strong>all plugin code runs on a single dedicated host thread, one call at a time, in load order</strong>. Never on the turn, net, or input threads; a plugin never needs locks of its own to be safe against the host. Sync hooks (prompt, system prompt, tool pre/result/exec, init/register/shutdown) round-trip with a deadline, so a slow plugin cannot stall a turn forever. Async hooks (turn, session, compact, file-write events) are fire-and-forget copies into a bounded queue.</p>
<p>Multiple plugins chain: mutations waterfall in load order (plugin two sees plugin one's edit), a veto or takeover short-circuits the chain and names the plugin in the tool result.</p>
<h2 id="writing-a-plugincolon-the-short-manual">Writing a plugin: the short manual</h2>
<h3 id="the-shape-of-a-module">The shape of a module</h3><p>One Nim file. The ABI types first, your hook procs in the middle, the SDK include last. The SDK include is what turns your <tt class="docutils literal"><span class="pre">onPrompt</span></tt> into the exported <tt class="docutils literal"><span class="pre">tc_on_prompt</span></tt> the host probes for, and it registers the host's plugin thread with your library's garbage collector before your first allocation:</p>
<p><pre class="listing"><span class="Keyword">include</span> <span class="Identifier">threecode</span><span class="Operator">/</span><span class="Identifier">pluginabi</span> <span class="Comment"># types + helpers (FIRST)</span>
<span class="Keyword">import</span> <span class="Identifier">std</span><span class="Operator">/</span><span class="Punctuation">[</span><span class="Identifier">json</span><span class="Punctuation">,</span> <span class="Identifier">os</span><span class="Punctuation">]</span> <span class="Comment"># your imports</span>
<span class="Keyword">proc</span> <span class="Identifier">onPrompt</span><span class="Operator">*</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Punctuation">:</span> <span class="Keyword">var</span> <span class="Identifier">TcPromptEvent</span><span class="Punctuation">)</span> <span class="Operator">=</span>
<span class="Keyword">if</span> <span class="StringLit">"deploy"</span> <span class="Keyword">in</span> <span class="Identifier">tcView</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">prompt</span><span class="Punctuation">)</span><span class="Punctuation">:</span>
<span class="Identifier">tcAssignStr</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">prompt</span><span class="Punctuation">,</span> <span class="Identifier">tcView</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">prompt</span><span class="Punctuation">)</span> <span class="Operator">&</span> <span class="StringLit">"</span><span class="EscapeSequence">\n</span><span class="StringLit">[checked by myplugin]"</span><span class="Punctuation">)</span>
<span class="Keyword">include</span> <span class="Identifier">threecode</span><span class="Operator">/</span><span class="Identifier">plugin_sdk</span> <span class="Comment"># exports the tc_* hooks (LAST)</span></pre></p>
<p>Define any subset of the optional procs; only defined ones are exported and thus subscribed by the host. Hook filtering (say, only some tools) is your job, not the host's: a cheap <tt class="docutils literal"><span class="pre">if tcView(ev.name) != "write": return</span></tt> guard at the top is the intended idiom.</p>
<p>Build and install (the ABI modules come from the 3code source tree; <tt class="docutils literal"><span class="pre">-p:</span></tt> it in, or use an installed package):</p>
<pre>nim c --app:lib --mm:orc --threads:on -p:~/p/3code/src -o:myplugin.so myplugin.nim
cp myplugin.so ~/.local/share/3code/lib/</pre>
<p><tt class="docutils literal"><span class="pre">--threads:on</span></tt> is not optional: the host calls you from its own thread, and without the SDK's foreign-thread registration your first allocation there is undefined behavior. Run <tt class="docutils literal"><span class="pre">:plugins</span></tt> to confirm the load (it lists subscribed hooks and call counts), then <tt class="docutils literal"><span class="pre">:plugin debug on</span></tt> to watch it live.</p>
<h3 id="editing-data-in-place">Editing data in place</h3><p>Read a field with <tt class="docutils literal"><span class="pre">tcView</span></tt>, replace it with <tt class="docutils literal"><span class="pre">tcAssignStr</span></tt>. The buffer you may grow is capped (see <a class="reference external" href="#strings-and-buffers">strings and buffers</a>); an edit that does not fit is dropped and the host logs it. Do not write past <tt class="docutils literal"><span class="pre">len</span></tt>, do not free anything, do not retain a pointer after your proc returns: every pointer the host hands you is valid only for the duration of the call.</p>
<h3 id="steering-tool-calls">Steering tool calls</h3><p><tt class="docutils literal"><span class="pre">onToolPre</span></tt> sees every tool call before execution and returns a verdict:</p>
<p><pre class="listing"><span class="Keyword">proc</span> <span class="Identifier">onToolPre</span><span class="Operator">*</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Punctuation">:</span> <span class="Keyword">var</span> <span class="Identifier">TcToolPreEvent</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Identifier">cint</span> <span class="Operator">=</span>
<span class="Keyword">if</span> <span class="Identifier">tcView</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">name</span><span class="Punctuation">)</span> <span class="Operator">==</span> <span class="StringLit">"write"</span> <span class="Keyword">and</span> <span class="StringLit">"migrations"</span> <span class="Keyword">in</span> <span class="Identifier">tcView</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">args</span><span class="Punctuation">)</span><span class="Punctuation">:</span>
<span class="Identifier">tcAssignStr</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">message</span><span class="Punctuation">,</span> <span class="StringLit">"myplugin: migrations are frozen today"</span><span class="Punctuation">)</span>
<span class="Keyword">return</span> <span class="Identifier">tcVeto</span>
<span class="Identifier">tcAllow</span></pre></p>
<ul class="simple"><li><tt class="docutils literal"><span class="pre">tcAllow</span></tt> (0): proceed unchanged.</li>
<li><tt class="docutils literal"><span class="pre">tcVeto</span></tt> (1): skip the call; <tt class="docutils literal"><span class="pre">message</span></tt> becomes the tool result the model sees.</li>
<li><tt class="docutils literal"><span class="pre">tcRewrite</span></tt> (2): you edited <tt class="docutils literal"><span class="pre">args</span></tt> (JSON text); proceed with the new ones.</li>
<li><tt class="docutils literal"><span class="pre">tcTakeover</span></tt> (3): skip execution; <tt class="docutils literal"><span class="pre">message</span></tt> and <tt class="docutils literal"><span class="pre">code</span></tt> are the whole result. You did the work yourself, which runs <em>outside</em> the sandbox, with your full rights. That is the point, and the risk.</li>
<li><tt class="docutils literal"><span class="pre">tcWrap</span></tt> (4): run the original, sandboxed, with <tt class="docutils literal"><span class="pre">message</span></tt> prepended and <tt class="docutils literal"><span class="pre">post</span></tt> appended to its output. Multiple wraps compose in load order.</li>
</ul>
<p><tt class="docutils literal"><span class="pre">onToolResult</span></tt> fires after a call lands and can edit the output before the model reads it (redaction is the classic use) and even the exit code.</p>
<h3 id="registering-a-modelminusfacing-tool">Registering a model-facing tool</h3><p>Two procs cooperate: one registers, one executes.</p>
<p><pre class="listing"><span class="Keyword">proc</span> <span class="Identifier">registerTools</span><span class="Operator">*</span><span class="Punctuation">(</span><span class="Identifier">s</span><span class="Punctuation">:</span> <span class="Keyword">ptr</span> <span class="Identifier">TcState</span><span class="Punctuation">)</span> <span class="Operator">=</span>
<span class="Keyword">discard</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">registerTool</span><span class="Punctuation">(</span><span class="StringLit">"weather"</span><span class="Punctuation">,</span> <span class="StringLit">"current conditions"</span><span class="Punctuation">,</span>
<span class="LongStringLit">"""{"type":"function","function":{"name":"weather",
"parameters":{"type":"object","properties":{
"city":{"type":"string"}},"required":["city"]}}}"""</span><span class="Punctuation">)</span>
<span class="Keyword">proc</span> <span class="Identifier">onToolExec</span><span class="Operator">*</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Punctuation">:</span> <span class="Keyword">var</span> <span class="Identifier">TcToolExecEvent</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Identifier">int32</span> <span class="Operator">=</span>
<span class="Identifier">tcAssignStr</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">output</span><span class="Punctuation">,</span> <span class="StringLit">"sunny"</span><span class="Punctuation">)</span>
<span class="DecNumber">0</span></pre></p>
<p><tt class="docutils literal"><span class="pre">registerTool</span></tt> is legal only inside <tt class="docutils literal"><span class="pre">registerTools</span></tt>. The schema is an OpenAI function-tool definition; the name must not collide with a builtin tool (<tt class="docutils literal"><span class="pre">bash</span></tt>, <tt class="docutils literal"><span class="pre">read</span></tt>, <tt class="docutils literal"><span class="pre">write</span></tt>, ... check <tt class="docutils literal"><span class="pre">:plugins</span></tt> for rejections) or an already-registered one. The optional last argument is a per-call timeout in milliseconds; 0 means the host default (120 s).</p>
<p>Tools are advertised to the model only when <tt class="docutils literal"><span class="pre">[plugins] tools = "on"</span></tt>, which is deliberately off by default: the tool array is stateless and rides every model request, so every registered schema is billed on every call whether used or not, roughly 300-900 tokens for a small curated one. The gate makes mounting a deliberate choice. Executions run unsandboxed in the plugin, like any plugin code. Drop a skill in <tt class="docutils literal"><span class="pre">~/.config/3code/skills/myplugin.md</span></tt> teaching the model when and how to call the tool; that is the whole install convention.</p>
<h3 id="adding-a-subcommand-or-an-option">Adding a subcommand or an option</h3><p>The same registration pattern reaches the command line. A subcommand makes <tt class="docutils literal"><span class="pre">3code <name> ...</span></tt> yours; an option adds a <tt class="docutils literal"><span class="pre">--flag</span></tt> the main parser accepts and hands to your plugin:</p>
<p><pre class="listing"><span class="Keyword">proc</span> <span class="Identifier">registerCli</span><span class="Operator">*</span><span class="Punctuation">(</span><span class="Identifier">s</span><span class="Punctuation">:</span> <span class="Keyword">ptr</span> <span class="Identifier">TcState</span><span class="Punctuation">)</span> <span class="Operator">=</span>
<span class="Keyword">discard</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">registerCliCommand</span><span class="Punctuation">(</span><span class="StringLit">"deploy"</span><span class="Punctuation">,</span> <span class="StringLit">"run the deploy pipeline"</span><span class="Punctuation">)</span>
<span class="Keyword">discard</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">registerCliOption</span><span class="Punctuation">(</span><span class="StringLit">"deploy-env"</span><span class="Punctuation">,</span> <span class="CharLit">'E'</span><span class="Punctuation">,</span> <span class="StringLit">"target environment"</span><span class="Punctuation">,</span>
<span class="Identifier">takesValue</span> <span class="Operator">=</span> <span class="Identifier">true</span><span class="Punctuation">)</span>
<span class="Keyword">proc</span> <span class="Identifier">onCliCommand</span><span class="Operator">*</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Punctuation">:</span> <span class="Keyword">var</span> <span class="Identifier">TcCliCommandEvent</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Identifier">int32</span> <span class="Operator">=</span>
<span class="Keyword">let</span> <span class="Identifier">args</span> <span class="Operator">=</span> <span class="Identifier">parseJson</span><span class="Punctuation">(</span><span class="Identifier">tcView</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">args</span><span class="Punctuation">)</span><span class="Punctuation">)</span> <span class="Comment"># JSON array, verbatim</span>
<span class="Identifier">tcAssignStr</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">output</span><span class="Punctuation">,</span> <span class="StringLit">"deploying to "</span> <span class="Operator">&</span> <span class="Operator">$</span><span class="Identifier">args</span><span class="Punctuation">)</span>
<span class="DecNumber">0</span>
<span class="Keyword">proc</span> <span class="Identifier">onCliOptions</span><span class="Operator">*</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Punctuation">:</span> <span class="Keyword">var</span> <span class="Identifier">TcCliOptionsEvent</span><span class="Punctuation">)</span> <span class="Operator">=</span>
<span class="Keyword">let</span> <span class="Identifier">opts</span> <span class="Operator">=</span> <span class="Identifier">parseJson</span><span class="Punctuation">(</span><span class="Identifier">tcView</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Operator">.</span><span class="Identifier">options</span><span class="Punctuation">)</span><span class="Punctuation">)</span> <span class="Comment"># JSON object</span>
<span class="Keyword">if</span> <span class="Identifier">opts</span><span class="Operator">.</span><span class="Identifier">hasKey</span><span class="Punctuation">(</span><span class="StringLit">"deploy-env"</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Identifier">target</span> <span class="Operator">=</span> <span class="Identifier">opts</span><span class="Punctuation">[</span><span class="StringLit">"deploy-env"</span><span class="Punctuation">]</span><span class="Operator">.</span><span class="Identifier">getStr</span></pre></p>
<p><tt class="docutils literal"><span class="pre">registerCliCommand</span></tt>/<tt class="docutils literal"><span class="pre">registerCliOption</span></tt> are legal only inside <tt class="docutils literal"><span class="pre">registerCli</span></tt> (which runs at load, before argv is parsed — that is the whole reason plugins now load that early). Names are lowercase <tt class="docutils literal"><span class="pre">a-z0-9-</span></tt>, one word. Anything the built-in CLI already owns is refused: the builtin subcommands (<tt class="docutils literal"><span class="pre">good</span></tt>, <tt class="docutils literal"><span class="pre">provider</span></tt>, <tt class="docutils literal"><span class="pre">sandbox</span></tt>, ...), the builtin option names (<tt class="docutils literal"><span class="pre">--model</span></tt>, <tt class="docutils literal"><span class="pre">--resume</span></tt>, ...) and the builtin short letters (<tt class="docutils literal"><span class="pre">-m</span></tt>, <tt class="docutils literal"><span class="pre">-r</span></tt>, ...), plus your own earlier registrations. Check the bool return or <tt class="docutils literal"><span class="pre">:plugins</span></tt> to see a refusal.</p>
<p>A registered subcommand dispatches when it is the FIRST bare word on the command line; everything after it is yours verbatim (flags, sub-subcommands, <tt class="docutils literal"><span class="pre">--</span></tt>), like <tt class="docutils literal"><span class="pre">3code provider</span></tt> owns its rest. Fill <tt class="docutils literal"><span class="pre">ev.output</span></tt> and return the exit code; the host prints the output and exits with your code. The budget is the tool-exec one (120 s default).</p>
<p>Registered options are accepted wherever builtin options are (<tt class="docutils literal"><span class="pre">--opt value</span></tt>, <tt class="docutils literal"><span class="pre">--opt=value</span></tt>, <tt class="docutils literal"><span class="pre">-Zvalue</span></tt> for a registered short) and collect into a JSON object delivered once to every plugin exporting <tt class="docutils literal"><span class="pre">tc_on_cli_options</span></tt>, before any session work: value options as strings, flags as <tt class="docutils literal"><span class="pre">true</span></tt>. <tt class="docutils literal"><span class="pre">3code -h</span></tt> lists both surfaces in an "added by plugins" block, so your additions are discoverable.</p>
<h3 id="overriding-default-config-values">Overriding default config values</h3><p>The same registration pattern reaches the config file's defaults. A plugin may retune what 3code uses when the user's own config is SILENT on a key — never what the user wrote:</p>
<p><pre class="listing"><span class="Keyword">proc</span> <span class="Identifier">registerConfig</span><span class="Operator">*</span><span class="Punctuation">(</span><span class="Identifier">s</span><span class="Punctuation">:</span> <span class="Keyword">ptr</span> <span class="Identifier">TcState</span><span class="Punctuation">)</span> <span class="Operator">=</span>
<span class="Keyword">discard</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">overrideDefault</span><span class="Punctuation">(</span><span class="StringLit">"settings"</span><span class="Punctuation">,</span> <span class="StringLit">"max_timeout"</span><span class="Punctuation">,</span> <span class="StringLit">"1800"</span><span class="Punctuation">)</span>
<span class="Keyword">discard</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">overrideDefault</span><span class="Punctuation">(</span><span class="StringLit">"settings"</span><span class="Punctuation">,</span> <span class="StringLit">"sandbox_wall_warn"</span><span class="Punctuation">,</span> <span class="StringLit">"off"</span><span class="Punctuation">)</span></pre></p>
<p><tt class="docutils literal"><span class="pre">registerConfig</span></tt> runs once at load, before the config file parses. The precedence ladder is exactly: compiled default < plugin default < the user's config line < a CLI flag. If the user writes <tt class="docutils literal"><span class="pre">max_timeout = 60</span></tt>, the user wins; if they write nothing, yours applies. A plugin that ships a GUI can default <tt class="docutils literal"><span class="pre">notify = "on"</span></tt>, a long-build shop can default <tt class="docutils literal"><span class="pre">max_timeout</span></tt>, a kiosk setup can default <tt class="docutils literal"><span class="pre">tone = "light"</span></tt> — without touching anyone's config file.</p>
<p>Defaultable keys: the booleans (<tt class="docutils literal"><span class="pre">notify</span></tt>, <tt class="docutils literal"><span class="pre">streaming</span></tt>, <tt class="docutils literal"><span class="pre">sandbox</span></tt>, <tt class="docutils literal"><span class="pre">patient_retry</span></tt>, <tt class="docutils literal"><span class="pre">sandbox_wall_warn</span></tt>, <tt class="docutils literal"><span class="pre">browserfetch</span></tt>, <tt class="docutils literal"><span class="pre">allow-empty-prompt</span></tt>, <tt class="docutils literal"><span class="pre">tab-title</span></tt>, <tt class="docutils literal"><span class="pre">computer</span></tt>), the integers (<tt class="docutils literal"><span class="pre">max_timeout</span></tt>, <tt class="docutils literal"><span class="pre">force_timeout</span></tt>, <tt class="docutils literal"><span class="pre">banner_lines</span></tt>), <tt class="docutils literal"><span class="pre">tone</span></tt>/<tt class="docutils literal"><span class="pre">mode</span></tt> (<tt class="docutils literal"><span class="pre">auto|dark|light</span></tt>), and the strings (<tt class="docutils literal"><span class="pre">bash</span></tt>, <tt class="docutils literal"><span class="pre">bash_path</span></tt>, <tt class="docutils literal"><span class="pre">user_agent</span></tt>). Provider selection (<tt class="docutils literal"><span class="pre">current</span></tt>) and provider sections are deliberately NOT defaultable — a plugin picking the user's provider would be a policy bypass, not a default. Values use the same dialect as the config file; refusals (unknown key, bad value) are logged and listed in <tt class="docutils literal"><span class="pre">:plugins</span></tt>, and later registrations win in load order like every other plugin chain.</p>
<h3 id="an-inminusprocess-gui-frontend">An in-process GUI frontend</h3><p><tt class="docutils literal"><span class="pre">--gui</span></tt> is the fourth embedding surface, and the one a plugin owns: the process runs headless (zero terminal output, exactly like <tt class="docutils literal"><span class="pre">--headless</span></tt>) and every plugin exporting <tt class="docutils literal"><span class="pre">tc_frontend</span></tt> gets its own thread to be the user interface — a native window, a webview, anything — while talking to the agent through the <tt class="docutils literal"><span class="pre">agent*</span></tt> services, in-process, no sockets and no second binary:</p>
<p><pre class="listing"><span class="Keyword">include</span> <span class="Identifier">threecode</span><span class="Operator">/</span><span class="Identifier">pluginabi</span>
<span class="Keyword">import</span> <span class="Identifier">std</span><span class="Operator">/</span><span class="Punctuation">[</span><span class="Identifier">json</span><span class="Punctuation">,</span> <span class="Identifier">os</span><span class="Punctuation">,</span> <span class="Identifier">strutils</span><span class="Punctuation">]</span>
<span class="Keyword">proc</span> <span class="Identifier">frontend</span><span class="Operator">*</span><span class="Punctuation">(</span><span class="Identifier">ev</span><span class="Punctuation">:</span> <span class="Keyword">var</span> <span class="Identifier">TcFrontendEvent</span><span class="Punctuation">)</span> <span class="Operator">=</span>
<span class="Comment"># runs on a dedicated host thread; loop here until the GUI quits.</span>
<span class="Comment"># A real frontend runs its event loop and marshals agent events to</span>
<span class="Comment"># its UI thread; this sketch polls.</span>
<span class="Keyword">let</span> <span class="Identifier">s</span> <span class="Operator">=</span> <span class="Identifier">tcCurrentState</span>
<span class="Keyword">if</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">agentOpen</span><span class="Punctuation">(</span><span class="StringLit">"{}"</span><span class="Punctuation">)</span> <span class="Operator">!=</span> <span class="DecNumber">0</span><span class="Punctuation">:</span>
<span class="Keyword">return</span> <span class="Comment"># no provider configured; tell the user your way</span>
<span class="Keyword">discard</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">agentStart</span><span class="Punctuation">(</span><span class="StringLit">"explain this repo"</span><span class="Punctuation">)</span>
<span class="Keyword">while</span> <span class="Identifier">true</span><span class="Punctuation">:</span>
<span class="Keyword">var</span> <span class="Identifier">aev</span><span class="Punctuation">:</span> <span class="Identifier">TcAgentEvent</span>
<span class="Keyword">while</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">agentPollEvent</span><span class="Punctuation">(</span><span class="Identifier">aev</span><span class="Punctuation">)</span> <span class="Operator">==</span> <span class="DecNumber">1</span><span class="Punctuation">:</span>
<span class="Keyword">case</span> <span class="Identifier">aev</span><span class="Operator">.</span><span class="Identifier">kind</span>
<span class="Keyword">of</span> <span class="Identifier">taeDelta</span><span class="Punctuation">:</span> <span class="Identifier">paintText</span><span class="Punctuation">(</span><span class="Identifier">tcView</span><span class="Punctuation">(</span><span class="Identifier">aev</span><span class="Operator">.</span><span class="Identifier">text</span><span class="Punctuation">)</span><span class="Punctuation">)</span>
<span class="Keyword">of</span> <span class="Identifier">taeTool</span><span class="Punctuation">:</span> <span class="Identifier">paintLine</span><span class="Punctuation">(</span><span class="Identifier">tcView</span><span class="Punctuation">(</span><span class="Identifier">aev</span><span class="Operator">.</span><span class="Identifier">text</span><span class="Punctuation">)</span><span class="Punctuation">)</span>
<span class="Keyword">of</span> <span class="Identifier">taeDone</span><span class="Punctuation">:</span> <span class="Identifier">paintUsage</span><span class="Punctuation">(</span><span class="Identifier">aev</span><span class="Operator">.</span><span class="Identifier">promptTokens</span><span class="Punctuation">,</span> <span class="Identifier">aev</span><span class="Operator">.</span><span class="Identifier">completionTokens</span><span class="Punctuation">)</span>
<span class="Keyword">of</span> <span class="Identifier">taeError</span><span class="Punctuation">:</span> <span class="Identifier">paintError</span><span class="Punctuation">(</span><span class="Identifier">tcView</span><span class="Punctuation">(</span><span class="Identifier">aev</span><span class="Operator">.</span><span class="Identifier">text</span><span class="Punctuation">)</span><span class="Punctuation">)</span>
<span class="Keyword">else</span><span class="Punctuation">:</span> <span class="Keyword">discard</span>
<span class="Keyword">if</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">agentBusy</span><span class="Punctuation">(</span><span class="Punctuation">)</span> <span class="Operator">==</span> <span class="DecNumber">0</span> <span class="Keyword">and</span> <span class="Identifier">userClosedWindow</span><span class="Punctuation">(</span><span class="Punctuation">)</span><span class="Punctuation">:</span> <span class="Keyword">break</span>
<span class="Identifier">pollGuiEvents</span><span class="Punctuation">(</span><span class="DecNumber">20</span><span class="Punctuation">)</span> <span class="Comment"># your toolkit's idle/wait</span>
<span class="Keyword">discard</span> <span class="Identifier">s</span><span class="Operator">.</span><span class="Identifier">agentClose</span><span class="Punctuation">(</span><span class="Punctuation">)</span>
<span class="Keyword">include</span> <span class="Identifier">threecode</span><span class="Operator">/</span><span class="Identifier">plugin_sdk</span></pre></p>
<p>The contract in one breath: <tt class="docutils literal"><span class="pre">agentOpen(optsJson)</span></tt> opens the process's one session (<tt class="docutils literal"><span class="pre">{"model", "cwd", "resume", "resumeId", "sessionPath", "experimental"}</span></tt>, all optional); <tt class="docutils literal"><span class="pre">agentStart(prompt)</span></tt> kicks a turn on a host worker thread and returns immediately (empty prompt = continue; 1 if busy); <tt class="docutils literal"><span class="pre">agentBusy()</span></tt>, <tt class="docutils literal"><span class="pre">agentCancel()</span></tt> are what they say; <tt class="docutils literal"><span class="pre">agentCommand(":tokens")</span></tt> runs a colon command into a plugin-allocated <tt class="docutils literal"><span class="pre">TcMutStr</span></tt> (refuses with 1 while a turn runs); <tt class="docutils literal"><span class="pre">agentScrollback()</span></tt> returns the stored conversation as JSON array text (<tt class="docutils literal"><span class="pre">[{"role","content"}]</span></tt>, tools stripped); <tt class="docutils literal"><span class="pre">agentPollEvent</span></tt> pops one event into a caller-owned <tt class="docutils literal"><span class="pre">TcAgentEvent</span></tt> (1 delivered, 0 empty — poll from your loop, <tt class="docutils literal"><span class="pre">text</span></tt> is a view valid only for the call). <tt class="docutils literal"><span class="pre">agentLastErrorStr()</span></tt> explains any nonzero return. All agent services are legal only from <tt class="docutils literal"><span class="pre">frontend</span></tt>'s thread.</p>
<p><tt class="docutils literal"><span class="pre">TcFrontendEvent</span></tt> hands you <tt class="docutils literal"><span class="pre">cwd</span></tt> and <tt class="docutils literal"><span class="pre">argv</span></tt> (the full command line as JSON array text, verbatim — parse what you want). Returning from <tt class="docutils literal"><span class="pre">frontend</span></tt> ends your thread; when every frontend returned, the process saves, shuts down, and exits 0. The host refuses to start (<tt class="docutils literal"><span class="pre">--gui</span></tt> exits 3, silently, like all headless paths) when no plugin exports <tt class="docutils literal"><span class="pre">tc_frontend</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">--headless</span></tt> (no plugin needed) is the same machinery without a frontend: prompt words run as one turn with ZERO output on any stream — no TUI, no banner, no stderr on failure; the exit code is the whole report (0 ok, 1 turn failed/interrupted, 2 usage, 3 config). Flags: <tt class="docutils literal"><span class="pre">-m</span></tt>, <tt class="docutils literal"><span class="pre">-c</span></tt>, <tt class="docutils literal"><span class="pre">-r[=id]</span></tt>, <tt class="docutils literal"><span class="pre">-s</span></tt>, <tt class="docutils literal"><span class="pre">-x</span></tt>, <tt class="docutils literal"><span class="pre">-p</span></tt>, <tt class="docutils literal"><span class="pre">--no-sandbox</span></tt>, <tt class="docutils literal"><span class="pre">-D</span></tt>.</p>
<h4 id="the-native-windows-gui-build">The native Windows GUI build</h4><p><tt class="docutils literal"><span class="pre">nimble gui</span></tt> builds <tt class="docutils literal"><span class="pre">bin/3code-gui</span></tt> with <tt class="docutils literal"><span class="pre">--app:gui -d:tcNativeGui</span></tt>: a Windows GUI-subsystem binary (WinMain, no console attached — double-clicking opens no terminal), a framework-linked binary on macOS, the console build on Linux. <tt class="docutils literal"><span class="pre">-d:tcNativeGui</span></tt> makes the runtime refuse everything except <tt class="docutils literal"><span class="pre">--headless</span></tt>/<tt class="docutils literal"><span class="pre">--gui</span></tt>: without a console, a terminal-UI run would be blind, so the binary alerts (a real MessageBox on Windows, stderr elsewhere) and exits 2 instead. Ship it beside the console binary: <tt class="docutils literal"><span class="pre">3code-gui --gui</span></tt> with a frontend plugin installed IS the native app; the model, config, sandbox, sessions, and plugins are all the same, in one process.</p>
<h3 id="long-work-and-interruption">Long work and interruption</h3><p>A sync hook that runs long gets its default outcome applied without it (see <a class="reference external" href="#failure-handling">failure handling</a>). Poll <tt class="docutils literal"><span class="pre">tcCancelled(tcCurrentState)</span></tt> in any loop that might outlive its budget, including tool execs (Esc during a turn sets the flag):</p>
<p><pre class="listing"><span class="Keyword">while</span> <span class="Identifier">moreWork</span><span class="Punctuation">(</span><span class="Punctuation">)</span> <span class="Keyword">and</span> <span class="Keyword">not</span> <span class="Identifier">tcCancelled</span><span class="Punctuation">(</span><span class="Identifier">tcCurrentState</span><span class="Punctuation">)</span><span class="Punctuation">:</span>
<span class="Identifier">doChunk</span><span class="Punctuation">(</span><span class="Punctuation">)</span></pre></p>
<h3 id="beyond-nim">Beyond Nim</h3><p>The ABI is plain C. A plugin in C, Rust (<tt class="docutils literal"><span class="pre">extern "C"</span></tt>), Zig, or anything else just exports the <tt class="docutils literal"><span class="pre">tc_*</span></tt> symbols itself, honors <tt class="docutils literal"><span class="pre">abi</span></tt>/<tt class="docutils literal"><span class="pre">structSize</span></tt> (treat a larger host struct as trailing unknown bytes; refuse nothing except a <tt class="docutils literal"><span class="pre">structSize</span></tt> smaller than yours), and keeps the memory rules above. The fixture in <tt class="docutils literal"><span class="pre">tests/testdata/plugin_fixture.nim</span></tt> in the 3code repo is the canonical worked example of every hook, heavily commented.</p>
<h2 id="hook-reference">Hook reference</h2><table border="1" class="docutils"><tr><th>export</th><th>Nim proc</th><th>budget</th><th>fires</th></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_abi_version()</span></tt></td><td>-</td><td>-</td><td>probed at load; must equal the host version exactly</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_init(s)</span></tt></td><td><tt class="docutils literal"><span class="pre">init(s): cint</span></tt></td><td>2 s</td><td>once after load, before any hook; return 0</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_register_tools(s)</span></tt></td><td><tt class="docutils literal"><span class="pre">registerTools(s)</span></tt></td><td>2 s</td><td>once after init</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_register_cli(s)</span></tt></td><td><tt class="docutils literal"><span class="pre">registerCli(s)</span></tt></td><td>2 s</td><td>once after init, before argv is parsed</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_register_config(s)</span></tt></td><td><tt class="docutils literal"><span class="pre">registerConfig(s)</span></tt></td><td>2 s</td><td>once after init, before the config parses</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_frontend(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">frontend(ev: var TcFrontendEvent)</span></tt></td><td>yours</td><td><tt class="docutils literal"><span class="pre">3code --gui</span></tt>: run the GUI, drive the agent, return when it quits</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_shutdown(s)</span></tt></td><td><tt class="docutils literal"><span class="pre">shutdown(s)</span></tt></td><td>-</td><td>at process exit, before unload</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_prompt(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onPrompt(ev: var TcPromptEvent)</span></tt></td><td>2 s</td><td>user submits a prompt</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_system_prompt(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onSystemPrompt(ev: var TcSysPromptEvent)</span></tt></td><td>2 s</td><td>once per provider/model/family (memoized), then cached</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_tool_pre(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onToolPre(ev: var TcToolPreEvent): cint</span></tt></td><td>2 s</td><td>before each tool call</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_tool_result(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onToolResult(ev: var TcToolResultEvent)</span></tt></td><td>2 s</td><td>after each tool call</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_tool_exec(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onToolExec(ev: var TcToolExecEvent): int32</span></tt></td><td>declared, default 120 s</td><td>the model calls a registered tool</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_turn_start(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onTurnStart(ev: var TcTurnEvent)</span></tt></td><td>async</td><td>a turn begins</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_turn_end(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onTurnEnd(ev: var TcTurnEndEvent)</span></tt></td><td>async</td><td>a turn ends (usage, elapsed)</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_model_retry(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onModelRetry(ev: var TcRetryEvent)</span></tt></td><td>async</td><td>provider error enters backoff</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_session_start(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onSessionStart(ev: var TcSessionEvent)</span></tt></td><td>async</td><td>a session loads</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_compact(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onCompact(ev: var TcCompactEvent)</span></tt></td><td>async</td><td>history gets summarized</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_file_write(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onFileWrite(ev: var TcFileWriteEvent)</span></tt></td><td>async</td><td>write/patch/apply_patch landed</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_cli_command(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onCliCommand(ev: var TcCliCommandEvent): int32</span></tt></td><td>120 s default</td><td>the user ran <tt class="docutils literal"><span class="pre">3code <your-subcommand> ...</span></tt></td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tc_on_cli_options(s, ev)</span></tt></td><td><tt class="docutils literal"><span class="pre">onCliOptions(ev: var TcCliOptionsEvent)</span></tt></td><td>2 s</td><td>after argv parse, once, when any registered option was given</td></tr>
</table><p>Async means fire-and-forget: the host copies a small POD event into a bounded queue (256 entries, oldest dropped under pressure) and moves on. Do not mutate async events as if the host were waiting; it is not.</p>
<p>Event structs. <tt class="docutils literal"><span class="pre">TcStr</span></tt> fields are read-only views; <tt class="docutils literal"><span class="pre">TcMutStr</span></tt> fields may be edited in place. Every struct also carries <tt class="docutils literal"><span class="pre">abi</span></tt> and <tt class="docutils literal"><span class="pre">structSize</span></tt> first.</p>
<p><strong>TcPromptEvent</strong>: <tt class="docutils literal"><span class="pre">prompt</span></tt> (mut, 1 MiB), <tt class="docutils literal"><span class="pre">cwd</span></tt>, <tt class="docutils literal"><span class="pre">sessionPath</span></tt>, <tt class="docutils literal"><span class="pre">provider</span></tt>, <tt class="docutils literal"><span class="pre">model</span></tt>.</p>
<p><strong>TcSysPromptEvent</strong>: <tt class="docutils literal"><span class="pre">prompt</span></tt> (mut, 512 KiB), <tt class="docutils literal"><span class="pre">provider</span></tt>, <tt class="docutils literal"><span class="pre">model</span></tt>, <tt class="docutils literal"><span class="pre">family</span></tt>. The result is cached per (provider, model, family) for the process lifetime.</p>
<p><strong>TcToolPreEvent</strong>: <tt class="docutils literal"><span class="pre">name</span></tt>, <tt class="docutils literal"><span class="pre">callId</span></tt>, <tt class="docutils literal"><span class="pre">family</span></tt>; <tt class="docutils literal"><span class="pre">args</span></tt> (mut, 256 KiB, JSON text of the tool arguments); out fields <tt class="docutils literal"><span class="pre">verdict</span></tt>, <tt class="docutils literal"><span class="pre">message</span></tt> (4 KiB), <tt class="docutils literal"><span class="pre">post</span></tt> (4 KiB), <tt class="docutils literal"><span class="pre">code</span></tt>. Set the verdict by returning it.</p>
<p><strong>TcToolResultEvent</strong>: <tt class="docutils literal"><span class="pre">name</span></tt>, <tt class="docutils literal"><span class="pre">args</span></tt>, <tt class="docutils literal"><span class="pre">elapsedMs</span></tt>, <tt class="docutils literal"><span class="pre">diff</span></tt> (the bash-style diff when a tool produced one); <tt class="docutils literal"><span class="pre">output</span></tt> (mut, 1 MiB) and <tt class="docutils literal"><span class="pre">code</span></tt> (pointer, editable) shape what the model sees.</p>
<p><strong>TcToolExecEvent</strong>: <tt class="docutils literal"><span class="pre">name</span></tt>, <tt class="docutils literal"><span class="pre">args</span></tt>; out fields <tt class="docutils literal"><span class="pre">output</span></tt> (mut, 1 MiB) and <tt class="docutils literal"><span class="pre">code</span></tt>. Your whole job: fill <tt class="docutils literal"><span class="pre">output</span></tt>, return the exit code as <tt class="docutils literal"><span class="pre">ev.code</span></tt> (the proc's return value).</p>
<p><strong>TcTurnEvent</strong>: <tt class="docutils literal"><span class="pre">turn</span></tt>, <tt class="docutils literal"><span class="pre">promptTokens</span></tt>, <tt class="docutils literal"><span class="pre">cwd</span></tt>.</p>
<p><strong>TcTurnEndEvent</strong>: <tt class="docutils literal"><span class="pre">turn</span></tt>, <tt class="docutils literal"><span class="pre">promptTokens</span></tt>, <tt class="docutils literal"><span class="pre">completionTokens</span></tt>, <tt class="docutils literal"><span class="pre">reasoningTokens</span></tt>, <tt class="docutils literal"><span class="pre">elapsedMs</span></tt>, <tt class="docutils literal"><span class="pre">interrupted</span></tt>, <tt class="docutils literal"><span class="pre">sessionPath</span></tt>.</p>
<p><strong>TcRetryEvent</strong>: <tt class="docutils literal"><span class="pre">provider</span></tt>, <tt class="docutils literal"><span class="pre">model</span></tt>, <tt class="docutils literal"><span class="pre">status</span></tt> (HTTP status or 0), <tt class="docutils literal"><span class="pre">category</span></tt>, <tt class="docutils literal"><span class="pre">backoffS</span></tt>, <tt class="docutils literal"><span class="pre">attempt</span></tt>.</p>
<p><strong>TcSessionEvent</strong>: <tt class="docutils literal"><span class="pre">sessionPath</span></tt>, <tt class="docutils literal"><span class="pre">cwd</span></tt>, <tt class="docutils literal"><span class="pre">provider</span></tt>, <tt class="docutils literal"><span class="pre">model</span></tt>, <tt class="docutils literal"><span class="pre">resumed</span></tt>, <tt class="docutils literal"><span class="pre">messages</span></tt>.</p>
<p><strong>TcCompactEvent</strong>: <tt class="docutils literal"><span class="pre">before</span></tt>, <tt class="docutils literal"><span class="pre">after</span></tt> (message counts), <tt class="docutils literal"><span class="pre">summary</span></tt>.</p>
<p><strong>TcFileWriteEvent</strong>: <tt class="docutils literal"><span class="pre">path</span></tt> (project-relative when possible), <tt class="docutils literal"><span class="pre">bytes</span></tt>, <tt class="docutils literal"><span class="pre">kind</span></tt> (0 write, 1 patch, 2 apply_patch).</p>
<p><strong>TcCliCommandEvent</strong>: <tt class="docutils literal"><span class="pre">name</span></tt>; <tt class="docutils literal"><span class="pre">args</span></tt> is the JSON array text of the arguments that followed the subcommand, verbatim. Out fields: <tt class="docutils literal"><span class="pre">output</span></tt> (mut, 1 MiB) and <tt class="docutils literal"><span class="pre">code</span></tt>. Set <tt class="docutils literal"><span class="pre">code</span></tt> by returning it.</p>
<p><strong>TcCliOptionsEvent</strong>: <tt class="docutils literal"><span class="pre">options</span></tt>, the JSON object text of the options collected from argv (<tt class="docutils literal"><span class="pre">{"deploy-env": "prod", "verbose": true}</span></tt>). Read-only.</p>
<p><strong>TcFrontendEvent</strong>: <tt class="docutils literal"><span class="pre">cwd</span></tt>, <tt class="docutils literal"><span class="pre">argv</span></tt> (JSON array text of the whole command line, verbatim). Read-only; yours until <tt class="docutils literal"><span class="pre">frontend</span></tt> returns.</p>
<p><strong>TcAgentEvent</strong> (filled by <tt class="docutils literal"><span class="pre">agentPollEvent</span></tt>): <tt class="docutils literal"><span class="pre">kind</span></tt> (one of the <tt class="docutils literal"><span class="pre">tae*</span></tt> kinds: user, delta, reasoning, tool, retry, notice, done, error), <tt class="docutils literal"><span class="pre">text</span></tt>, and on <tt class="docutils literal"><span class="pre">taeDone</span></tt> the usage fields <tt class="docutils literal"><span class="pre">promptTokens</span></tt>, <tt class="docutils literal"><span class="pre">completionTokens</span></tt>, <tt class="docutils literal"><span class="pre">reasoningTokens</span></tt>, <tt class="docutils literal"><span class="pre">elapsedMs</span></tt>. <tt class="docutils literal"><span class="pre">text</span></tt> is a view valid only for the poll call.</p>
<h2 id="strings-and-buffers">Strings and buffers</h2><p><tt class="docutils literal"><span class="pre">TcStr</span></tt> is a read-only <tt class="docutils literal"><span class="pre">data</span></tt>+<tt class="docutils literal"><span class="pre">len</span></tt> view into host memory, not NUL-terminated. <tt class="docutils literal"><span class="pre">TcMutStr</span></tt> is a host-allocated buffer with <tt class="docutils literal"><span class="pre">len <= cap</span></tt> at all times. <tt class="docutils literal"><span class="pre">tcView</span></tt> copies a view into a Nim string (the only allocating conversion; call it when you need the bytes), <tt class="docutils literal"><span class="pre">tcAssignStr</span></tt> copies your bytes back, silently doing nothing when they do not fit <tt class="docutils literal"><span class="pre">cap</span></tt> (the host logs the drop).</p>
<p>The host sizes each editable buffer at twice the payload, floored at 16 KiB, capped per field: prompt 1 MiB, system prompt 512 KiB, tool args 256 KiB, tool result and tool-exec output 1 MiB, tool-pre message/post 4 KiB. A payload already over its cap skips the hook entirely rather than truncating silently; the debug trace shows the skip. Ordinary edits always fit.</p>
<h2 id="state-services-cancellation">State, services, cancellation</h2><p><tt class="docutils literal"><span class="pre">TcState</span></tt> is the per-plugin context the host passes as the first argument everywhere. It is stable for the process lifetime, so a pointer stashed in <tt class="docutils literal"><span class="pre">userData</span></tt> survives between calls. Fields: <tt class="docutils literal"><span class="pre">abi</span></tt>, <tt class="docutils literal"><span class="pre">structSize</span></tt>, <tt class="docutils literal"><span class="pre">pluginName</span></tt>, <tt class="docutils literal"><span class="pre">userData</span></tt>, <tt class="docutils literal"><span class="pre">cancelled</span></tt> (set to 1 by the host when the user interrupts while your call is in flight), and <tt class="docutils literal"><span class="pre">services</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">TcServices</span></tt> are host callables:</p>
<ul class="simple"><li><tt class="docutils literal"><span class="pre">log(msg)</span></tt>: append to the debug trace, tagged with your plugin name. Safe from any hook.</li>
<li><tt class="docutils literal"><span class="pre">registerTool(name, description, schemaJson, timeoutMs)</span></tt>: legal only inside <tt class="docutils literal"><span class="pre">registerTools</span></tt>. Returns 0 on success, 1 outside registration, 2 for an empty name, 3 for a builtin tool name, 4 for a duplicate. The Nim-side <tt class="docutils literal"><span class="pre">s.registerTool(...)</span></tt> wrapper returns a bool.</li>
<li><tt class="docutils literal"><span class="pre">registerCliCommand(name, help)</span></tt>: legal only inside <tt class="docutils literal"><span class="pre">registerCli</span></tt>. Adds a <tt class="docutils literal"><span class="pre">3code <name></span></tt> subcommand. Same return-code scheme; 3 means a builtin subcommand owns that name, 4 a plugin already registered it.</li>
<li><tt class="docutils literal"><span class="pre">registerCliOption(longName, shortName, help, takesValue)</span></tt>: legal only inside <tt class="docutils literal"><span class="pre">registerCli</span></tt>. Adds a <tt class="docutils literal"><span class="pre">--longName</span></tt> option and, when <tt class="docutils literal"><span class="pre">shortName</span></tt> is a non-empty string, a <tt class="docutils literal"><span class="pre">-x</span></tt> short form. 3 covers a builtin long name or short letter, 2 a bad name.</li>
<li><tt class="docutils literal"><span class="pre">overrideDefault(section, key, value)</span></tt>: legal only inside <tt class="docutils literal"><span class="pre">registerConfig</span></tt>. Sets the default of a <tt class="docutils literal"><span class="pre">[settings]</span></tt> key (see <a class="reference external" href="#overriding-default-config-values">overriding default config values</a>). 0 ok, 1 outside registration, 2 for a key plugins cannot default (or a non-settings section), 3 for a bad value.</li>
<li>the agent services (<tt class="docutils literal"><span class="pre">agentOpen</span></tt>, <tt class="docutils literal"><span class="pre">agentClose</span></tt>, <tt class="docutils literal"><span class="pre">agentStart</span></tt>, <tt class="docutils literal"><span class="pre">agentCancel</span></tt>, <tt class="docutils literal"><span class="pre">agentBusy</span></tt>, <tt class="docutils literal"><span class="pre">agentCommand</span></tt>, <tt class="docutils literal"><span class="pre">agentScrollback</span></tt>, <tt class="docutils literal"><span class="pre">agentPollEvent</span></tt>, <tt class="docutils literal"><span class="pre">agentLastError</span></tt>): legal only from <tt class="docutils literal"><span class="pre">frontend</span></tt>'s thread. See <a class="reference external" href="#an-in-process-gui-frontend">an in-process GUI frontend</a> for the full contract; the Nim-side wrappers are the <tt class="docutils literal"><span class="pre">s.agent*</span></tt> conveniences, plus <tt class="docutils literal"><span class="pre">agentLastErrorStr</span></tt> for a copy of the message.</li>
</ul>
<p>The SDK keeps the current call's state pointer in the threadvar <tt class="docutils literal"><span class="pre">tcCurrentState</span></tt>; <tt class="docutils literal"><span class="pre">tcCancelled(tcCurrentState)</span></tt> is the polite way to poll for interruption.</p>
<h2 id="failure-handling">Failure handling</h2><p>A sync hook has a deadline (2 s, or the tool-exec budget; the <tt class="docutils literal"><span class="pre">[plugins]</span></tt> keys <tt class="docutils literal"><span class="pre">sync_ms</span></tt> and <tt class="docutils literal"><span class="pre">tool_ms</span></tt> retune them). On timeout the default outcome applies without you: allow for verdicts, the original text for prompts and outputs, an error result for a plugin tool. The plugin takes a strike, the host flags <tt class="docutils literal"><span class="pre">cancelled</span></tt> so a well-behaved hook winds down, and three strikes demote the plugin: its sync hooks are skipped for the rest of the session (<tt class="docutils literal"><span class="pre">:plugins</span></tt> shows DEMOTED). A Nim exception in a hook is caught and traced; a segfault takes the process down. There is no process isolation in this tier, which is why the lib directories are yours, not the model's.</p>
<h2 id="config-and-debug">Config and debug</h2><table border="1" class="docutils"><tr><th>key</th><th>effect</th></tr>
<tr><td><tt class="docutils literal"><span class="pre">disable = "slow, other"</span></tt></td><td>skip plugins by lib file stem</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">tools = "on"</span></tt></td><td>advertise registered tools to the model (opt-in)</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">debug = "on"</span></tt></td><td>per-call trace with mutation diffs</td></tr>
<tr><td><tt class="docutils literal"><span class="pre">lib = "/path"</span></tt></td><td>extra discovery dir, scanned first</td></tr>
</table><p><tt class="docutils literal"><span class="pre">:plugins</span></tt> (or <tt class="docutils literal"><span class="pre">:plugin list</span></tt>) reports loaded libraries, subscribed hooks, call counts, strikes, registered tools, and every load-time skip with its reason. <tt class="docutils literal"><span class="pre">:plugin debug on</span></tt> traces every call to the <tt class="docutils literal"><span class="pre">[settings] debug_log</span></tt> path (or stderr): the hook, the plugin, elapsed milliseconds, verdicts, and a line diff of anything a plugin mutated, which is the fastest way to see your plugin actually doing something.</p>
<h2 id="abi-stability">ABI stability</h2><p>The ABI version is 1 and must match exactly; a mismatched library is skipped, never shimmed. Additive changes (trailing struct fields) bump nothing: <tt class="docutils literal"><span class="pre">structSize</span></tt> negotiation absorbs them, and both sides treat a larger counterpart struct as unknown trailing bytes. Any incompatible layout or signature change bumps <tt class="docutils literal"><span class="pre">TcAbiVersion</span></tt>, and old plugins are refused loudly at load rather than corrupting memory quietly.</p>
<p><tt class="docutils literal"><span class="pre">TcServices</span></tt> has no size field, so a slot added to it later (the CLI registration calls above) is safe only for old-plugin-on-new-host; a plugin calling a service slot the running host never had reads past its allocation. Keep the pluginabi you compile against no newer than the 3code that will load you. </p>
</div>
</div>
<div class="twelve-columns footer">
<span class="nim-sprite"></span>
<br>
<small style="color: var(--hint);">Made with Nim. Generated: 2026-11-25 09:49:48 UTC</small>
</div>
</div>
</div>
</body>
</html>