repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

track pi skill files

13e45ae53c210642c0c3cd7cb6025ea051ef9c3c

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (12)

pi/agent/skills/pi

Deleted
deleted file mode 120000
1 -../../../../../.agents/skills/pi

pi/agent/skills/pi/LICENSE.md

Added
new file mode 100644
1 +# GNU GENERAL PUBLIC LICENSE
3 +Version 3, 29 June 2007
5 +Copyright (C) 2007 Free Software Foundation, Inc.
6 +<https://fsf.org/>
8 +Everyone is permitted to copy and distribute verbatim copies of this
9 +license document, but changing it is not allowed.
11 +## Preamble
13 +The GNU General Public License is a free, copyleft license for
14 +software and other kinds of works.
16 +The licenses for most software and other practical works are designed
17 +to take away your freedom to share and change the works. By contrast,
18 +the GNU General Public License is intended to guarantee your freedom
19 +to share and change all versions of a program--to make sure it remains
20 +free software for all its users. We, the Free Software Foundation, use
21 +the GNU General Public License for most of our software; it applies
22 +also to any other work released this way by its authors. You can apply
23 +it to your programs, too.
25 +When we speak of free software, we are referring to freedom, not
26 +price. Our General Public Licenses are designed to make sure that you
27 +have the freedom to distribute copies of free software (and charge for
28 +them if you wish), that you receive source code or can get it if you
29 +want it, that you can change the software or use pieces of it in new
30 +free programs, and that you know you can do these things.
32 +To protect your rights, we need to prevent others from denying you
33 +these rights or asking you to surrender the rights. Therefore, you
34 +have certain responsibilities if you distribute copies of the
35 +software, or if you modify it: responsibilities to respect the freedom
36 +of others.
38 +For example, if you distribute copies of such a program, whether
39 +gratis or for a fee, you must pass on to the recipients the same
40 +freedoms that you received. You must make sure that they, too, receive
41 +or can get the source code. And you must show them these terms so they
42 +know their rights.
44 +Developers that use the GNU GPL protect your rights with two steps:
45 +(1) assert copyright on the software, and (2) offer you this License
46 +giving you legal permission to copy, distribute and/or modify it.
48 +For the developers' and authors' protection, the GPL clearly explains
49 +that there is no warranty for this free software. For both users' and
50 +authors' sake, the GPL requires that modified versions be marked as
51 +changed, so that their problems will not be attributed erroneously to
52 +authors of previous versions.
54 +Some devices are designed to deny users access to install or run
55 +modified versions of the software inside them, although the
56 +manufacturer can do so. This is fundamentally incompatible with the
57 +aim of protecting users' freedom to change the software. The
58 +systematic pattern of such abuse occurs in the area of products for
59 +individuals to use, which is precisely where it is most unacceptable.
60 +Therefore, we have designed this version of the GPL to prohibit the
61 +practice for those products. If such problems arise substantially in
62 +other domains, we stand ready to extend this provision to those
63 +domains in future versions of the GPL, as needed to protect the
64 +freedom of users.
66 +Finally, every program is threatened constantly by software patents.
67 +States should not allow patents to restrict development and use of
68 +software on general-purpose computers, but in those that do, we wish
69 +to avoid the special danger that patents applied to a free program
70 +could make it effectively proprietary. To prevent this, the GPL
71 +assures that patents cannot be used to render the program non-free.
73 +The precise terms and conditions for copying, distribution and
74 +modification follow.
76 +## TERMS AND CONDITIONS
78 +### 0. Definitions.
80 +"This License" refers to version 3 of the GNU General Public License.
82 +"Copyright" also means copyright-like laws that apply to other kinds
83 +of works, such as semiconductor masks.
85 +"The Program" refers to any copyrightable work licensed under this
86 +License. Each licensee is addressed as "you". "Licensees" and
87 +"recipients" may be individuals or organizations.
89 +To "modify" a work means to copy from or adapt all or part of the work
90 +in a fashion requiring copyright permission, other than the making of
91 +an exact copy. The resulting work is called a "modified version" of
92 +the earlier work or a work "based on" the earlier work.
94 +A "covered work" means either the unmodified Program or a work based
95 +on the Program.
97 +To "propagate" a work means to do anything with it that, without
98 +permission, would make you directly or secondarily liable for
99 +infringement under applicable copyright law, except executing it on a
100 +computer or modifying a private copy. Propagation includes copying,
101 +distribution (with or without modification), making available to the
102 +public, and in some countries other activities as well.
104 +To "convey" a work means any kind of propagation that enables other
105 +parties to make or receive copies. Mere interaction with a user
106 +through a computer network, with no transfer of a copy, is not
107 +conveying.
109 +An interactive user interface displays "Appropriate Legal Notices" to
110 +the extent that it includes a convenient and prominently visible
111 +feature that (1) displays an appropriate copyright notice, and (2)
112 +tells the user that there is no warranty for the work (except to the
113 +extent that warranties are provided), that licensees may convey the
114 +work under this License, and how to view a copy of this License. If
115 +the interface presents a list of user commands or options, such as a
116 +menu, a prominent item in the list meets this criterion.
118 +### 1. Source Code.
120 +The "source code" for a work means the preferred form of the work for
121 +making modifications to it. "Object code" means any non-source form of
122 +a work.
124 +A "Standard Interface" means an interface that either is an official
125 +standard defined by a recognized standards body, or, in the case of
126 +interfaces specified for a particular programming language, one that
127 +is widely used among developers working in that language.
129 +The "System Libraries" of an executable work include anything, other
130 +than the work as a whole, that (a) is included in the normal form of
131 +packaging a Major Component, but which is not part of that Major
132 +Component, and (b) serves only to enable use of the work with that
133 +Major Component, or to implement a Standard Interface for which an
134 +implementation is available to the public in source code form. A
135 +"Major Component", in this context, means a major essential component
136 +(kernel, window system, and so on) of the specific operating system
137 +(if any) on which the executable work runs, or a compiler used to
138 +produce the work, or an object code interpreter used to run it.
140 +The "Corresponding Source" for a work in object code form means all
141 +the source code needed to generate, install, and (for an executable
142 +work) run the object code and to modify the work, including scripts to
143 +control those activities. However, it does not include the work's
144 +System Libraries, or general-purpose tools or generally available free
145 +programs which are used unmodified in performing those activities but
146 +which are not part of the work. For example, Corresponding Source
147 +includes interface definition files associated with source files for
148 +the work, and the source code for shared libraries and dynamically
149 +linked subprograms that the work is specifically designed to require,
150 +such as by intimate data communication or control flow between those
151 +subprograms and other parts of the work.
153 +The Corresponding Source need not include anything that users can
154 +regenerate automatically from other parts of the Corresponding Source.
156 +The Corresponding Source for a work in source code form is that same
157 +work.
159 +### 2. Basic Permissions.
161 +All rights granted under this License are granted for the term of
162 +copyright on the Program, and are irrevocable provided the stated
163 +conditions are met. This License explicitly affirms your unlimited
164 +permission to run the unmodified Program. The output from running a
165 +covered work is covered by this License only if the output, given its
166 +content, constitutes a covered work. This License acknowledges your
167 +rights of fair use or other equivalent, as provided by copyright law.
169 +You may make, run and propagate covered works that you do not convey,
170 +without conditions so long as your license otherwise remains in force.
171 +You may convey covered works to others for the sole purpose of having
172 +them make modifications exclusively for you, or provide you with
173 +facilities for running those works, provided that you comply with the
174 +terms of this License in conveying all material for which you do not
175 +control copyright. Those thus making or running the covered works for
176 +you must do so exclusively on your behalf, under your direction and
177 +control, on terms that prohibit them from making any copies of your
178 +copyrighted material outside their relationship with you.
180 +Conveying under any other circumstances is permitted solely under the
181 +conditions stated below. Sublicensing is not allowed; section 10 makes
182 +it unnecessary.
184 +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
186 +No covered work shall be deemed part of an effective technological
187 +measure under any applicable law fulfilling obligations under article
188 +11 of the WIPO copyright treaty adopted on 20 December 1996, or
189 +similar laws prohibiting or restricting circumvention of such
190 +measures.
192 +When you convey a covered work, you waive any legal power to forbid
193 +circumvention of technological measures to the extent such
194 +circumvention is effected by exercising rights under this License with
195 +respect to the covered work, and you disclaim any intention to limit
196 +operation or modification of the work as a means of enforcing, against
197 +the work's users, your or third parties' legal rights to forbid
198 +circumvention of technological measures.
200 +### 4. Conveying Verbatim Copies.
202 +You may convey verbatim copies of the Program's source code as you
203 +receive it, in any medium, provided that you conspicuously and
204 +appropriately publish on each copy an appropriate copyright notice;
205 +keep intact all notices stating that this License and any
206 +non-permissive terms added in accord with section 7 apply to the code;
207 +keep intact all notices of the absence of any warranty; and give all
208 +recipients a copy of this License along with the Program.
210 +You may charge any price or no price for each copy that you convey,
211 +and you may offer support or warranty protection for a fee.
213 +### 5. Conveying Modified Source Versions.
215 +You may convey a work based on the Program, or the modifications to
216 +produce it from the Program, in the form of source code under the
217 +terms of section 4, provided that you also meet all of these
218 +conditions:
220 +- a) The work must carry prominent notices stating that you modified
221 + it, and giving a relevant date.
222 +- b) The work must carry prominent notices stating that it is
223 + released under this License and any conditions added under
224 + section 7. This requirement modifies the requirement in section 4
225 + to "keep intact all notices".
226 +- c) You must license the entire work, as a whole, under this
227 + License to anyone who comes into possession of a copy. This
228 + License will therefore apply, along with any applicable section 7
229 + additional terms, to the whole of the work, and all its parts,
230 + regardless of how they are packaged. This License gives no
231 + permission to license the work in any other way, but it does not
232 + invalidate such permission if you have separately received it.
233 +- d) If the work has interactive user interfaces, each must display
234 + Appropriate Legal Notices; however, if the Program has interactive
235 + interfaces that do not display Appropriate Legal Notices, your
236 + work need not make them do so.
238 +A compilation of a covered work with other separate and independent
239 +works, which are not by their nature extensions of the covered work,
240 +and which are not combined with it such as to form a larger program,
241 +in or on a volume of a storage or distribution medium, is called an
242 +"aggregate" if the compilation and its resulting copyright are not
243 +used to limit the access or legal rights of the compilation's users
244 +beyond what the individual works permit. Inclusion of a covered work
245 +in an aggregate does not cause this License to apply to the other
246 +parts of the aggregate.
248 +### 6. Conveying Non-Source Forms.
250 +You may convey a covered work in object code form under the terms of
251 +sections 4 and 5, provided that you also convey the machine-readable
252 +Corresponding Source under the terms of this License, in one of these
253 +ways:
255 +- a) Convey the object code in, or embodied in, a physical product
256 + (including a physical distribution medium), accompanied by the
257 + Corresponding Source fixed on a durable physical medium
258 + customarily used for software interchange.
259 +- b) Convey the object code in, or embodied in, a physical product
260 + (including a physical distribution medium), accompanied by a
261 + written offer, valid for at least three years and valid for as
262 + long as you offer spare parts or customer support for that product
263 + model, to give anyone who possesses the object code either (1) a
264 + copy of the Corresponding Source for all the software in the
265 + product that is covered by this License, on a durable physical
266 + medium customarily used for software interchange, for a price no
267 + more than your reasonable cost of physically performing this
268 + conveying of source, or (2) access to copy the Corresponding
269 + Source from a network server at no charge.
270 +- c) Convey individual copies of the object code with a copy of the
271 + written offer to provide the Corresponding Source. This
272 + alternative is allowed only occasionally and noncommercially, and
273 + only if you received the object code with such an offer, in accord
274 + with subsection 6b.
275 +- d) Convey the object code by offering access from a designated
276 + place (gratis or for a charge), and offer equivalent access to the
277 + Corresponding Source in the same way through the same place at no
278 + further charge. You need not require recipients to copy the
279 + Corresponding Source along with the object code. If the place to
280 + copy the object code is a network server, the Corresponding Source
281 + may be on a different server (operated by you or a third party)
282 + that supports equivalent copying facilities, provided you maintain
283 + clear directions next to the object code saying where to find the
284 + Corresponding Source. Regardless of what server hosts the
285 + Corresponding Source, you remain obligated to ensure that it is
286 + available for as long as needed to satisfy these requirements.
287 +- e) Convey the object code using peer-to-peer transmission,
288 + provided you inform other peers where the object code and
289 + Corresponding Source of the work are being offered to the general
290 + public at no charge under subsection 6d.
292 +A separable portion of the object code, whose source code is excluded
293 +from the Corresponding Source as a System Library, need not be
294 +included in conveying the object code work.
296 +A "User Product" is either (1) a "consumer product", which means any
297 +tangible personal property which is normally used for personal,
298 +family, or household purposes, or (2) anything designed or sold for
299 +incorporation into a dwelling. In determining whether a product is a
300 +consumer product, doubtful cases shall be resolved in favor of
301 +coverage. For a particular product received by a particular user,
302 +"normally used" refers to a typical or common use of that class of
303 +product, regardless of the status of the particular user or of the way
304 +in which the particular user actually uses, or expects or is expected
305 +to use, the product. A product is a consumer product regardless of
306 +whether the product has substantial commercial, industrial or
307 +non-consumer uses, unless such uses represent the only significant
308 +mode of use of the product.
310 +"Installation Information" for a User Product means any methods,
311 +procedures, authorization keys, or other information required to
312 +install and execute modified versions of a covered work in that User
313 +Product from a modified version of its Corresponding Source. The
314 +information must suffice to ensure that the continued functioning of
315 +the modified object code is in no case prevented or interfered with
316 +solely because modification has been made.
318 +If you convey an object code work under this section in, or with, or
319 +specifically for use in, a User Product, and the conveying occurs as
320 +part of a transaction in which the right of possession and use of the
321 +User Product is transferred to the recipient in perpetuity or for a
322 +fixed term (regardless of how the transaction is characterized), the
323 +Corresponding Source conveyed under this section must be accompanied
324 +by the Installation Information. But this requirement does not apply
325 +if neither you nor any third party retains the ability to install
326 +modified object code on the User Product (for example, the work has
327 +been installed in ROM).
329 +The requirement to provide Installation Information does not include a
330 +requirement to continue to provide support service, warranty, or
331 +updates for a work that has been modified or installed by the
332 +recipient, or for the User Product in which it has been modified or
333 +installed. Access to a network may be denied when the modification
334 +itself materially and adversely affects the operation of the network
335 +or violates the rules and protocols for communication across the
336 +network.
338 +Corresponding Source conveyed, and Installation Information provided,
339 +in accord with this section must be in a format that is publicly
340 +documented (and with an implementation available to the public in
341 +source code form), and must require no special password or key for
342 +unpacking, reading or copying.
344 +### 7. Additional Terms.
346 +"Additional permissions" are terms that supplement the terms of this
347 +License by making exceptions from one or more of its conditions.
348 +Additional permissions that are applicable to the entire Program shall
349 +be treated as though they were included in this License, to the extent
350 +that they are valid under applicable law. If additional permissions
351 +apply only to part of the Program, that part may be used separately
352 +under those permissions, but the entire Program remains governed by
353 +this License without regard to the additional permissions.
355 +When you convey a copy of a covered work, you may at your option
356 +remove any additional permissions from that copy, or from any part of
357 +it. (Additional permissions may be written to require their own
358 +removal in certain cases when you modify the work.) You may place
359 +additional permissions on material, added by you to a covered work,
360 +for which you have or can give appropriate copyright permission.
362 +Notwithstanding any other provision of this License, for material you
363 +add to a covered work, you may (if authorized by the copyright holders
364 +of that material) supplement the terms of this License with terms:
366 +- a) Disclaiming warranty or limiting liability differently from the
367 + terms of sections 15 and 16 of this License; or
368 +- b) Requiring preservation of specified reasonable legal notices or
369 + author attributions in that material or in the Appropriate Legal
370 + Notices displayed by works containing it; or
371 +- c) Prohibiting misrepresentation of the origin of that material,
372 + or requiring that modified versions of such material be marked in
373 + reasonable ways as different from the original version; or
374 +- d) Limiting the use for publicity purposes of names of licensors
375 + or authors of the material; or
376 +- e) Declining to grant rights under trademark law for use of some
377 + trade names, trademarks, or service marks; or
378 +- f) Requiring indemnification of licensors and authors of that
379 + material by anyone who conveys the material (or modified versions
380 + of it) with contractual assumptions of liability to the recipient,
381 + for any liability that these contractual assumptions directly
382 + impose on those licensors and authors.
384 +All other non-permissive additional terms are considered "further
385 +restrictions" within the meaning of section 10. If the Program as you
386 +received it, or any part of it, contains a notice stating that it is
387 +governed by this License along with a term that is a further
388 +restriction, you may remove that term. If a license document contains
389 +a further restriction but permits relicensing or conveying under this
390 +License, you may add to a covered work material governed by the terms
391 +of that license document, provided that the further restriction does
392 +not survive such relicensing or conveying.
394 +If you add terms to a covered work in accord with this section, you
395 +must place, in the relevant source files, a statement of the
396 +additional terms that apply to those files, or a notice indicating
397 +where to find the applicable terms.
399 +Additional terms, permissive or non-permissive, may be stated in the
400 +form of a separately written license, or stated as exceptions; the
401 +above requirements apply either way.
403 +### 8. Termination.
405 +You may not propagate or modify a covered work except as expressly
406 +provided under this License. Any attempt otherwise to propagate or
407 +modify it is void, and will automatically terminate your rights under
408 +this License (including any patent licenses granted under the third
409 +paragraph of section 11).
411 +However, if you cease all violation of this License, then your license
412 +from a particular copyright holder is reinstated (a) provisionally,
413 +unless and until the copyright holder explicitly and finally
414 +terminates your license, and (b) permanently, if the copyright holder
415 +fails to notify you of the violation by some reasonable means prior to
416 +60 days after the cessation.
418 +Moreover, your license from a particular copyright holder is
419 +reinstated permanently if the copyright holder notifies you of the
420 +violation by some reasonable means, this is the first time you have
421 +received notice of violation of this License (for any work) from that
422 +copyright holder, and you cure the violation prior to 30 days after
423 +your receipt of the notice.
425 +Termination of your rights under this section does not terminate the
426 +licenses of parties who have received copies or rights from you under
427 +this License. If your rights have been terminated and not permanently
428 +reinstated, you do not qualify to receive new licenses for the same
429 +material under section 10.
431 +### 9. Acceptance Not Required for Having Copies.
433 +You are not required to accept this License in order to receive or run
434 +a copy of the Program. Ancillary propagation of a covered work
435 +occurring solely as a consequence of using peer-to-peer transmission
436 +to receive a copy likewise does not require acceptance. However,
437 +nothing other than this License grants you permission to propagate or
438 +modify any covered work. These actions infringe copyright if you do
439 +not accept this License. Therefore, by modifying or propagating a
440 +covered work, you indicate your acceptance of this License to do so.
442 +### 10. Automatic Licensing of Downstream Recipients.
444 +Each time you convey a covered work, the recipient automatically
445 +receives a license from the original licensors, to run, modify and
446 +propagate that work, subject to this License. You are not responsible
447 +for enforcing compliance by third parties with this License.
449 +An "entity transaction" is a transaction transferring control of an
450 +organization, or substantially all assets of one, or subdividing an
451 +organization, or merging organizations. If propagation of a covered
452 +work results from an entity transaction, each party to that
453 +transaction who receives a copy of the work also receives whatever
454 +licenses to the work the party's predecessor in interest had or could
455 +give under the previous paragraph, plus a right to possession of the
456 +Corresponding Source of the work from the predecessor in interest, if
457 +the predecessor has it or can get it with reasonable efforts.
459 +You may not impose any further restrictions on the exercise of the
460 +rights granted or affirmed under this License. For example, you may
461 +not impose a license fee, royalty, or other charge for exercise of
462 +rights granted under this License, and you may not initiate litigation
463 +(including a cross-claim or counterclaim in a lawsuit) alleging that
464 +any patent claim is infringed by making, using, selling, offering for
465 +sale, or importing the Program or any portion of it.
467 +### 11. Patents.
469 +A "contributor" is a copyright holder who authorizes use under this
470 +License of the Program or a work on which the Program is based. The
471 +work thus licensed is called the contributor's "contributor version".
473 +A contributor's "essential patent claims" are all patent claims owned
474 +or controlled by the contributor, whether already acquired or
475 +hereafter acquired, that would be infringed by some manner, permitted
476 +by this License, of making, using, or selling its contributor version,
477 +but do not include claims that would be infringed only as a
478 +consequence of further modification of the contributor version. For
479 +purposes of this definition, "control" includes the right to grant
480 +patent sublicenses in a manner consistent with the requirements of
481 +this License.
483 +Each contributor grants you a non-exclusive, worldwide, royalty-free
484 +patent license under the contributor's essential patent claims, to
485 +make, use, sell, offer for sale, import and otherwise run, modify and
486 +propagate the contents of its contributor version.
488 +In the following three paragraphs, a "patent license" is any express
489 +agreement or commitment, however denominated, not to enforce a patent
490 +(such as an express permission to practice a patent or covenant not to
491 +sue for patent infringement). To "grant" such a patent license to a
492 +party means to make such an agreement or commitment not to enforce a
493 +patent against the party.
495 +If you convey a covered work, knowingly relying on a patent license,
496 +and the Corresponding Source of the work is not available for anyone
497 +to copy, free of charge and under the terms of this License, through a
498 +publicly available network server or other readily accessible means,
499 +then you must either (1) cause the Corresponding Source to be so
500 +available, or (2) arrange to deprive yourself of the benefit of the
501 +patent license for this particular work, or (3) arrange, in a manner
502 +consistent with the requirements of this License, to extend the patent
503 +license to downstream recipients. "Knowingly relying" means you have
504 +actual knowledge that, but for the patent license, your conveying the
505 +covered work in a country, or your recipient's use of the covered work
506 +in a country, would infringe one or more identifiable patents in that
507 +country that you have reason to believe are valid.
509 +If, pursuant to or in connection with a single transaction or
510 +arrangement, you convey, or propagate by procuring conveyance of, a
511 +covered work, and grant a patent license to some of the parties
512 +receiving the covered work authorizing them to use, propagate, modify
513 +or convey a specific copy of the covered work, then the patent license
514 +you grant is automatically extended to all recipients of the covered
515 +work and works based on it.
517 +A patent license is "discriminatory" if it does not include within the
518 +scope of its coverage, prohibits the exercise of, or is conditioned on
519 +the non-exercise of one or more of the rights that are specifically
520 +granted under this License. You may not convey a covered work if you
521 +are a party to an arrangement with a third party that is in the
522 +business of distributing software, under which you make payment to the
523 +third party based on the extent of your activity of conveying the
524 +work, and under which the third party grants, to any of the parties
525 +who would receive the covered work from you, a discriminatory patent
526 +license (a) in connection with copies of the covered work conveyed by
527 +you (or copies made from those copies), or (b) primarily for and in
528 +connection with specific products or compilations that contain the
529 +covered work, unless you entered into that arrangement, or that patent
530 +license was granted, prior to 28 March 2007.
532 +Nothing in this License shall be construed as excluding or limiting
533 +any implied license or other defenses to infringement that may
534 +otherwise be available to you under applicable patent law.
536 +### 12. No Surrender of Others' Freedom.
538 +If conditions are imposed on you (whether by court order, agreement or
539 +otherwise) that contradict the conditions of this License, they do not
540 +excuse you from the conditions of this License. If you cannot convey a
541 +covered work so as to satisfy simultaneously your obligations under
542 +this License and any other pertinent obligations, then as a
543 +consequence you may not convey it at all. For example, if you agree to
544 +terms that obligate you to collect a royalty for further conveying
545 +from those to whom you convey the Program, the only way you could
546 +satisfy both those terms and this License would be to refrain entirely
547 +from conveying the Program.
549 +### 13. Use with the GNU Affero General Public License.
551 +Notwithstanding any other provision of this License, you have
552 +permission to link or combine any covered work with a work licensed
553 +under version 3 of the GNU Affero General Public License into a single
554 +combined work, and to convey the resulting work. The terms of this
555 +License will continue to apply to the part which is the covered work,
556 +but the special requirements of the GNU Affero General Public License,
557 +section 13, concerning interaction through a network will apply to the
558 +combination as such.
560 +### 14. Revised Versions of this License.
562 +The Free Software Foundation may publish revised and/or new versions
563 +of the GNU General Public License from time to time. Such new versions
564 +will be similar in spirit to the present version, but may differ in
565 +detail to address new problems or concerns.
567 +Each version is given a distinguishing version number. If the Program
568 +specifies that a certain numbered version of the GNU General Public
569 +License "or any later version" applies to it, you have the option of
570 +following the terms and conditions either of that numbered version or
571 +of any later version published by the Free Software Foundation. If the
572 +Program does not specify a version number of the GNU General Public
573 +License, you may choose any version ever published by the Free
574 +Software Foundation.
576 +If the Program specifies that a proxy can decide which future versions
577 +of the GNU General Public License can be used, that proxy's public
578 +statement of acceptance of a version permanently authorizes you to
579 +choose that version for the Program.
581 +Later license versions may give you additional or different
582 +permissions. However, no additional obligations are imposed on any
583 +author or copyright holder as a result of your choosing to follow a
584 +later version.
586 +### 15. Disclaimer of Warranty.
588 +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
589 +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
590 +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
591 +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
592 +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
593 +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
594 +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
595 +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
596 +CORRECTION.
598 +### 16. Limitation of Liability.
600 +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
602 +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
603 +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
604 +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
605 +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
606 +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
607 +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
608 +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
610 +### 17. Interpretation of Sections 15 and 16.
612 +If the disclaimer of warranty and limitation of liability provided
613 +above cannot be given local legal effect according to their terms,
614 +reviewing courts shall apply local law that most closely approximates
615 +an absolute waiver of all civil liability in connection with the
616 +Program, unless a warranty or assumption of liability accompanies a
617 +copy of the Program in return for a fee.
619 +END OF TERMS AND CONDITIONS
621 +## How to Apply These Terms to Your New Programs
623 +If you develop a new program, and you want it to be of the greatest
624 +possible use to the public, the best way to achieve this is to make it
625 +free software which everyone can redistribute and change under these
626 +terms.
628 +To do so, attach the following notices to the program. It is safest to
629 +attach them to the start of each source file to most effectively state
630 +the exclusion of warranty; and each file should have at least the
631 +"copyright" line and a pointer to where the full notice is found.
633 + <one line to give the program's name and a brief idea of what it does.>
634 + Copyright (C) <year> <name of author>
636 + This program is free software: you can redistribute it and/or modify
637 + it under the terms of the GNU General Public License as published by
638 + the Free Software Foundation, either version 3 of the License, or
639 + (at your option) any later version.
641 + This program is distributed in the hope that it will be useful,
642 + but WITHOUT ANY WARRANTY; without even the implied warranty of
643 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
644 + GNU General Public License for more details.
646 + You should have received a copy of the GNU General Public License
647 + along with this program. If not, see <https://www.gnu.org/licenses/>.
649 +Also add information on how to contact you by electronic and paper
650 +mail.
652 +If the program does terminal interaction, make it output a short
653 +notice like this when it starts in an interactive mode:
655 + <program> Copyright (C) <year> <name of author>
656 + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 + This is free software, and you are welcome to redistribute it
658 + under certain conditions; type `show c' for details.
660 +The hypothetical commands \`show w' and \`show c' should show the
661 +appropriate parts of the General Public License. Of course, your
662 +program's commands might be different; for a GUI interface, you would
663 +use an "about box".
665 +You should also get your employer (if you work as a programmer) or
666 +school, if any, to sign a "copyright disclaimer" for the program, if
667 +necessary. For more information on this, and how to apply and follow
668 +the GNU GPL, see <https://www.gnu.org/licenses/>.
670 +The GNU General Public License does not permit incorporating your
671 +program into proprietary programs. If your program is a subroutine
672 +library, you may consider it more useful to permit linking proprietary
673 +applications with the library. If this is what you want to do, use the
674 +GNU Lesser General Public License instead of this License. But first,
675 +please read <https://www.gnu.org/licenses/why-not-lgpl.html>.

pi/agent/skills/pi/README.md

Added
new file mode 100644
1 +# Pi Skill
3 +Pi's own system prompt already points it at its source documentation. But when you use a different coding agent — Claude Code, OpenCode, Codex CLI, or an IDE agent like Cursor or Windsurf — to work on Pi extensions, skills, packages, or configuration, that agent has no built-in knowledge of Pi's architecture. It will hallucinate APIs, invent settings, and confidently describe extension hooks that don't exist.
5 +This skill gives any coding agent grounded knowledge of Pi via the [Agent Skills](https://agentskills.io/home) standard. It injects task-specific reference documentation into context so the agent reasons from facts — about extensions, settings, providers, sessions, and the SDK — rather than from plausible fictions.
7 +## Install
9 +```bash
10 +# as a skill
11 +npx skills add counterposition/pi --skill pi
13 +# as a Pi package
14 +pi install npm:@counterposition/skill-pi
15 +```
17 +### Maintainer Paths
19 +```bash
20 +# from a local checkout
21 +npx skills add /absolute/path/to/pi --skill pi
23 +# packaged install from monorepo root
24 +pi install ./packages/skill-pi
25 +```
27 +If you develop inside this repo, Pi already loads the skill via `.pi/settings.json`.
29 +## What this covers
31 +Pi's architecture and package layout. Skill authoring, discovery, and routing. Extensions, tools, and UI hooks. Settings, models, providers, and packages. Sessions, forks, and compaction. The SDK and RPC interface.
33 +The reference material lives in `references/` as task-specific documents — not a single monolith, but pieces sized for injection into a conversation when relevant.
35 +## Files
37 +| Path | Purpose |
38 +| ------------------ | ------------------------------------- |
39 +| `SKILL.md` | Trigger rules and routing description |
40 +| `references/` | Task-specific Pi reference documents |
41 +| `evals/evals.json` | Example evaluation cases |
42 +| `LICENSE.md` | GPLv3 license text |

pi/agent/skills/pi/SKILL.md

Added
new file mode 100644
1 +---
2 +name: pi
3 +description: "Provides Pi-specific guidance for extensions, skills, `.pi/` config, `settings.json`, `models.json`, packages, providers, themes, SDK/RPC, sessions, and compaction in Pi, the coding agent. Use when the user mentions Pi or Pi-specific terms such as `.pi/`, `SKILL.md`, `createAgentSession()`, `thinkingLevel`, `session_before_compact`, `pi-ai`, `pi-tui`, `pi-agent-core`, or `pi-coding-agent`. Not for Raspberry Pi hardware, the math constant, or unrelated generic tooling."
4 +license: GPLv3
5 +compatibility: "Pi-specific guidance for agents that support Agent Skills"
6 +---
8 +# Pi Coding Agent
10 +Pi is a minimal terminal coding harness. Default tools: `read`, `write`, `edit`, `bash`, `grep`, `find`, `ls`. Modes: interactive (`pi`), print (`pi -p`), JSON (`--mode json`), RPC (`--mode rpc`), or embedded (`createAgentSession()`). Sub-agents, plan mode, permission flows, and MCP are intentionally left to extensions and Pi packages.
12 +Pi's philosophy: **adapt Pi to your workflows, not the other way around**.
14 +## Architecture
16 +Core packages on npm (source: [github.com/earendil-works/pi](https://github.com/earendil-works/pi)):
18 +| Package | Purpose |
19 +|---------|---------|
20 +| `@earendil-works/pi-ai` | Unified LLM API across 20+ providers |
21 +| `@earendil-works/pi-agent-core` | Agent runtime with tool execution and state |
22 +| `@earendil-works/pi-tui` | Terminal UI components |
23 +| `@earendil-works/pi-coding-agent` | CLI, extensions, skills, sessions, settings |
24 +| `@earendil-works/pi-web-ui` | Web components for chat interfaces |
26 +## File System Layout
28 +```text
29 +~/.pi/agent/ # Global config dir (PI_CODING_AGENT_DIR overrides)
30 +├── settings.json # Global settings
31 +├── auth.json # Credentials (0600 perms)
32 +├── models.json # Custom provider/model definitions
33 +├── keybindings.json # Keyboard shortcuts
34 +├── extensions/ # Auto-discovered
35 +├── skills/ # Auto-discovered
36 +├── prompts/ # Auto-discovered
37 +├── themes/ # Custom themes
38 +└── sessions/ # JSONL session files
40 +<project>/
41 +└── .pi/ # Project-local config (overrides global)
42 + ├── settings.json
43 + ├── extensions/
44 + ├── skills/
45 + ├── prompts/
46 + ├── themes/
47 + └── agents/ # Agent definitions (subagent extension)
48 +```
50 +## Key Concepts
52 +- **Extensions** — TypeScript modules with full system access. Hook into Pi's lifecycle to register tools, intercept calls, add commands, build UI. → `references/extensions.md`
53 +- **Skills** — Markdown capability packages (`SKILL.md` + frontmatter) following the Agent Skills standard. Pi loads names + descriptions into the system prompt; bodies load on demand. → `references/skills.md`
54 +- **Settings** — Hierarchical JSON: project `.pi/settings.json` merges over global `~/.pi/agent/settings.json`. → `references/settings.md`
55 +- **Packages** — Bundles of extensions/skills/prompts/themes via npm, git, or local paths. Installed with `pi install`. → `references/packages.md`
56 +- **Context files & prompt templates** — Pi loads `AGENTS.md` / `CLAUDE.md` from the agent dir and from `cwd` up through ancestors. `.pi/SYSTEM.md` replaces the system prompt; `APPEND_SYSTEM.md` appends. Prompt templates in `prompts/` become slash commands. → `references/settings.md`
57 +- **SDK** — Programmatic embedding via `createAgentSession()`; `createAgentSessionRuntime()` for session replacement. → `references/sdk.md`
58 +- **Custom providers & models** — `models.json` or extension `pi.registerProvider()` for any OpenAI-/Anthropic-/Google-compatible or custom LLM endpoint. → `references/providers.md`
59 +- **Sessions & compaction** — Append-only JSONL with a tree structure; branch with `/tree`, `/fork`, `/clone`, compact with `/compact`. Auto-compaction triggers when `contextTokens > contextWindow - reserveTokens`. Extensions intercept via `session_before_compact`. → `references/extensions.md` and `references/sdk.md`
61 +## How to Use This Skill
63 +| Task | Reference |
64 +|------|-----------|
65 +| Writing an extension (tools, commands, events, UI) | `references/extensions.md` |
66 +| Creating a skill | `references/skills.md` |
67 +| Configuring Pi (settings, env vars, CLI flags) | `references/settings.md` |
68 +| Building a shareable package | `references/packages.md` |
69 +| Embedding Pi programmatically | `references/sdk.md` |
70 +| Adding LLM providers or models | `references/providers.md` |
71 +| Looking for a recipe or pattern | `references/patterns.md` |
73 +For exact CLI flags run `pi --help` or read the relevant reference. Resource flags (`--no-extensions`, `--no-skills`, `--no-context-files`, `--no-builtin-tools`, etc.) are documented in `references/settings.md`.

pi/agent/skills/pi/evals/evals.json

Added
new file mode 100644
1 +{
2 + "skill_name": "pi",
3 + "evals": [
4 + {
5 + "id": 1,
6 + "prompt": "Write a Pi extension that blocks any bash command containing `curl` unless the user confirms, and logs all blocked commands to a file at ~/.pi/agent/blocked-commands.log",
7 + "expected_output": "A TypeScript extension file that hooks into tool_call events, checks for curl in bash commands, prompts via ctx.ui.select, and appends blocked commands to a log file. Should check ctx.hasUI and handle non-interactive mode.",
8 + "files": [],
9 + "assertions": [
10 + "Uses correct ExtensionAPI import from @earendil-works/pi-coding-agent",
11 + "Hooks into tool_call event (the correct event for intercepting tool calls)",
12 + "Checks event.toolName === 'bash' before inspecting command",
13 + "Tests for curl in the command string",
14 + "Checks ctx.hasUI before calling interactive UI methods",
15 + "Uses ctx.ui.select or ctx.ui.confirm for user confirmation",
16 + "Returns { block: true, reason: '...' } to prevent execution",
17 + "Logs blocked commands to ~/.pi/agent/blocked-commands.log",
18 + "Uses correct export default function (pi: ExtensionAPI) signature"
19 + ]
20 + },
21 + {
22 + "id": 2,
23 + "prompt": "I want to set up Pi to use Ollama with llama3.2 locally, with auto-compaction disabled and a custom session directory at ~/pi-sessions. Walk me through the configuration.",
24 + "expected_output": "Instructions covering models.json with Ollama provider config (baseUrl localhost:11434/v1, api openai-completions, dummy apiKey, model id llama3.2), settings.json with compaction.enabled=false and sessionDir pointing to ~/pi-sessions.",
25 + "files": [],
26 + "assertions": [
27 + "Provides models.json with Ollama baseUrl containing localhost:11434",
28 + "Uses api type openai-completions (correct for Ollama)",
29 + "Includes model entry with id llama3.2",
30 + "Provides settings.json with compaction.enabled set to false",
31 + "Sets sessionDir to ~/pi-sessions",
32 + "Correct file paths: ~/.pi/agent/models.json and ~/.pi/agent/settings.json"
33 + ]
34 + },
35 + {
36 + "id": 3,
37 + "prompt": "Create a Pi skill that helps with database migrations — it should know about Prisma, Drizzle, and raw SQL approaches. Give me the full SKILL.md and any reference files.",
38 + "expected_output": "A SKILL.md with proper frontmatter (name, description), a main body routing to reference files, and separate reference docs for Prisma, Drizzle, and raw SQL migration patterns.",
39 + "files": [],
40 + "assertions": [
41 + "SKILL.md has valid YAML frontmatter with name and description fields",
42 + "Name follows Pi convention: lowercase, hyphens only, max 64 chars",
43 + "Description mentions trigger contexts (migrations, Prisma, Drizzle, SQL)",
44 + "Includes separate reference files for Prisma, Drizzle, and raw SQL",
45 + "SKILL.md uses relative paths to reference files",
46 + "Body routes to the correct reference doc based on the user's framework choice"
47 + ]
48 + }
49 + ]

pi/agent/skills/pi/references/extensions.md

Added
new file mode 100644
1 +# Extensions
3 +Extensions are TypeScript modules that extend Pi's behavior. They run with the user's full permissions, so treat them like normal application code.
5 +## Placement & Discovery
7 +| Location | Scope |
8 +|----------|-------|
9 +| `~/.pi/agent/extensions/*.ts` | Global |
10 +| `~/.pi/agent/extensions/*/index.ts` | Global |
11 +| `.pi/extensions/*.ts` | Project |
12 +| `.pi/extensions/*/index.ts` | Project |
13 +| `settings.json` → `extensions` | Additional local paths |
15 +Use `pi -e ./my-extension.ts` or `pi --extension ...` for quick tests. Put stable extensions in auto-discovered locations if you want `/reload` to pick them up.
17 +## Common Imports
19 +```typescript
20 +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
21 +import { Type } from "typebox";
22 +import { StringEnum } from "@earendil-works/pi-ai";
23 +import { Text } from "@earendil-works/pi-tui";
24 +```
26 +- Use `typebox` (1.x) for schemas.
27 +- Use `StringEnum` from `@earendil-works/pi-ai` for Google-compatible string enums.
29 +## Quick Start
31 +```typescript
32 +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
33 +import { Type } from "typebox";
35 +export default function (pi: ExtensionAPI) {
36 + pi.on("session_start", async (_event, ctx) => {
37 + if (ctx.hasUI) ctx.ui.notify("Extension loaded", "info");
38 + });
40 + pi.registerTool({
41 + name: "greet",
42 + label: "Greet",
43 + description: "Greet someone by name",
44 + parameters: Type.Object({
45 + name: Type.String({ description: "Name to greet" }),
46 + }),
47 + async execute(_toolCallId, params) {
48 + return {
49 + content: [{ type: "text", text: `Hello, ${params.name}!` }],
50 + details: {},
51 + };
52 + },
53 + });
55 + // For reusable tool definitions outside `pi.registerTool(...)`, use `defineTool({...})`
56 + // — it preserves parameter type inference and can be passed via `customTools` to the SDK.
58 + pi.registerCommand("hello", {
59 + description: "Say hello",
60 + async handler(args, ctx) {
61 + if (ctx.hasUI) ctx.ui.notify(`Hello ${args || "world"}!`, "info");
62 + },
63 + });
65 +```
67 +## Event Surface
69 +Useful session events:
71 +- `session_start`
72 +- `session_before_switch`
73 +- `session_before_fork`
74 +- `session_before_compact`
75 +- `session_compact`
76 +- `session_before_tree`
77 +- `session_tree`
78 +- `session_shutdown`
79 +- `resources_discover`
81 +`session_start` carries `event.reason` — `"startup" | "reload" | "new" | "resume" | "fork"` — and `event.previousSessionFile` for `"new"`/`"resume"`/`"fork"`. The old post-transition `session_switch` / `session_fork` events were removed; route all of those flows through `session_start`.
83 +Useful agent events:
85 +- `input`
86 +- `before_agent_start` — receives `event.systemPromptOptions` (a `BuildSystemPromptOptions`) so handlers can inspect the structured inputs feeding the system prompt
87 +- `agent_start`
88 +- `agent_end`
89 +- `turn_start`
90 +- `turn_end`
91 +- `message_start`
92 +- `message_update`
93 +- `message_end` — return a replacement message to override usage/cost or rewrite the finalized assistant message
94 +- `context`
95 +- `before_provider_request`
96 +- `after_provider_response` — inspect the provider HTTP status and headers before stream consumption
97 +- `model_select`
98 +- `thinking_level_select` — observe interactive thinking-level changes
100 +Useful tool events:
102 +- `tool_execution_start`
103 +- `tool_call`
104 +- `tool_execution_update`
105 +- `tool_result`
106 +- `tool_execution_end`
108 +Tool results may include `terminate: true` to end the current tool batch without an automatic follow-up LLM turn — useful for tools that produce a structured final answer (see `examples/extensions/structured-output.ts` in the Pi repo).
110 +`session_shutdown` events carry `event.reason` (`"quit" | "reload" | "new" | "resume" | "fork"`) and, where applicable, `event.targetSessionFile` so cleanup logic can distinguish teardown paths.
112 +## Extension Context
114 +`ctx` gives extensions access to:
116 +- `ctx.ui` for interactive UI hooks
117 +- `ctx.cwd`
118 +- `ctx.session`
119 +- `ctx.sessionManager`
120 +- `ctx.modelRegistry`
121 +- `ctx.hasUI`
122 +- `ctx.isIdle()`
123 +- `ctx.abort()`
124 +- `ctx.getContextUsage()`
125 +- `ctx.getSystemPrompt()`
127 +## Tool Registration
129 +```typescript
130 +pi.registerTool({
131 + name: "tool_name",
132 + label: "Tool Name",
133 + description: "What this tool does",
134 + parameters: Type.Object({
135 + arg1: Type.String({ description: "..." }),
136 + }),
138 + // Runs before schema validation. Useful for migrating old tool-call shapes.
139 + prepareArguments(rawArgs) {
140 + return rawArgs;
141 + },
143 + async execute(toolCallId, params, signal, onUpdate, ctx) {
144 + return {
145 + content: [{ type: "text", text: "result" }],
146 + details: { persisted: true },
147 + };
148 + },
149 +});
150 +```
152 +Important rules:
154 +1. Truncate large output.
155 +2. Respect `signal.aborted`.
156 +3. Throw on failure instead of returning fake success.
157 +4. Use the file-mutation queue for write/edit style tools.
158 +5. Put reconstructable state in `details`; it persists in session history.
160 +## UI Methods
162 +Check `ctx.hasUI` first. Non-interactive modes may not support UI.
164 +```typescript
165 +const choice = await ctx.ui.select("Pick one:", ["A", "B"]);
166 +const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
167 +const text = await ctx.ui.input("Name:", "default");
168 +const edited = await ctx.ui.editor("Edit:", "prefilled text");
170 +ctx.ui.notify("Done", "info");
172 +ctx.ui.setStatus("my-ext", "Processing...");
173 +ctx.ui.setWorkingMessage("Thinking deeply...");
174 +ctx.ui.setWorkingIndicator({ frames: ["⣷", "⣯", "⣟", "⡿"], intervalMs: 80 });
175 +ctx.ui.setWorkingVisible(false); // hide the built-in loader row
176 +ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
177 +ctx.ui.setFooter((tui, theme) => new Text(theme.fg("dim", "Custom footer"), 0, 0));
178 +ctx.ui.setTitle("pi - custom");
180 +ctx.ui.setEditorText("prefilled text");
181 +const current = ctx.ui.getEditorText();
182 +ctx.ui.pasteToEditor("extra text");
183 +ctx.ui.setHiddenThinkingLabel("…");
184 +const editorFactory = ctx.ui.getEditorComponent(); // wrap the active editor factory
186 +ctx.ui.setToolsExpanded(true);
188 +ctx.ui.addAutocompleteProvider((query, ctx) => /* completions */); // stack on top of slash/path provider
190 +const result = await ctx.ui.custom((tui, theme, keybindings, done) => {
191 + return new Text("Press Enter", 0, 0);
192 +}, { overlay: true });
193 +```
195 +## Commands, Shortcuts, Flags
197 +```typescript
198 +pi.registerCommand("name", {
199 + description: "Run a command",
200 + async handler(args, ctx) {
201 + await ctx.waitForIdle();
202 + ctx.reload();
203 + },
204 +});
206 +pi.registerShortcut("ctrl+x", {
207 + description: "Do something quickly",
208 + handler: async (ctx) => {},
209 +});
211 +pi.registerFlag("my-flag", {
212 + description: "Enable something",
213 + handler: (value) => {},
214 +});
215 +```
217 +## Persistence & Process Hooks
219 +Store extension state with custom session entries:
221 +```typescript
222 +pi.appendEntry("my-extension-state", { key: "value" });
223 +```
225 +Use lifecycle hooks to restore it:
227 +```typescript
228 +pi.on("session_start", async (_event, ctx) => {
229 + for (const entry of ctx.sessionManager.getBranch().reverse()) {
230 + if (entry.type === "custom" && entry.name === "my-extension-state") {
231 + break;
234 +});
235 +```
237 +## Provider Integration
239 +Extensions can register or override providers:
241 +```typescript
242 +pi.registerProvider("my-provider", {
243 + name: "My Provider", // optional friendly label for /login
244 + baseUrl: "https://api.example.com",
245 + api: "openai-completions",
246 + apiKey: "MY_PROVIDER_KEY",
247 + models: [
249 + id: "my-model",
250 + name: "My Model",
251 + contextWindow: 128000,
252 + maxTokens: 4096,
253 + baseUrl: "https://us-east.api.example.com", // per-model override
254 + thinkingLevelMap: { off: null, minimal: "low", medium: "medium", high: "high", xhigh: "high" },
255 + },
256 + ],
257 +});
259 +// Override-only: re-route an existing built-in provider through a proxy
260 +pi.registerProvider("anthropic", { baseUrl: "https://proxy.example.com" });
262 +pi.unregisterProvider("my-provider");
263 +```
265 +If you need auth for a specific model request, use:
267 +```typescript
268 +const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
269 +```
271 +Pass `shouldStopAfterTurn` via the SDK to exit the agent loop gracefully after a completed turn. See `references/sdk.md` and `references/providers.md` for the full provider/model schema.
273 +## Handy Patterns
275 +- Permission gates via `tool_call`
276 +- Prompt injection via `before_agent_start`
277 +- Branch or compaction customization via `session_before_tree` / `session_before_compact`
278 +- Provider payload inspection via `before_provider_request`
279 +- Stateful tools via `details` plus `session_start` reconstruction

pi/agent/skills/pi/references/packages.md

Added
new file mode 100644
1 +# Pi Packages
3 +Pi packages bundle extensions, skills, prompt templates, and themes so they can be shared through npm, git, or local paths.
5 +**Security warning:** Pi packages run with full system access. Review third-party source before installing it.
7 +## Install and Manage
9 +```bash
10 +pi install npm:@foo/bar@1.0.0
11 +pi install git:github.com/user/repo@v1
12 +pi install https://github.com/user/repo
13 +pi install /absolute/path/to/package
14 +pi install ./relative/path/to/package
16 +pi remove npm:@foo/bar
17 +pi uninstall npm:@foo/bar
18 +pi list
19 +pi update # update pi itself + all installed packages (skips pinned)
20 +pi update --self # update pi only
21 +pi update --extensions # update packages only
22 +pi update <source> # update one package
23 +pi config
24 +```
26 +By default, `install` and `remove` write to global settings (`~/.pi/agent/settings.json`). Use `-l` to write to project settings (`.pi/settings.json`) instead.
28 +Project installs are shareable with a team. Pi will install missing project packages automatically on startup.
30 +For temporary one-run testing, use `--extension` / `-e` with an npm or git source. Pi installs it into a temporary directory for that run only.
32 +## Package Sources
34 +### npm
36 +```text
37 +npm:@scope/pkg@1.2.3
38 +npm:pkg
39 +```
41 +- Global installs use `npm install -g`
42 +- Project installs go under `.pi/npm/`
43 +- Version-pinned installs are skipped by `pi update`
44 +- Use `npmCommand` in settings if you need a wrapper such as `mise` or `asdf`
46 +### git
48 +```text
49 +git:github.com/user/repo@v1
50 +git:git@github.com:user/repo@v1
51 +https://github.com/user/repo@v1
52 +ssh://git@github.com/user/repo@v1
53 +```
55 +- Global clones live in `~/.pi/agent/git/`
56 +- Project clones live in `.pi/git/`
57 +- Refs pin the package and are skipped by `pi update`
58 +- Pi runs `npm install` after clone/pull when `package.json` exists
60 +### local paths
62 +- Files are treated as single extensions
63 +- Directories are loaded using normal package rules
64 +- Relative paths resolve relative to the settings file they appear in
66 +## Creating a Package
68 +Pi supports either a `pi` manifest in `package.json` or convention-based directories.
70 +```json
72 + "name": "my-package",
73 + "keywords": ["pi-package"],
74 + "pi": {
75 + "extensions": ["./extensions"],
76 + "skills": ["./skills"],
77 + "prompts": ["./prompts"],
78 + "themes": ["./themes"]
79 + }
81 +```
83 +If there is no `pi` manifest, Pi auto-discovers:
85 +- `extensions/` for `.ts` / `.js`
86 +- `skills/` for `SKILL.md` directories and top-level `.md` skill files
87 +- `prompts/` for `.md`
88 +- `themes/` for `.json`
90 +## Dependencies
92 +- Normal runtime dependencies belong in `dependencies`
93 +- Pi core libraries should be peer deps with `"*"` ranges:
94 + - `@earendil-works/pi-ai`
95 + - `@earendil-works/pi-agent-core`
96 + - `@earendil-works/pi-coding-agent`
97 + - `@earendil-works/pi-tui`
98 + - `typebox`
99 +- Other Pi packages must be bundled explicitly
100 +- Git package installs run `npm install --omit=dev` — runtime needs go in `dependencies`, not `devDependencies`
102 +## Package Filtering
104 +`settings.json` can narrow package resources with object-form entries:
106 +```json
108 + "packages": [
110 + "source": "npm:my-package",
111 + "extensions": ["extensions/*.ts", "!extensions/legacy.ts"],
112 + "skills": [],
113 + "prompts": ["prompts/review.md"],
114 + "themes": ["+themes/legacy.json"]
118 +```
120 +Rules:
122 +- Omit a key to load all resources of that type
123 +- Use `[]` to load none
124 +- Use `!pattern` to exclude glob matches
125 +- Use `+path` / `-path` for exact include or exclude
127 +## Scope and Deduplication
129 +- Project settings override global settings for the same package identity
130 +- Identity is package name for npm, repo URL for git, and resolved absolute path for local sources
131 +- `pi config` can enable or disable package resources after installation

pi/agent/skills/pi/references/patterns.md

Added
new file mode 100644
1 +# Common Patterns & Recipes
3 +Practical recipes for extending Pi. Each pattern is a self-contained example.
5 +## Table of Contents
7 +1. [Permission Gate](#permission-gate)
8 +2. [Protected Paths](#protected-paths)
9 +3. [Preset System](#preset-system)
10 +4. [Sub-agents](#sub-agents)
11 +5. [Git Checkpoint & Restore](#git-checkpoint--restore)
12 +6. [Auto-Commit on Exit](#auto-commit-on-exit)
13 +7. [Custom Compaction](#custom-compaction)
14 +8. [Plan Mode (Read-Only)](#plan-mode-read-only)
15 +9. [Claude Rules Integration](#claude-rules-integration)
16 +10. [Interactive Shell](#interactive-shell)
17 +11. [TUI Components](#tui-components)
18 +12. [Status Line & Widgets](#status-line--widgets)
19 +13. [File Watcher / Trigger](#file-watcher--trigger)
20 +14. [Input Transform](#input-transform)
21 +15. [Tool Override](#tool-override)
23 +---
25 +## Permission Gate
27 +Block dangerous bash commands with user confirmation:
29 +```typescript
30 +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
32 +export default function (pi: ExtensionAPI) {
33 + const dangerous = [/\brm\s+(-rf?|--recursive)/i, /\bsudo\b/i, /\b(chmod|chown)\b.*777/i];
35 + pi.on("tool_call", async (event, ctx) => {
36 + if (event.toolName !== "bash") return;
37 + const cmd = event.input.command as string;
38 + if (!dangerous.some(p => p.test(cmd))) return;
39 + if (!ctx.hasUI) return { block: true, reason: "Dangerous command blocked (no UI)" };
40 + const ok = await ctx.ui.select(`⚠️ ${cmd}\nAllow?`, ["Yes", "No"]);
41 + if (ok !== "Yes") return { block: true, reason: "Blocked by user" };
42 + });
44 +```
46 +## Protected Paths
48 +Block writes to sensitive files:
50 +```typescript
51 +export default function (pi: ExtensionAPI) {
52 + const protected = [".env", ".git/", "node_modules/", "*.pem", "*.key"];
54 + pi.on("tool_call", async (event, ctx) => {
55 + if (!["write", "edit"].includes(event.toolName)) return;
56 + const path = (event.input.file_path || event.input.path) as string;
57 + if (protected.some(p => path.includes(p))) {
58 + return { block: true, reason: `Protected path: ${path}` };
59 + }
60 + });
62 +```
64 +## Preset System
66 +Named configurations (model + thinking + tools + instructions):
68 +**`~/.pi/agent/presets.json`:**
70 +```json
72 + "plan": {
73 + "model": "claude-sonnet-4-20250514",
74 + "thinkingLevel": "high",
75 + "tools": ["read", "grep", "find", "ls"],
76 + "instructions": "Analyze the codebase and propose a plan. Do not modify any files."
77 + },
78 + "implement": {
79 + "model": "claude-sonnet-4-20250514",
80 + "thinkingLevel": "medium",
81 + "tools": ["read", "bash", "edit", "write"],
82 + "instructions": "Implement the requested changes with minimal, focused edits."
83 + }
85 +```
87 +The preset extension (from Pi examples) loads these and exposes `/preset [name]` + `Ctrl+Shift+U` cycling.
89 +## Sub-agents
91 +Delegate tasks to isolated Pi processes. The subagent extension (from Pi examples) provides:
93 +```text
94 +// Single agent
95 +{ agent: "researcher", task: "Find all API endpoints in this codebase" }
97 +// Parallel execution
98 +{ tasks: [
99 + { agent: "researcher", task: "Analyze auth module" },
100 + { agent: "researcher", task: "Analyze database module" }
103 +// Sequential chain with context passing
104 +{ chain: [
105 + { agent: "researcher", task: "Find all TODO comments" },
106 + { agent: "writer", task: "Write a summary of: {previous}" }
108 +```
110 +Agent definitions live in `~/.pi/agent/agents/` or `.pi/agents/`. Each is a directory with a config file specifying model, tools, and system prompt.
112 +## Git Checkpoint & Restore
114 +Save code state at each turn, offer restore on fork:
116 +```typescript
117 +export default function (pi: ExtensionAPI) {
118 + const checkpoints = new Map<string, string>();
119 + let currentEntryId: string | undefined;
121 + pi.on("tool_result", async (_event, ctx) => {
122 + const leaf = ctx.sessionManager.getLeafEntry();
123 + if (leaf) currentEntryId = leaf.id;
124 + });
126 + pi.on("turn_start", async () => {
127 + const { stdout } = await pi.exec("git", ["stash", "create"]);
128 + if (stdout.trim() && currentEntryId) checkpoints.set(currentEntryId, stdout.trim());
129 + });
131 + pi.on("session_before_fork", async (event, ctx) => {
132 + const ref = checkpoints.get(event.entryId);
133 + if (!ref || !ctx.hasUI) return;
134 + const ok = await ctx.ui.select("Restore code?", ["Yes", "No"]);
135 + if (ok?.startsWith("Yes")) await pi.exec("git", ["stash", "apply", ref]);
136 + });
138 +```
140 +## Auto-Commit on Exit
142 +Stage and commit all changes when session ends:
144 +```typescript
145 +export default function (pi: ExtensionAPI) {
146 + pi.on("session_shutdown", async (_event, ctx) => {
147 + const { stdout } = await pi.exec("git", ["status", "--porcelain"]);
148 + if (!stdout.trim()) return;
150 + const messages = ctx.sessionManager.getBranch();
151 + const lastAssistant = messages.reverse().find(m => m.role === "assistant");
152 + const text = lastAssistant?.content?.find(c => c.type === "text")?.text || "pi session changes";
153 + const firstLine = text.split("\n")[0].slice(0, 50);
155 + await pi.exec("git", ["add", "-A"]);
156 + await pi.exec("git", ["commit", "-m", `[pi] ${firstLine}`]);
157 + ctx.ui?.notify("Changes committed", "info");
158 + });
160 +```
162 +## Custom Compaction
164 +Replace default compaction with a custom summary model:
166 +```typescript
167 +export default function (pi: ExtensionAPI) {
168 + pi.on("session_before_compact", async (event, ctx) => {
169 + const allMessages = [...event.messagesToSummarize, ...event.turnPrefixMessages];
170 + // Use a cheaper model for summarization
171 + const summary = await myCustomSummarize(allMessages);
172 + return {
173 + summary,
174 + firstKeptEntryId: event.firstKeptEntryId,
175 + tokensBefore: event.tokens,
176 + };
177 + });
179 +```
181 +## Plan Mode (Read-Only)
183 +Restrict to read-only tools for safe exploration:
185 +```typescript
186 +export default function (pi: ExtensionAPI) {
187 + let planMode = false;
189 + pi.registerCommand("plan", {
190 + description: "Toggle read-only plan mode",
191 + async handler(_args, ctx) {
192 + planMode = !planMode;
193 + if (planMode) {
194 + pi.setActiveTools(["read", "bash", "grep", "find", "ls"]);
195 + ctx.ui.notify("Plan mode ON — read-only tools only", "info");
196 + } else {
197 + pi.setActiveTools(["read", "bash", "edit", "write"]);
198 + ctx.ui.notify("Plan mode OFF — full tools restored", "info");
200 + },
201 + });
203 + pi.on("tool_call", async (event) => {
204 + if (!planMode || event.toolName !== "bash") return;
205 + const cmd = event.input.command as string;
206 + // Block destructive bash in plan mode
207 + if (/\b(rm|mv|cp|chmod|chown|git\s+(push|commit|reset))\b/.test(cmd)) {
208 + return { block: true, reason: "Blocked in plan mode" };
210 + });
212 +```
214 +## Claude Rules Integration
216 +Scan `.claude/rules/` and inject into system prompt:
218 +```typescript
219 +export default function (pi: ExtensionAPI) {
220 + pi.on("before_agent_start", async (event, ctx) => {
221 + const rulesDir = path.join(ctx.cwd, ".claude", "rules");
222 + if (!fs.existsSync(rulesDir)) return;
223 + const files = fs.readdirSync(rulesDir, { recursive: true })
224 + .filter(f => f.toString().endsWith(".md"));
225 + if (files.length === 0) return;
226 + const listing = files.map(f => `- .claude/rules/${f}`).join("\n");
227 + event.systemPrompt += `\n\nProject rules (${files.length} files):\n${listing}\nUse the read tool to load relevant rules.`;
228 + });
230 +```
232 +## Interactive Shell
234 +Keep a persistent shell session across tool calls (rather than spawning a new shell each time):
236 +The Pi examples include an `interactive-shell.ts` extension that maintains a persistent bash process, allowing stateful shell operations (cd, environment variables, etc.) across multiple tool invocations.
238 +## TUI Components
240 +Pi's TUI library (`@earendil-works/pi-tui`) provides:
242 +- `Text` — Word-wrapped text
243 +- `Box` — Padded container with border
244 +- `Container` — Vertical grouping
245 +- `Spacer` — Vertical space
246 +- `Markdown` — Rendered markdown
247 +- `Image` — Terminal image display
248 +- `SelectList` — Interactive selection list
249 +- `BorderedLoader` — Async spinner with cancel
251 +All components implement `render(width) → string[]` and optional `handleInput(data)`.
253 +## Status Line & Widgets
255 +```typescript
256 +// Footer status text
257 +ctx.ui.setStatus("search", "Searching...");
259 +// Widget above the editor
260 +ctx.ui.setWidget("current-task", new Text("Current task: refactoring auth", 0, 0));
262 +// Widget below the editor
263 +ctx.ui.setWidget("progress", progressComponent, { placement: "belowEditor" });
265 +// Custom footer
266 +ctx.ui.setFooter((tui, theme) => new Text(theme.fg("accent", "My Extension v1.0"), 0, 0));
267 +```
269 +## File Watcher / Trigger
271 +Run actions when files change:
273 +```typescript
274 +export default function (pi: ExtensionAPI) {
275 + pi.on("session_start", async (_event, ctx) => {
276 + fs.watch(ctx.cwd, { recursive: true }, (eventType, filename) => {
277 + if (filename?.endsWith(".test.ts")) {
278 + ctx.ui.notify(`Test file changed: ${filename}`, "info");
280 + });
281 + });
283 +```
285 +## Input Transform
287 +Modify user input before it reaches the LLM:
289 +```typescript
290 +pi.on("input", async (event) => {
291 + // Expand shorthand
292 + event.text = event.text.replace(/^fix /, "Find and fix the bug: ");
293 + // Or block certain inputs
294 + if (event.text.includes("DELETE EVERYTHING")) {
295 + return { block: true };
297 +});
298 +```
300 +## Tool Override
302 +Replace a built-in tool's behavior:
304 +```typescript
305 +pi.on("tool_call", async (event, ctx) => {
306 + if (event.toolName === "write") {
307 + // Add a backup before every write
308 + const filePath = event.input.file_path as string;
309 + if (fs.existsSync(filePath)) {
310 + fs.copyFileSync(filePath, `${filePath}.bak`);
313 +});
314 +```

pi/agent/skills/pi/references/providers.md

Added
new file mode 100644
1 +# Providers & Custom Models
3 +Pi supports subscription-based providers via OAuth, API-key providers via env vars or `auth.json`, and custom providers via `models.json` or extensions.
5 +## Subscription Providers
7 +Use `/login` in interactive mode, then select a provider. The `/login` selector is fuzzy-searchable and shows where each entry's auth comes from (`--api-key`, env var, custom provider) without leaking the secret.
9 +- Anthropic Claude Pro / Max — third-party usage draws from extra usage and is billed per token (suppress the warning via `warnings.anthropicExtraUsage`)
10 +- OpenAI ChatGPT Plus / Pro (Codex)
11 +- GitHub Copilot
13 +Use `/logout` to clear stored OAuth credentials. Pi 0.71.0 removed built-in Google Gemini CLI and Google Antigravity providers.
15 +## API Key Providers
17 +| Provider | Env Var | `auth.json` key |
18 +|----------|---------|-----------------|
19 +| Anthropic | `ANTHROPIC_API_KEY` | `anthropic` |
20 +| Azure OpenAI Responses | `AZURE_OPENAI_API_KEY` | `azure-openai-responses` |
21 +| OpenAI | `OPENAI_API_KEY` | `openai` |
22 +| DeepSeek | `DEEPSEEK_API_KEY` | `deepseek` |
23 +| Google Gemini | `GEMINI_API_KEY` | `google` |
24 +| Mistral | `MISTRAL_API_KEY` | `mistral` |
25 +| Groq | `GROQ_API_KEY` | `groq` |
26 +| Cerebras | `CEREBRAS_API_KEY` | `cerebras` |
27 +| Cloudflare AI Gateway | `CLOUDFLARE_API_KEY` (+ `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_GATEWAY_ID`) | `cloudflare-ai-gateway` |
28 +| Cloudflare Workers AI | `CLOUDFLARE_API_KEY` (+ `CLOUDFLARE_ACCOUNT_ID`) | `cloudflare-workers-ai` |
29 +| xAI | `XAI_API_KEY` | `xai` |
30 +| OpenRouter | `OPENROUTER_API_KEY` | `openrouter` |
31 +| Vercel AI Gateway | `AI_GATEWAY_API_KEY` | `vercel-ai-gateway` |
32 +| ZAI | `ZAI_API_KEY` | `zai` |
33 +| OpenCode Zen | `OPENCODE_API_KEY` | `opencode` |
34 +| OpenCode Go | `OPENCODE_API_KEY` | `opencode-go` |
35 +| Hugging Face | `HF_TOKEN` | `huggingface` |
36 +| Fireworks | `FIREWORKS_API_KEY` | `fireworks` |
37 +| Together AI | `TOGETHER_API_KEY` | `together` |
38 +| Kimi For Coding | `KIMI_API_KEY` | `kimi-coding` |
39 +| MiniMax | `MINIMAX_API_KEY` | `minimax` |
40 +| MiniMax (China) | `MINIMAX_CN_API_KEY` | `minimax-cn` |
41 +| Xiaomi MiMo | `XIAOMI_API_KEY` | `xiaomi` |
42 +| Xiaomi MiMo Token Plan (CN/AMS/SGP) | `XIAOMI_TOKEN_PLAN_{CN,AMS,SGP}_API_KEY` | `xiaomi-token-plan-{cn,ams,sgp}` |
44 +## Auth File
46 +`~/.pi/agent/auth.json` stores API keys and OAuth tokens with `0600` permissions:
48 +```json
50 + "anthropic": { "type": "api_key", "key": "sk-ant-..." },
51 + "openai": { "type": "api_key", "key": "!op read 'OpenAI API Key'" },
52 + "google": { "type": "api_key", "key": "GEMINI_API_KEY" }
54 +```
56 +`key` values can be:
58 +- A literal secret
59 +- An environment variable name
60 +- A shell command prefixed with `!`
62 +## Credential Resolution Order
64 +1. `--api-key`
65 +2. `auth.json`
66 +3. Environment variables
67 +4. Custom provider keys from `models.json`
69 +## Cloud Providers
71 +### Azure OpenAI
73 +```bash
74 +export AZURE_OPENAI_API_KEY=...
75 +export AZURE_OPENAI_BASE_URL=https://your-resource.openai.azure.com
76 +# Cognitive Services endpoints are also supported and auto-normalized to /openai/v1:
77 +# export AZURE_OPENAI_BASE_URL=https://your-resource.cognitiveservices.azure.com
78 +# Or supply the resource name only:
79 +export AZURE_OPENAI_RESOURCE_NAME=your-resource
81 +export AZURE_OPENAI_API_VERSION=2024-02-01
82 +export AZURE_OPENAI_DEPLOYMENT_NAME_MAP=gpt-4o=my-gpt4o
83 +```
85 +### Amazon Bedrock
87 +Pi supports standard AWS auth flows:
89 +- `AWS_PROFILE`
90 +- `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`
91 +- `AWS_BEARER_TOKEN_BEDROCK`
93 +Useful extras:
95 +- `AWS_REGION`
96 +- `AWS_BEDROCK_FORCE_CACHE=1` for application inference profiles
97 +- `AWS_ENDPOINT_URL_BEDROCK_RUNTIME` / `AWS_BEDROCK_SKIP_AUTH` / `AWS_BEDROCK_FORCE_HTTP1` for proxies
99 +### Cloudflare AI Gateway / Workers AI
101 +`/login` stores `CLOUDFLARE_API_KEY`. Account ID (and gateway slug for AI Gateway) must be set as env vars:
103 +```bash
104 +export CLOUDFLARE_ACCOUNT_ID=...
105 +export CLOUDFLARE_GATEWAY_ID=... # AI Gateway only
107 +pi --provider cloudflare-ai-gateway --model "claude-sonnet-4-5"
108 +pi --provider cloudflare-workers-ai --model "@cf/moonshotai/kimi-k2.6"
109 +```
111 +### Google Vertex AI
113 +Use ADC:
115 +```bash
116 +gcloud auth application-default login
117 +export GOOGLE_CLOUD_PROJECT=your-project
118 +export GOOGLE_CLOUD_LOCATION=us-central1
119 +```
121 +## Custom Providers via `models.json`
123 +Use `models.json` for OpenAI-compatible, Anthropic-compatible, Google-compatible, or other supported APIs:
125 +```json
127 + "providers": [
129 + "name": "ollama",
130 + "baseUrl": "http://localhost:11434/v1",
131 + "api": "openai-completions",
132 + "apiKey": "unused",
133 + "models": [
135 + "id": "llama3.2",
136 + "name": "Llama 3.2",
137 + "contextWindow": 128000,
138 + "maxTokens": 4096,
139 + "input": ["text"],
140 + "thinkingLevelMap": {
141 + "off": null,
142 + "minimal": "low",
143 + "low": "low",
144 + "medium": "medium",
145 + "high": "high",
146 + "xhigh": "high"
153 +```
155 +Common `api` values:
157 +- `"openai-completions"`
158 +- `"openai-responses"`
159 +- `"anthropic-messages"`
160 +- `"google-generative-ai"`
161 +- `"google-vertex"`
162 +- `"azure-openai-responses"`
163 +- `"mistral-conversations"`
164 +- `"bedrock-converse-stream"`
166 +### Model & Compatibility Knobs
168 +- `thinkingLevelMap` (Pi 0.72) replaces `compat.reasoningEffortMap`. Map pi levels (`off`/`minimal`/`low`/`medium`/`high`/`xhigh`) to provider values; use `null` to hide a level.
169 +- `openRouterRouting` is forwarded as-is in the OpenRouter `provider` field (fallbacks, ZDR, ignore lists, throughput/latency).
170 +- Advanced `compat` flags exist for proxy quirks (`cacheControlFormat`, `supportsLongCacheRetention`, `supportsEagerToolInputStreaming`, `sendSessionIdHeader`, `sendSessionAffinityHeaders`). See [Pi `docs/models.md`](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/models.md) when a proxy rejects pi's defaults.
172 +## Custom Providers via Extensions
174 +Use extensions when you need custom streaming, custom headers, OAuth/device-flow logic, or want to override an existing provider's `baseUrl`/`headers`:
176 +```typescript
177 +// Full registration
178 +pi.registerProvider("my-provider", {
179 + name: "My Provider", // optional friendly /login label
180 + baseUrl: "https://api.example.com",
181 + api: "openai-completions",
182 + apiKey: "MY_PROVIDER_KEY",
183 + models: [
185 + id: "my-model",
186 + name: "My Model",
187 + contextWindow: 128000,
188 + maxTokens: 4096,
189 + baseUrl: "https://us-east.api.example.com", // per-model override
190 + },
191 + ],
192 +});
194 +// Override-only: re-route an existing built-in provider through a proxy
195 +pi.registerProvider("anthropic", { baseUrl: "https://proxy.example.com" });
196 +```
198 +## SDK / Extension Auth Lookup
200 +If extension or SDK code needs auth for a specific model request, use `getApiKeyAndHeaders(model)` rather than the removed `getApiKey(model)`:
202 +```typescript
203 +const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
204 +if (!auth.ok) throw new Error(auth.error);
206 +const { apiKey, headers } = auth;
207 +```
209 +This matters for providers whose headers or auth values resolve dynamically on every request.

pi/agent/skills/pi/references/sdk.md

Added
new file mode 100644
1 +# SDK
3 +The SDK embeds Pi in Node.js applications via `createAgentSession()`. Use `createAgentSessionRuntime()` when you need `/new`, `/resume`, `/fork`, or import-style session replacement.
5 +## Installation
7 +```bash
8 +npm install @earendil-works/pi-coding-agent
9 +```
11 +## Quick Start
13 +```typescript
14 +import {
15 + AuthStorage,
16 + createAgentSession,
17 + ModelRegistry,
18 + SessionManager,
19 +} from "@earendil-works/pi-coding-agent";
21 +const authStorage = AuthStorage.create();
22 +const modelRegistry = ModelRegistry.create(authStorage);
24 +const { session } = await createAgentSession({
25 + sessionManager: SessionManager.inMemory(),
26 + authStorage,
27 + modelRegistry,
28 +});
30 +session.subscribe((event) => {
31 + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
32 + process.stdout.write(event.assistantMessageEvent.delta);
33 + }
34 +});
36 +await session.prompt("What files are in the current directory?");
37 +```
39 +Run with `npx tsx my-script.ts`.
41 +**Important:** `ModelRegistry` no longer has a public constructor. Use `ModelRegistry.create(authStorage, modelsJsonPath?)` for file-backed registries or `ModelRegistry.inMemory(authStorage)` for built-in models only.
43 +## Key Imports
45 +```typescript
46 +import {
47 + AuthStorage,
48 + createAgentSession,
49 + DefaultResourceLoader,
50 + defineTool,
51 + ModelRegistry,
52 + SessionManager,
53 +} from "@earendil-works/pi-coding-agent";
54 +import { getModel } from "@earendil-works/pi-ai";
55 +```
57 +## Core Options
59 +```typescript
60 +const cwd = "/path/to/project";
61 +const authStorage = AuthStorage.create();
62 +const modelRegistry = ModelRegistry.create(authStorage);
64 +const { session } = await createAgentSession({
65 + cwd,
66 + agentDir: "~/.pi/agent",
67 + authStorage,
68 + modelRegistry,
69 + model: getModel("anthropic", "claude-opus-4-7"),
70 + thinkingLevel: "medium",
71 + scopedModels: [
72 + { model: getModel("anthropic", "claude-opus-4-7"), thinkingLevel: "high" },
73 + ],
74 + tools: ["read", "bash", "edit", "write"],
75 + customTools: [/* defineTool(...) entries */],
76 + resourceLoader: new DefaultResourceLoader(),
77 + sessionManager: SessionManager.inMemory(),
78 + shouldStopAfterTurn: (state) => state.turnCount >= 5,
79 +});
80 +```
82 +Notes:
84 +- `cwd` and `agentDir` control default resource discovery when using `DefaultResourceLoader`.
85 +- Pi 0.68.0 changed the SDK `tools` option from `Tool[]` to a `string[]` allowlist of built-in, extension, and custom tool names. Use `noTools: "builtin"` to disable built-ins while keeping extension/custom tools enabled, or `noTools: "all"` for none.
86 +- `customTools` accepts `ToolDefinition[]`. Build them with `defineTool({...})` for full TypeScript inference.
87 +- The `create*Tool(cwd)` factories still exist for code that needs explicit `AgentTool` instances (e.g. when wiring tools into pi-agent-core directly), but they are no longer the value passed to `createAgentSession({ tools })`.
88 +- `DefaultResourceLoader` loads extensions, skills, prompt templates, themes, and context files. Replace it to drive resource discovery from custom sources (and it must implement `loadProjectContextFiles()` if you want `AGENTS.md`/`CLAUDE.md` discovery; that helper is also exported standalone).
89 +- Pass `shouldStopAfterTurn(state) => boolean` (Pi 0.72.0) to exit the agent loop gracefully after a completed turn.
91 +## Prompting & Queueing
93 +```typescript
94 +await session.prompt("Review the current directory");
96 +// During streaming, choose how the new prompt should queue.
97 +await session.prompt("Stop and do this instead", { streamingBehavior: "steer" });
98 +await session.prompt("After you finish, also check tests", { streamingBehavior: "followUp" });
100 +await session.steer("Use a smaller diff");
101 +await session.followUp("Summarize the changes afterward");
102 +```
104 +`prompt()` expands file-based prompt templates. During active streaming, calling it without `streamingBehavior` throws.
106 +## Session Runtime
108 +Pi 0.65.0 moved session replacement off `AgentSession` and onto `AgentSessionRuntime`. Use the runtime when you need `newSession()`, `switchSession()`, `fork()`, or `importFromJsonl()`.
110 +```typescript
111 +import {
112 + type CreateAgentSessionRuntimeFactory,
113 + createAgentSessionFromServices,
114 + createAgentSessionRuntime,
115 + createAgentSessionServices,
116 + getAgentDir,
117 + SessionManager,
118 +} from "@earendil-works/pi-coding-agent";
120 +const createRuntime: CreateAgentSessionRuntimeFactory = async ({
121 + cwd,
122 + sessionManager,
123 + sessionStartEvent,
124 +}) => {
125 + const services = await createAgentSessionServices({ cwd });
126 + return {
127 + ...(await createAgentSessionFromServices({
128 + services,
129 + sessionManager,
130 + sessionStartEvent,
131 + })),
132 + services,
133 + diagnostics: services.diagnostics,
134 + };
137 +const runtime = await createAgentSessionRuntime(createRuntime, {
138 + cwd: process.cwd(),
139 + agentDir: getAgentDir(),
140 + sessionManager: SessionManager.create(process.cwd()),
141 +});
143 +let session = runtime.session;
144 +let unsubscribe = session.subscribe(() => {});
146 +await runtime.newSession();
147 +await runtime.fork("entry-id", { position: "at" }); // "before" | "at" — `at` powers /clone
149 +unsubscribe();
150 +session = runtime.session;
151 +unsubscribe = session.subscribe(() => {});
152 +```
154 +Notes:
156 +- `runtime.session` changes after replacement. Re-subscribe to session-local events after `newSession()`, `switchSession()`, `fork()`, or `importFromJsonl()`.
157 +- Cross-cwd replacement rebuilds cwd-bound services and session configuration.
158 +- `runtime.diagnostics` carries startup and replacement diagnostics instead of printing or exiting directly.
160 +## Session Surface
162 +```typescript
163 +await session.navigateTree("entry-id", { summarize: true });
164 +await session.compact("Summarize design decisions only");
166 +await session.abort();
167 +await session.agent.waitForIdle();
168 +session.dispose();
169 +```
171 +Use `runtime.newSession()`, `runtime.switchSession()`, and `runtime.fork()` for session replacement. Keep `navigateTree()` and `compact()` on the live `session`.
173 +Useful state:
175 +- `session.sessionFile` / `session.sessionId`
176 +- `session.agent.state.messages`
177 +- `session.model`
178 +- `session.thinkingLevel`
180 +## Events
182 +```typescript
183 +session.subscribe((event) => {
184 + switch (event.type) {
185 + case "message_update":
186 + if (event.assistantMessageEvent.type === "text_delta") {
187 + process.stdout.write(event.assistantMessageEvent.delta);
189 + break;
190 + case "tool_execution_start":
191 + case "tool_execution_update":
192 + case "tool_execution_end":
193 + case "agent_start":
194 + case "agent_end":
195 + case "turn_start":
196 + case "turn_end":
197 + case "queue_update":
198 + case "compaction_start":
199 + case "compaction_end":
200 + case "auto_retry_start":
201 + case "auto_retry_end":
202 + break;
204 +});
205 +```
207 +## Resource Loader Hooks
209 +`DefaultResourceLoader` supports overrides for extensions, skills, prompts, themes, and context files. Common patterns:
211 +- Add inline extension factories
212 +- Override `agentsFiles` to inject virtual `AGENTS.md` content
213 +- Add custom skills or prompt templates without touching disk
214 +- Share an event bus between the host app and loaded extensions
216 +## Standalone Custom Tools
218 +Use `defineTool()` when you want a reusable custom tool definition outside `pi.registerTool(...)`:
220 +```typescript
221 +import { defineTool } from "@earendil-works/pi-coding-agent";
222 +import { Type } from "typebox";
224 +const myTool = defineTool({
225 + name: "my_tool",
226 + label: "My Tool",
227 + description: "Does something useful",
228 + parameters: Type.Object({
229 + input: Type.String({ description: "Input value" }),
230 + }),
231 + async execute(_toolCallId, params) {
232 + return {
233 + content: [{ type: "text", text: `Result: ${params.input}` }],
234 + details: {},
235 + // terminate: true, // optional — end the tool batch without an automatic follow-up LLM turn
236 + };
237 + },
238 +});
239 +```
241 +Pass these via `customTools: [myTool]` on `createAgentSession()` or via `pi.registerTool(myTool)` from inside an extension.

pi/agent/skills/pi/references/settings.md

Added
new file mode 100644
1 +# Settings
3 +Pi uses JSON settings files with project settings overriding global settings:
5 +| Location | Scope |
6 +|----------|-------|
7 +| `~/.pi/agent/settings.json` | Global |
8 +| `.pi/settings.json` | Project |
10 +Edit JSON directly or use `/settings` for common interactive options.
12 +## Model & Thinking
14 +```json
16 + "defaultProvider": "anthropic",
17 + "defaultModel": "claude-sonnet-4-20250514",
18 + "defaultThinkingLevel": "medium",
19 + "hideThinkingBlock": false,
20 + "thinkingBudgets": {
21 + "minimal": 1024,
22 + "low": 4096,
23 + "medium": 10240,
24 + "high": 32768
25 + }
27 +```
29 +- Thinking levels: `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`
30 +- `hideThinkingBlock` hides visible thinking output in the UI
32 +## UI & Display
34 +```json
36 + "theme": "dark",
37 + "quietStartup": false,
38 + "collapseChangelog": false,
39 + "doubleEscapeAction": "tree",
40 + "treeFilterMode": "default",
41 + "editorPaddingX": 0,
42 + "autocompleteMaxVisible": 5,
43 + "showHardwareCursor": false
45 +```
47 +- `doubleEscapeAction`: `"tree"`, `"fork"`, or `"none"`
48 +- `treeFilterMode`: `"default"`, `"no-tools"`, `"user-only"`, `"labeled-only"`, or `"all"`
49 +- In `/tree`, `Shift+T` toggles timestamps on entry labels
51 +## Compaction, Branch Summary, Retry
53 +```json
55 + "compaction": {
56 + "enabled": true,
57 + "reserveTokens": 16384,
58 + "keepRecentTokens": 20000
59 + },
60 + "branchSummary": {
61 + "reserveTokens": 16384,
62 + "skipPrompt": false
63 + },
64 + "retry": {
65 + "enabled": true,
66 + "maxRetries": 3,
67 + "baseDelayMs": 2000,
68 + "maxDelayMs": 60000,
69 + "provider": {
70 + "timeoutMs": 0,
71 + "maxRetries": 0,
72 + "maxRetryDelayMs": 0
73 + }
74 + }
76 +```
78 +Notes:
80 +- `retry.maxDelayMs = 0` disables the cap on server-requested retry delays.
81 +- `retry.provider.*` (Pi 0.70.1) controls the underlying provider SDK's request timeout and retry/backoff — useful for slow local LLMs and flaky proxies. Pi forwards these into `streamSimple` request options when set.
82 +- `branchSummary.skipPrompt` skips the confirmation step when navigating with `/tree`.
84 +## Message Delivery
86 +```json
88 + "steeringMode": "one-at-a-time",
89 + "followUpMode": "one-at-a-time",
90 + "transport": "sse"
92 +```
94 +- `steeringMode` and `followUpMode`: `"all"` or `"one-at-a-time"`
95 +- `transport`: `"sse"`, `"websocket"`, or `"auto"`
97 +## Terminal, Images, and Shell
99 +```json
101 + "terminal": {
102 + "showImages": true,
103 + "clearOnShrink": false,
104 + "showTerminalProgress": false,
105 + "imageWidthCells": 60
106 + },
107 + "images": {
108 + "autoResize": true,
109 + "blockImages": false
110 + },
111 + "shellPath": "/bin/bash",
112 + "shellCommandPrefix": "",
113 + "npmCommand": ["mise", "exec", "node@20", "--", "npm"]
115 +```
117 +- `npmCommand` is argv-style and is used for npm lookup/install operations, including git-package installs.
118 +- `terminal.showTerminalProgress` (default `false` since Pi 0.70.0) toggles OSC 9;4 progress reporting in supporting terminals (iTerm2, WezTerm, Windows Terminal, Kitty).
119 +- `terminal.imageWidthCells` (Pi 0.68.1) caps inline tool-output image width in terminal cells.
121 +## Warnings & Telemetry
123 +```json
125 + "warnings": { "anthropicExtraUsage": true },
126 + "enableInstallTelemetry": true
128 +```
130 +`enableInstallTelemetry` sends an anonymous version ping to `pi.dev` once per local changelog advance (interactive mode only). `PI_OFFLINE=1` or `PI_TELEMETRY=0` disable it.
132 +## Sessions, Model Cycling, Markdown
134 +```json
136 + "sessionDir": ".pi/sessions",
137 + "enabledModels": ["claude-*", "gpt-4o", "gemini-2*"],
138 + "markdown": {
139 + "codeBlockIndent": " "
142 +```
144 +When multiple sources specify a session directory, `--session-dir` takes precedence over `sessionDir` in settings. Pi 0.65.0 removed the old `session_directory` extension/settings hook.
146 +## Resources
148 +These settings control what Pi loads from disk or packages:
150 +```json
152 + "packages": [
153 + "npm:@foo/pi-tools",
155 + "source": "git:github.com/user/repo@v1",
156 + "skills": ["brave-search"],
157 + "extensions": []
159 + ],
160 + "extensions": ["./extensions/my-ext.ts"],
161 + "skills": ["./skills", "../.claude/skills"],
162 + "prompts": ["./prompts"],
163 + "themes": ["./themes"],
164 + "enableSkillCommands": true
166 +```
168 +Notes:
170 +- Paths in `~/.pi/agent/settings.json` resolve relative to `~/.pi/agent`.
171 +- Paths in `.pi/settings.json` resolve relative to `.pi`.
172 +- `packages` loads npm/git/local Pi packages.
173 +- `extensions`, `skills`, `prompts`, and `themes` are for local files/directories.
174 +- `enableSkillCommands` controls `/skill:name` registration.
176 +## Include / Exclude Patterns
178 +Arrays support filtering:
180 +```json
182 + "skills": [
183 + "./skills",
184 + "!legacy-skill",
185 + "+must-load-skill",
186 + "-blocked-skill"
189 +```
191 +- `!pattern` excludes glob matches
192 +- `+path` force-includes an exact path
193 +- `-path` force-excludes an exact path
195 +## CLI Flags
197 +Run `pi --help` for the authoritative list. Most commonly:
199 +```text
200 +pi [options] [@files...] [messages...]
202 +# package commands: install/remove/uninstall/update/list/config (all support -l for project scope)
204 +# modes
205 +-p, --print single-shot text output
206 +--mode json|rpc newline-delimited events / JSON-RPC over stdio
207 +--export <in> [out] export a session to HTML
209 +# model
210 +--provider <name> e.g. anthropic, openai, google
211 +--model <pattern> supports provider/id and optional :<thinking>
212 +--api-key <key>
213 +--thinking off|minimal|low|medium|high|xhigh
214 +--models <patterns> Ctrl+P cycling allowlist
215 +--list-models [search]
217 +# sessions
218 +-c, --continue continue most recent session
219 +-r, --resume browse and select
220 +--session <path|id>
221 +--fork <path|id>
222 +--session-dir <dir>
223 +--no-session ephemeral
225 +# tools and resources
226 +--tools <list>, -t name allowlist (read,bash,edit,write,grep,find,ls,...)
227 +--no-tools, -nt disable everything
228 +--no-builtin-tools, -nbt disable built-ins, keep extension/custom
229 +-e, --extension <source> repeatable; npm/git/path
230 +--skill <path> repeatable
231 +--prompt-template <path> repeatable
232 +--theme <path> repeatable
233 +--no-extensions / --no-skills / --no-prompt-templates / --no-themes
234 +--no-context-files, -nc skip AGENTS.md / CLAUDE.md discovery
236 +# prompts and misc
237 +--system-prompt <text> replace default
238 +--append-system-prompt <text> repeatable; appended with double newlines
239 +--verbose
240 +```
242 +## Environment Variables
244 +| Variable | Effect |
245 +|----------|--------|
246 +| `PI_CODING_AGENT_DIR` | Override the global agent directory |
247 +| `PI_CODING_AGENT_SESSION_DIR` | Override session storage; `--session-dir` still wins |
248 +| `PI_PACKAGE_DIR` | Override package storage directory |
249 +| `PI_SKIP_VERSION_CHECK` | Skip the `pi.dev` latest-version request at startup |
250 +| `PI_OFFLINE` | Disable all startup network operations (update checks, telemetry) |
251 +| `PI_TELEMETRY` | Force install telemetry on/off (`1`/`0`); does not gate update checks |
252 +| `PI_CACHE_RETENTION` | Set to `long` for extended prompt-cache retention where supported |
253 +| `PI_OAUTH_CALLBACK_HOST` | Bind the OAuth callback server to a custom interface |
254 +| `PI_CODING_AGENT=true` | Set automatically at startup so subprocesses can detect Pi |
255 +| `VISUAL`, `EDITOR` | External editor for `Ctrl+G` |
256 +| Provider API key env vars | See `references/providers.md` |
258 +## Practical Notes
260 +- Project settings are good for shared package/resource configuration.
261 +- Global settings are better for personal credentials, UI preferences, and model defaults.
262 +- Nested objects are merged; project keys override the same global keys.

pi/agent/skills/pi/references/skills.md

Added
new file mode 100644
1 +# Skills
3 +Skills are self-contained capability packages that Pi loads on demand. Pi follows the [Agent Skills specification](https://agentskills.io/specification) and stays fairly lenient, warning on many violations instead of hard-failing.
5 +## How Skills Work
7 +1. At startup, Pi scans skill locations and extracts each skill's name and description.
8 +2. The system prompt includes those skills in XML form.
9 +3. When a task matches, the agent uses `read` to load the full `SKILL.md`.
10 +4. The skill body can route to `references/`, `scripts/`, or `assets/` files via relative paths.
12 +This is progressive disclosure: descriptions stay in prompt context, full instructions are loaded only when needed.
14 +## Locations
16 +Pi discovers skills from:
18 +- Global:
19 + - `~/.pi/agent/skills/`
20 + - `~/.agents/skills/`
21 +- Project:
22 + - `.pi/skills/`
23 + - `.agents/skills/` in `cwd` and ancestor directories
24 +- Packages:
25 + - `skills/` directories or `pi.skills` entries in `package.json`
26 +- Settings:
27 + - `skills` array in `settings.json`
28 +- CLI:
29 + - `--skill <path>` (repeatable, still additive even with `--no-skills`)
31 +Discovery rules:
33 +- Root `.md` files in `.pi/skills/` and `~/.pi/agent/skills/` are loaded as standalone skills.
34 +- Directories containing `SKILL.md` are discovered recursively in all skill locations.
35 +- Root `.md` files in `.agents/skills/` locations are ignored.
37 +## Skill Commands
39 +Every skill can register as `/skill:name` when `enableSkillCommands` is enabled:
41 +```text
42 +/skill:my-skill
43 +/skill:my-skill extra arguments
44 +```
46 +Arguments after the command are appended to the skill body as `User: ...`.
48 +## Directory Structure
50 +```text
51 +my-skill/
52 +├── SKILL.md
53 +├── scripts/
54 +│ └── process.sh
55 +├── references/
56 +│ └── api.md
57 +└── assets/
58 + └── template.json
59 +```
61 +## SKILL.md Format
63 +```markdown
64 +---
65 +name: my-skill
66 +description: "What this skill does and when to use it. Be specific."
67 +license: MIT
68 +compatibility: "Requires bash"
69 +---
71 +# My Skill
73 +## Setup
75 +Run `npm install` in this directory before first use.
77 +## Usage
79 +Read `references/api.md` for the full details.
80 +```
82 +## Frontmatter
84 +| Field | Required | Notes |
85 +|-------|----------|-------|
86 +| `name` | Yes | 1-64 chars, lowercase letters/numbers/hyphens, must match parent dir |
87 +| `description` | Yes | Max 1024 chars; primary trigger text |
88 +| `license` | No | License name or bundled reference |
89 +| `compatibility` | No | Environment requirements |
90 +| `metadata` | No | Arbitrary key-value mapping |
91 +| `allowed-tools` | No | Experimental, space-delimited list of pre-approved tools |
92 +| `disable-model-invocation` | No | Hides skill from system prompt; user must use `/skill:name` |
94 +## Writing Good Skills
96 +- Make the description specific and assertive. It is the main trigger.
97 +- Keep `SKILL.md` focused and move bulk detail into `references/`.
98 +- Use imperative instructions and explain why when it changes the workflow.
99 +- Use relative links/paths so the agent can open supporting files reliably.
100 +- Put deterministic helper logic in `scripts/` instead of asking the model to recreate it.
102 +## Using Skills from Other Harnesses
104 +To reuse Claude Code or Codex skill directories, add them to settings:
106 +```json
108 + "skills": ["~/.claude/skills", "~/.codex/skills"]
110 +```
112 +## Validation
114 +Pi warns on most issues but still loads the skill when possible:
116 +- Name and parent-directory mismatch
117 +- Name too long or invalid
118 +- Description too long
119 +- Duplicate names, where first discovered wins
121 +One hard failure remains: a skill without `description` is not loaded.