@zew1me/pi-subagents 0.0.0-stage → 0.1.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -2
- package/dist/ATTRIBUTION.md +320 -0
- package/dist/LICENSE +21 -0
- package/dist/extensions/subagents/auth-bridge.ts +52 -0
- package/dist/extensions/subagents/helpers.ts +251 -0
- package/dist/extensions/subagents/index.ts +727 -0
- package/dist/extensions/subagents/rpc.ts +845 -0
- package/package.json +40 -4
package/README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zew1me/pi-subagents
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Pi package for the subagents extension.
|
|
4
|
+
|
|
5
|
+
Install with:
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pi install npm:@zew1me/pi-subagents@alpha
|
|
9
|
+
```
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
# Attribution
|
|
2
|
+
|
|
3
|
+
## Subagent context modes from `nigel-upstart/pi-buildout`
|
|
4
|
+
|
|
5
|
+
- Source: `nigel-upstart/pi-buildout`
|
|
6
|
+
- Canonical repository: <https://github.com/nigel-upstart/pi-buildout>
|
|
7
|
+
- Revision ported: `fe4e325a22cb4489b1c7083b84c5dcf6c79e3f55` (#138)
|
|
8
|
+
- License declared by the source: MIT (Copyright 2026 Nigel Stuke)
|
|
9
|
+
|
|
10
|
+
Copied code: the optional `contextMode` parameter, task-only creation path, mode metadata, documentation, and regression
|
|
11
|
+
tests in `extensions/subagents`. The default `task_compacted` behavior is preserved; `none` skips parent conversation
|
|
12
|
+
access and compaction without changing filesystem, credential, project-instruction, skill, or extension inheritance.
|
|
13
|
+
|
|
14
|
+
The fork's router and OpenTelemetry extensions, generic signaling protocol, final-only wait behavior, newer Pi patch
|
|
15
|
+
sets, internal release packaging, and dependency overrides were intentionally not adopted. This is a direct code port,
|
|
16
|
+
not solely conceptual inspiration; the repository's existing MIT notice covers the copied material.
|
|
17
|
+
|
|
18
|
+
## Public npm packaging and release automation
|
|
19
|
+
|
|
20
|
+
- Source: `nigel-upstart/pi-buildout`
|
|
21
|
+
- Canonical URL: <https://github.com/nigel-upstart/pi-buildout>
|
|
22
|
+
- Revision reviewed: `5ed4c390ee13fd8c491d964008cf37b459b621d9`
|
|
23
|
+
- Declared license: MIT (Nigel Stuke, 2026); the root `LICENSE` preserves that notice.
|
|
24
|
+
|
|
25
|
+
The separate per-extension package directories, explicit Pi entrypoints, host-provided peer dependencies, minimal
|
|
26
|
+
`prepack` staging, inclusion of license/attribution files, and separate patch-only CLI were informed by the fork's
|
|
27
|
+
`packages/`, `scripts/stage-release-package.mjs`, and package tests. The staging helper structure and portions of the
|
|
28
|
+
archive assertions are modified adaptations of that MIT-licensed code, reduced to this repository's extension set and
|
|
29
|
+
installer; the root `LICENSE` preserves its notice. Public manifests and version-driven release planning/publishing
|
|
30
|
+
logic are authored here. No router, OTel, telemetry defaults, private package names, CodeArtifact endpoints, AWS
|
|
31
|
+
credentials, internal documentation, or manual-only alpha-release restriction are adopted.
|
|
32
|
+
|
|
33
|
+
- Pi package documentation: <https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/packages.md>
|
|
34
|
+
(installed `@earendil-works/pi-coding-agent@1.3.0`; MIT).
|
|
35
|
+
- npm trusted publishing guidance: <https://docs.npmjs.com/trusted-publishers/>
|
|
36
|
+
- GitHub Actions concurrency guidance:
|
|
37
|
+
<https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency>
|
|
38
|
+
|
|
39
|
+
These documentation sources informed explicit resource manifests, runtime/host dependency separation, npm OIDC
|
|
40
|
+
permissions and provenance, and queued non-cancelling release runs. Their prose and example workflows were not copied;
|
|
41
|
+
the workflow extends this repository's existing quality gate. Token-based publishing, git-tag-triggered releases, and Pi
|
|
42
|
+
runtime patching during npm installation were intentionally not adopted.
|
|
43
|
+
|
|
44
|
+
## Subagent implementations
|
|
45
|
+
|
|
46
|
+
The subagent extension in [`extensions/subagents`](extensions/subagents) was informed by the two implementations
|
|
47
|
+
identified by the project owner. The implementation in this repository is original code, but it deliberately carries
|
|
48
|
+
forward architectural ideas and operational lessons from both projects.
|
|
49
|
+
|
|
50
|
+
## `nicobailon/pi-subagents`
|
|
51
|
+
|
|
52
|
+
- Repository: <https://github.com/nicobailon/pi-subagents>
|
|
53
|
+
- Initial revision reviewed: `315e1eb1482c4ac2d912a8d95aac4287dc7e60ac`
|
|
54
|
+
- Latest revision reviewed: `1b64c35cc221a23a5b8293deb108a30c0646f520` (`0.48.0` plus unreleased changes)
|
|
55
|
+
- License declared by its package: MIT
|
|
56
|
+
|
|
57
|
+
Ideas and lessons used:
|
|
58
|
+
|
|
59
|
+
- Treat a subagent as a separate Pi process and session rather than an in-process prompt persona.
|
|
60
|
+
- Keep asynchronous child work observable through structured state and transcript tails.
|
|
61
|
+
- Expose explicit lifecycle controls for status inspection, steering, interruption, and stopping.
|
|
62
|
+
- Bound child protocol and diagnostic output so a malformed or noisy child cannot grow parent memory without limit.
|
|
63
|
+
- Make recursive delegation safe by scoping child registries and controls to a parent/child tree rather than a global
|
|
64
|
+
fleet.
|
|
65
|
+
- Validate model choices against Pi's live model registry and preserve a clear fallback path.
|
|
66
|
+
- Clean up child processes and extension-owned resources during Pi session shutdown/reload.
|
|
67
|
+
- Keep the child JSONL protocol bounded while allowing Pi-sized resized-image events; this repository uses a 16 MiB
|
|
68
|
+
per-line ceiling.
|
|
69
|
+
- Sanitize child-controlled transcript and diagnostic text before terminal rendering while retaining the original
|
|
70
|
+
bounded text in the model-facing tool result.
|
|
71
|
+
|
|
72
|
+
We intentionally did **not** reproduce its agent profiles, chain/parallel workflow engine, intercom/supervisor channel,
|
|
73
|
+
watchdog, artifact protocol, slash-command suite, or TUI fleet. This extension stays between that feature-rich design
|
|
74
|
+
and a one-shot runner.
|
|
75
|
+
|
|
76
|
+
## `elpapi42/pi-minimal-subagent`
|
|
77
|
+
|
|
78
|
+
- Repository: <https://github.com/elpapi42/pi-minimal-subagent>
|
|
79
|
+
- Local revision reviewed: `4c847a37b7d675470a8c5eb50d736d11ceac910a`
|
|
80
|
+
- License declared by its package: MIT
|
|
81
|
+
|
|
82
|
+
Ideas and lessons used:
|
|
83
|
+
|
|
84
|
+
- Keep the model-facing surface centered on one small `subagent` tool.
|
|
85
|
+
- Let ordinary natural-language requests cause the parent model to delegate; do not require a special slash workflow.
|
|
86
|
+
- Launch child Pi with normal extension/resource discovery by default so configured tools and integrations remain
|
|
87
|
+
available.
|
|
88
|
+
- Resolve the Pi executable robustly when Pi is running either as a standalone executable or through Node.
|
|
89
|
+
- Use process isolation and propagate shutdown/abort behavior instead of sharing an agent session object.
|
|
90
|
+
- Keep task dispatch simple and avoid requiring named role/persona files.
|
|
91
|
+
|
|
92
|
+
We extended that minimal shape with persistent RPC children, task-targeted context compaction, automatic model/effort
|
|
93
|
+
classification, direct-child spying and control, and recursive child creation.
|
|
94
|
+
|
|
95
|
+
## `tintinweb/pi-subagents`
|
|
96
|
+
|
|
97
|
+
- Repository: <https://github.com/tintinweb/pi-subagents>
|
|
98
|
+
- Initial revision reviewed: `c161865a0e8ca12f406041c263ea6c2ca35c74d5` (`0.14.1`)
|
|
99
|
+
- Latest revision reviewed: `4cc473855c2af4f12873c01dad130dd0b3d52639` (`0.15.1`)
|
|
100
|
+
- License: MIT
|
|
101
|
+
|
|
102
|
+
This package was reviewed after the initial implementation as a source of possible follow-up ideas. The review
|
|
103
|
+
considered its in-process SDK sessions, background concurrency queue, graceful turn limits, result/steering tools,
|
|
104
|
+
conversation viewer, context-usage statistics, compact tool-description mode, model-scope guardrail, and resumable
|
|
105
|
+
sessions.
|
|
106
|
+
|
|
107
|
+
Follow-up work adopted three conceptual patterns: explicit, bounded result waiting; richer inspection statistics
|
|
108
|
+
(tokens, cost, context utilization, compactions, and active tool); and treating an output-limit stop with no assistant
|
|
109
|
+
text as a failed child run rather than a successful empty result. They were implemented as original code inside the
|
|
110
|
+
existing single-tool RPC design. No tintinweb code was copied or modified. Major pieces intentionally not adopted
|
|
111
|
+
include named/default agent types, custom agent frontmatter, proactive completion notifications, FleetView/widget UI,
|
|
112
|
+
scheduling, event-bus RPC, persistent memory, worktree isolation, skill preloading, and its three-tool Claude
|
|
113
|
+
Code-compatible surface.
|
|
114
|
+
|
|
115
|
+
## Pi 1.0.3 `/skills` runtime patch
|
|
116
|
+
|
|
117
|
+
- Source: `@earendil-works/pi-coding-agent@1.0.3`
|
|
118
|
+
- Canonical repository: <https://github.com/earendil-works/pi> (`packages/coding-agent`)
|
|
119
|
+
- Upstream revision reviewed: `d78dc83d633229d12f8b79631384c4c2717c399f` (`v1.0.3`), from npm `gitHead`
|
|
120
|
+
- Source archive: `pi-1.0.3-source.tar.gz`, verified against the release's published `SHA256SUMS`
|
|
121
|
+
- License declared by the package: MIT
|
|
122
|
+
|
|
123
|
+
[`pi-overlay/versions/1.0.3/integration.patch`](pi-overlay/versions/1.0.3/integration.patch) adapts the existing opt-in
|
|
124
|
+
skills seam to the MIT-licensed 1.0.3 TypeScript sources and documentation. The generated
|
|
125
|
+
[`skills.patch`](patches/pi-1.0.3/skills.patch) modifies the published resource loader, slash-command list, CLI and
|
|
126
|
+
interactive entry points, and `docs/skills.md`; it adds this repository's original skill-management modules. The patch
|
|
127
|
+
reuses Pi's package/resource discovery, project-trust, and `proper-lockfile` APIs, including the adapted lock pattern
|
|
128
|
+
described under the TypeScript overlay below. It keeps discovered skills catalog-only, enables explicit global,
|
|
129
|
+
repository, and session activation, preserves explicit `--skill` paths when `--no-skills` is used, and leaves Pi's
|
|
130
|
+
unrelated extensions, prompts, themes, packages, providers, trust behavior, and bundled chunks unchanged. It does not
|
|
131
|
+
copy Pi's automatic skill-loading behavior or its runtime implementation into the overlay.
|
|
132
|
+
|
|
133
|
+
The `cli-runtime.js` and `rpc-entry.js` replacements are original wrappers written for this repository, not derived from
|
|
134
|
+
upstream's bundle output; Pi's published `dist/bundle/cli.js` compile-cache loader remains unchanged and is pinned by
|
|
135
|
+
checksum. Source inputs are fetched from the 1.0.3 release archive and npm tarball with committed checksums; no complete
|
|
136
|
+
Pi source checkout is committed.
|
|
137
|
+
|
|
138
|
+
## Pi 1.0.4 `/skills` runtime patch
|
|
139
|
+
|
|
140
|
+
- Source: `@earendil-works/pi-coding-agent@1.0.4`
|
|
141
|
+
- Canonical repository: <https://github.com/earendil-works/pi> (`packages/coding-agent`)
|
|
142
|
+
- Upstream revision reviewed: `7c10bd4337495ee613f2224843ecdf349b80d1df` (`v1.0.4`), from npm `gitHead`
|
|
143
|
+
- Source archive: `pi-1.0.4-source.tar.gz`, verified against the release's published `SHA256SUMS`
|
|
144
|
+
- License declared by the package: MIT
|
|
145
|
+
|
|
146
|
+
[`pi-overlay/versions/1.0.4/integration.patch`](pi-overlay/versions/1.0.4/integration.patch) adapts the opt-in skills
|
|
147
|
+
integration seam to the MIT-licensed 1.0.4 TypeScript sources and documentation. The generated
|
|
148
|
+
[`skills.patch`](patches/pi-1.0.4/skills.patch) modifies Pi's published resource loader, slash-command list, CLI and
|
|
149
|
+
interactive entry points, and skill documentation. It adds this repository's original skill-management modules and
|
|
150
|
+
reuses Pi's package/resource discovery, project-trust, and `proper-lockfile` APIs. It preserves explicit `--skill` with
|
|
151
|
+
`--no-skills`, makes discovered skills catalog-only until activated, and leaves unrelated extensions, prompts, themes,
|
|
152
|
+
packages, providers, trust behavior, and bundled chunks unchanged. Pi's automatic loading of all discovered skills and
|
|
153
|
+
its skill implementation were not copied into the overlay. The original `cli-runtime.js` and `rpc-entry.js` wrappers are
|
|
154
|
+
reused from the earlier patch; the published `dist/bundle/cli.js` loader is unchanged and checksum-pinned. Inputs come
|
|
155
|
+
from the verified release archive and npm tarball; no complete Pi source checkout is committed.
|
|
156
|
+
|
|
157
|
+
## Pi 1.1.0 `/skills` runtime patch
|
|
158
|
+
|
|
159
|
+
- Source: `@earendil-works/pi-coding-agent@1.1.0`
|
|
160
|
+
- Canonical repository: <https://github.com/earendil-works/pi> (`packages/coding-agent`)
|
|
161
|
+
- Upstream revision reviewed: `abe508e1b89912adde45528136c3221eb69acdd7` (`v1.1.0`)
|
|
162
|
+
- Source archive: `pi-1.1.0-source.tar.gz`, verified against the release's published `SHA256SUMS`
|
|
163
|
+
- License declared by the package: MIT
|
|
164
|
+
|
|
165
|
+
[`pi-overlay/versions/1.1.0/integration.patch`](pi-overlay/versions/1.1.0/integration.patch) adapts the opt-in skills
|
|
166
|
+
seam to Pi 1.1.0's MIT-licensed TypeScript sources and documentation. The generated
|
|
167
|
+
[`skills.patch`](patches/pi-1.1.0/skills.patch) modifies the published resource loader, slash-command list, CLI and
|
|
168
|
+
interactive entry points, and skill documentation. It adds this repository's original skill-management modules and
|
|
169
|
+
reuses Pi's package/resource discovery, project-trust, and `proper-lockfile` APIs. It keeps catalog skills inactive
|
|
170
|
+
until explicitly enabled, preserves explicit `--skill` paths with `--no-skills`, and does not copy Pi's automatic skill
|
|
171
|
+
loading or its skill implementation. The original `cli-runtime.js` wrapper reuses Pi's `setupCli()` path; the original
|
|
172
|
+
`rpc-entry.js` wrapper also preserves Pi 1.1.0's process markers and HTTP-dispatcher setup. The published
|
|
173
|
+
`dist/bundle/cli.js` loader remains unchanged and checksum-pinned. No complete Pi source checkout is committed.
|
|
174
|
+
|
|
175
|
+
## Pi 1.3.0 `/skills` runtime patch
|
|
176
|
+
|
|
177
|
+
- Source: `@earendil-works/pi-coding-agent@1.3.0`
|
|
178
|
+
- Canonical repository: <https://github.com/earendil-works/pi> (`packages/coding-agent`)
|
|
179
|
+
- Upstream revision reviewed: `71023aec1546d6d677a65669c5665c0927ce0dd0` (`v1.3.0`), the commit the lightweight release
|
|
180
|
+
tag points to; the npm registry publishes no `gitHead` for this release, and the commit is unsigned
|
|
181
|
+
- Source archive: `pi-1.3.0-source.tar.gz`, verified against the release's published `SHA256SUMS`
|
|
182
|
+
- npm tarball: `pi-coding-agent-1.3.0.tgz`, pinned by SHA-256 and registry integrity
|
|
183
|
+
- License declared by the package: MIT
|
|
184
|
+
|
|
185
|
+
[`pi-overlay/versions/1.3.0/integration.patch`](pi-overlay/versions/1.3.0/integration.patch) is the 1.1.0 seam rebased
|
|
186
|
+
onto Pi 1.3.0's MIT-licensed TypeScript sources and documentation: the added and removed lines are unchanged, and only
|
|
187
|
+
hunk positions and blob indexes differ. The generated [`skills.patch`](patches/pi-1.3.0/skills.patch) modifies the
|
|
188
|
+
published resource loader, slash-command list, CLI and interactive entry points, and skill documentation, within the
|
|
189
|
+
same 48-line seam budget. It adds this repository's original skill-management modules, which compile byte-identically to
|
|
190
|
+
the 1.1.0 output, and reuses Pi's package/resource discovery, project-trust, and `proper-lockfile` APIs. It keeps
|
|
191
|
+
catalog skills inactive until explicitly enabled, preserves explicit `--skill` paths with `--no-skills`, and does not
|
|
192
|
+
copy Pi's automatic skill loading or its skill implementation. The original `cli-runtime.js` and `rpc-entry.js` wrappers
|
|
193
|
+
are reused byte-for-byte from 1.1.0 because Pi 1.3.0's `src/cli.ts`, `src/rpc-entry.ts`, and `src/cli/setup.ts` are
|
|
194
|
+
unchanged. The published `dist/bundle/cli.js` loader remains unchanged and checksum-pinned. Upstream changes elsewhere
|
|
195
|
+
in 1.3.0, including those near the seams, were not adopted. No complete Pi source checkout is committed.
|
|
196
|
+
|
|
197
|
+
## Pi 1.5.2 `/skills` runtime patch
|
|
198
|
+
|
|
199
|
+
- Source: [nigel-upstart/pi-buildout](https://github.com/nigel-upstart/pi-buildout), commit
|
|
200
|
+
`0704169310246b2b4fe8144f94ad4314c4a382e3`, MIT.
|
|
201
|
+
- Upstream Pi: [earendil-works/pi](https://github.com/earendil-works/pi), release `v1.5.2`, commit
|
|
202
|
+
`b4afdddf44e059c67ccf5097e5317d913521b470`, MIT.
|
|
203
|
+
|
|
204
|
+
The 1.5.2 integration seam, entrypoint wrappers, and pinned build inputs are adapted from the downstream patch, which
|
|
205
|
+
modifies Pi source and documentation. The generated runtime patch uses this repository's shared overlay and portable
|
|
206
|
+
path behavior rather than copying downstream's generated skill implementation. Other downstream changes and a complete
|
|
207
|
+
Pi source checkout were not adopted.
|
|
208
|
+
|
|
209
|
+
## Pi 1.4.0 `/skills` runtime patch
|
|
210
|
+
|
|
211
|
+
- Source: `@earendil-works/pi-coding-agent@1.4.0`
|
|
212
|
+
- Canonical repository: <https://github.com/earendil-works/pi> (`packages/coding-agent`)
|
|
213
|
+
- Upstream revision reviewed: `4a080252f06caf63a525d7873c5d94d3c23887e0` (`v1.4.0`), the commit referenced by the
|
|
214
|
+
lightweight release tag; the npm registry publishes no `gitHead`, and GitHub reports the commit as unsigned
|
|
215
|
+
- Source archive: `pi-1.4.0-source.tar.gz`, verified against the release's published `SHA256SUMS`
|
|
216
|
+
- npm tarball: `pi-coding-agent-1.4.0.tgz`, pinned by SHA-256 and registry integrity
|
|
217
|
+
- License declared by the package: MIT
|
|
218
|
+
|
|
219
|
+
[`pi-overlay/versions/1.4.0/integration.patch`](pi-overlay/versions/1.4.0/integration.patch) adapts the existing seam
|
|
220
|
+
against Pi 1.4.0's MIT-licensed TypeScript sources and documentation. The modified-code patch retains the same additions
|
|
221
|
+
and removals as 1.3.0; the interactive-mode hunk positions and blob indexes are refreshed. The generated
|
|
222
|
+
[`skills.patch`](patches/pi-1.4.0/skills.patch) changes the resource loader, slash-command list, CLI/interactive
|
|
223
|
+
dispatch, and skill documentation within the same 48-line generated-runtime seam budget. It adds this repository's
|
|
224
|
+
original skill-management modules unchanged, reusing Pi's package discovery, project trust, path, and locking APIs
|
|
225
|
+
rather than copying its skill implementation. The original CLI/RPC wrappers are reused byte-for-byte from 1.3.0 after
|
|
226
|
+
reviewing 1.4.0's unchanged entrypoint sources and setup. The unchanged compile-cache loader is checksum-pinned. The
|
|
227
|
+
build order follows 1.4.0's root build, with telemetry first. Pi's automatic activation of all discovered skills and
|
|
228
|
+
unrelated runtime changes are intentionally not adopted into the overlay; unrelated package files and bundled chunks are
|
|
229
|
+
left unchanged. No complete Pi source checkout is committed.
|
|
230
|
+
|
|
231
|
+
## Pi `/skills` TypeScript overlay
|
|
232
|
+
|
|
233
|
+
- Source: `@earendil-works/pi-coding-agent@1.0.3`, `@earendil-works/pi-coding-agent@1.0.4`,
|
|
234
|
+
`@earendil-works/pi-coding-agent@1.1.0`, `@earendil-works/pi-coding-agent@1.3.0`, and
|
|
235
|
+
`@earendil-works/pi-coding-agent@1.4.0`
|
|
236
|
+
- Canonical repository: <https://github.com/earendil-works/pi> (`packages/coding-agent`)
|
|
237
|
+
- Upstream revisions reviewed: `d78dc83d633229d12f8b79631384c4c2717c399f` (`v1.0.3`) and
|
|
238
|
+
`7c10bd4337495ee613f2224843ecdf349b80d1df` (`v1.0.4`), taken from the npm registry's `gitHead`; and
|
|
239
|
+
`abe508e1b89912adde45528136c3221eb69acdd7` (`v1.1.0`), `71023aec1546d6d677a65669c5665c0927ce0dd0` (`v1.3.0`), and
|
|
240
|
+
`4a080252f06caf63a525d7873c5d94d3c23887e0` (`v1.4.0`), the commits the release tags point to, because the registry
|
|
241
|
+
publishes no `gitHead` for those releases
|
|
242
|
+
- Source acquired from the 1.0.3, 1.0.4, 1.1.0, 1.3.0, and 1.4.0 release archives and verified against each release's
|
|
243
|
+
published `SHA256SUMS`
|
|
244
|
+
- License declared by the package: MIT
|
|
245
|
+
|
|
246
|
+
[`pi-overlay`](pi-overlay) is the authored form of the `/skills` runtime patch; the artifacts under `patches/pi-1.0.3/`,
|
|
247
|
+
`patches/pi-1.0.4/`, `patches/pi-1.1.0/`, `patches/pi-1.3.0/`, and `patches/pi-1.4.0/` are generated from it.
|
|
248
|
+
|
|
249
|
+
`pi-overlay/skill-management-core.ts` and `pi-overlay/skill-management.ts` are original code for this repository. They
|
|
250
|
+
are a TypeScript reimplementation of the `dist/core/skill-management.js` previously authored here as JavaScript,
|
|
251
|
+
informed by Pi's resource-loading and command conventions rather than copied from an upstream file. They additionally
|
|
252
|
+
absorb logic that earlier versions of the patch inlined into upstream files, so those files now receive only imports and
|
|
253
|
+
call sites.
|
|
254
|
+
|
|
255
|
+
The persisted-skill lock in `pi-overlay/skill-management-core.ts` (`acquireSkillConfigLock` and `withSkillConfigLock`)
|
|
256
|
+
is a modified adaptation of the `acquireTrustLockSync` and `withTrustFileLock` pattern in Pi's MIT-licensed
|
|
257
|
+
`src/core/trust-manager.ts`: a synchronous `proper-lockfile` lock on a sibling `.lock` path, retried only on `ELOCKED`,
|
|
258
|
+
and released in `finally`. It differs by waiting with `Atomics.wait` instead of busy-spinning, allowing more attempts,
|
|
259
|
+
and reporting rather than throwing a failed release so the update's own result or error is preserved. The shell binds
|
|
260
|
+
Pi's existing `proper-lockfile` dependency; no new upstream dependency is introduced.
|
|
261
|
+
|
|
262
|
+
`pi-overlay/versions/<version>/integration.patch` is a modified-code patch against Pi's MIT-licensed TypeScript sources:
|
|
263
|
+
`src/core/resource-loader.ts`, `src/core/slash-commands.ts`, `src/main.ts`, `src/modes/interactive/interactive-mode.ts`,
|
|
264
|
+
and `docs/skills.md`. Its unchanged context and modified lines derive from the MIT-licensed Pi package.
|
|
265
|
+
|
|
266
|
+
`pi-overlay/versions/<version>/replacements/dist/bundle/cli-runtime.js` and `rpc-entry.js` are original hand-written
|
|
267
|
+
wrappers, not derived from upstream's generated bundle output. They replace Pi's esbuild-produced bundled entrypoints so
|
|
268
|
+
the patched unbundled runtime handles CLI and RPC execution.
|
|
269
|
+
|
|
270
|
+
`scripts/skills-patch-103.test.mjs` pins the unchanged `dist/bundle/cli.js` loader with a byte-identical five-line
|
|
271
|
+
stand-in based on that MIT-licensed loader, and asserts it against each release's checksum manifest.
|
|
272
|
+
|
|
273
|
+
The overlay intentionally does not adopt Pi's automatic loading of every discovered skill, configured-path confinement,
|
|
274
|
+
new public resource-loader mutator APIs, or changes to Pi's unrelated extension, prompt, theme, package, trust, and
|
|
275
|
+
provider behavior.
|
|
276
|
+
|
|
277
|
+
This repository vendors no upstream source and maintains no fork. Upstream source is fetched per generation run against
|
|
278
|
+
pinned, checksum-verified inputs, and is not committed here.
|
|
279
|
+
|
|
280
|
+
## Pi documentation and examples
|
|
281
|
+
|
|
282
|
+
- Source: `@earendil-works/pi-coding-agent`
|
|
283
|
+
- Canonical repository: <https://github.com/earendil-works/pi> (`packages/coding-agent`)
|
|
284
|
+
- Releases reviewed: `0.80.6`, `0.82.0`, `0.82.1`, `0.83.0`, `0.84.0`, `0.84.1`, `0.84.2`, `0.84.4`, `0.85.1`, `0.99.2`,
|
|
285
|
+
and `1.0.3`
|
|
286
|
+
- Latest documentation and example revision reviewed: `d78dc83d633229d12f8b79631384c4c2717c399f`
|
|
287
|
+
- License declared by the package: MIT
|
|
288
|
+
|
|
289
|
+
Ideas and API patterns used:
|
|
290
|
+
|
|
291
|
+
- Extension tool registration, lifecycle shutdown hooks, resource discovery, and TUI tool rendering.
|
|
292
|
+
- The versioned skills catalog reuses `DefaultPackageManager.resolve()` and its resolved-resource metadata to discover
|
|
293
|
+
package and settings skills with upstream manifest, filtering, scope, and precedence behavior. The catalog merge and
|
|
294
|
+
opt-in activation logic remain original code; Pi's automatic skill loading is intentionally not adopted.
|
|
295
|
+
- The skills patches adapt the synchronous `proper-lockfile` acquisition/retry and `finally` release pattern from Pi's
|
|
296
|
+
trust manager so skill configuration updates serialize across processes.
|
|
297
|
+
- SDK `AgentSession.compact()` with custom instructions and in-memory sessions.
|
|
298
|
+
- RPC JSONL framing and the `prompt`, `steer`, `follow_up`, `abort`, state, and event protocols. The real-RPC
|
|
299
|
+
integration test exercises these documented patterns against the pinned Pi CLI with a test-only provider registered
|
|
300
|
+
through `ExtensionAPI.registerProvider` and a deterministic loopback streaming endpoint; no Pi provider or RPC client
|
|
301
|
+
code was copied.
|
|
302
|
+
- Model-registry authentication, fuzzy CLI-equivalent model resolution, thinking-level capability maps, and normal child
|
|
303
|
+
resource inheritance.
|
|
304
|
+
- Pi's thinking-level clamp policy (prefer the nearest supported level above the request, fall back downward only when
|
|
305
|
+
necessary) is a conceptual adaptation, reimplemented in `extensions/subagents/helpers.ts`; no Pi code was copied.
|
|
306
|
+
`supportedThinkingLevels` additionally narrows OpenAI's direct GPT-5.6 levels beyond what Pi's generated model
|
|
307
|
+
metadata declares, because the live endpoint rejects `minimal` and `max`. Pi's own permissive handling of those two
|
|
308
|
+
levels is intentionally not adopted.
|
|
309
|
+
- Pi's bundled subagent and custom-compaction examples as reference implementations for process invocation, output
|
|
310
|
+
bounds, and compaction setup.
|
|
311
|
+
|
|
312
|
+
Major pieces intentionally not adopted include Pi's full interactive mode, session-replacement runtime, prompt-template
|
|
313
|
+
workflows, production custom provider implementations, and bundled role-based subagent profiles. No Pi source file or
|
|
314
|
+
example was copied verbatim; the extension is original code using Pi's published APIs and adapting the documented
|
|
315
|
+
architectural patterns.
|
|
316
|
+
|
|
317
|
+
Pi's official launcher signatures and managed marker fields informed nonexecuting managed-install recognition:
|
|
318
|
+
<https://github.com/earendil-works/pi>, local source revision `741fb3a686f8dcc075f12ea77f985967ced59e21`
|
|
319
|
+
(`packages/coding-agent/src/package-manager-cli.ts`; MIT), plus the installed official launcher. These are behavioral
|
|
320
|
+
references only; no launcher code, execution, installation, or self-update machinery was copied or adopted.
|
package/dist/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nigel Stuke
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
const PROVIDER_ENV = "PI_SIMPLE_SUBAGENT_AUTH_PROVIDER";
|
|
4
|
+
const API_KEY_ENV = "PI_SIMPLE_SUBAGENT_API_KEY";
|
|
5
|
+
const HEADERS_ENV = "PI_SIMPLE_SUBAGENT_AUTH_HEADERS";
|
|
6
|
+
|
|
7
|
+
const UNSAFE = /[\0\r\n]/;
|
|
8
|
+
|
|
9
|
+
/** Only accept a flat string map whose entries cannot inject extra headers. */
|
|
10
|
+
function parseHeaders(raw: string | undefined): Record<string, string> | undefined {
|
|
11
|
+
if (!raw) return undefined;
|
|
12
|
+
let parsed: unknown;
|
|
13
|
+
try {
|
|
14
|
+
parsed = JSON.parse(raw);
|
|
15
|
+
} catch {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
|
|
19
|
+
const headers: Record<string, string> = {};
|
|
20
|
+
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
|
|
21
|
+
if (typeof value !== "string" || !key || UNSAFE.test(key) || UNSAFE.test(value)) return undefined;
|
|
22
|
+
headers[key] = value;
|
|
23
|
+
}
|
|
24
|
+
return Object.keys(headers).length > 0 ? headers : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Invocation-private bridge for runtime-only parent credentials (for example
|
|
29
|
+
* `pi --api-key ...`). The child process receives the secrets in its environment,
|
|
30
|
+
* never in argv, and applies them only to the selected provider. Normal persisted
|
|
31
|
+
* auth continues to work unchanged.
|
|
32
|
+
*
|
|
33
|
+
* Headers travel with the API key because `registerProvider` replaces the whole
|
|
34
|
+
* stored provider request config, so registering an API key alone would drop the
|
|
35
|
+
* provider's configured headers (including an `authHeader` bearer) in the child.
|
|
36
|
+
* `env` is deliberately not bridged: the child re-reads provider env from the
|
|
37
|
+
* same persisted auth storage as the parent.
|
|
38
|
+
*/
|
|
39
|
+
export default function subagentAuthBridge(pi: ExtensionAPI) {
|
|
40
|
+
const provider = process.env[PROVIDER_ENV]?.trim();
|
|
41
|
+
const apiKey = process.env[API_KEY_ENV];
|
|
42
|
+
const headers = parseHeaders(process.env[HEADERS_ENV]);
|
|
43
|
+
Reflect.deleteProperty(process.env, PROVIDER_ENV);
|
|
44
|
+
Reflect.deleteProperty(process.env, API_KEY_ENV);
|
|
45
|
+
Reflect.deleteProperty(process.env, HEADERS_ENV);
|
|
46
|
+
if (!provider || UNSAFE.test(provider)) return;
|
|
47
|
+
if (!apiKey && !headers) return;
|
|
48
|
+
pi.registerProvider(provider, {
|
|
49
|
+
...(apiKey ? { apiKey } : {}),
|
|
50
|
+
...(headers ? { headers } : {}),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
export const CONTEXT_MODES = ["task_compacted", "none"] as const;
|
|
2
|
+
export type ContextMode = (typeof CONTEXT_MODES)[number];
|
|
3
|
+
|
|
4
|
+
export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
5
|
+
export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
|
|
6
|
+
|
|
7
|
+
export type ClassifierDecision = {
|
|
8
|
+
model: string;
|
|
9
|
+
effort: ThinkingLevel;
|
|
10
|
+
rationale?: string;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type ParsedModelRequest = {
|
|
14
|
+
reference: string;
|
|
15
|
+
effort?: ThinkingLevel;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export type ModelLike = {
|
|
19
|
+
provider: string;
|
|
20
|
+
id: string;
|
|
21
|
+
name?: string;
|
|
22
|
+
reasoning?: boolean;
|
|
23
|
+
contextWindow?: number;
|
|
24
|
+
cost?: {
|
|
25
|
+
input?: number;
|
|
26
|
+
output?: number;
|
|
27
|
+
cacheRead?: number;
|
|
28
|
+
cacheWrite?: number;
|
|
29
|
+
};
|
|
30
|
+
thinkingLevelMap?: Partial<Record<ThinkingLevel, string | null>>;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** Keep both the beginning and the newest context when a utility prompt needs a hard bound. */
|
|
34
|
+
export function truncateMiddle(text: string, maxChars: number): string {
|
|
35
|
+
if (text.length <= maxChars) return text;
|
|
36
|
+
if (maxChars < 80) return text.slice(0, Math.max(0, maxChars));
|
|
37
|
+
const marker = `\n\n[... ${String(text.length - maxChars)} context characters omitted ...]\n\n`;
|
|
38
|
+
const remaining = Math.max(0, maxChars - marker.length);
|
|
39
|
+
const head = Math.floor(remaining * 0.35);
|
|
40
|
+
return text.slice(0, head) + marker + text.slice(text.length - (remaining - head));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function extractTextContent(content: unknown): string {
|
|
44
|
+
if (typeof content === "string") return content;
|
|
45
|
+
if (!Array.isArray(content)) return "";
|
|
46
|
+
return content
|
|
47
|
+
.filter(
|
|
48
|
+
(part): part is { type: "text"; text: string } =>
|
|
49
|
+
Boolean(part) &&
|
|
50
|
+
typeof part === "object" &&
|
|
51
|
+
(part as { type?: unknown }).type === "text" &&
|
|
52
|
+
typeof (part as { text?: unknown }).text === "string",
|
|
53
|
+
)
|
|
54
|
+
.map((part) => part.text)
|
|
55
|
+
.join("\n");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function firstJsonObject(text: string): string | undefined {
|
|
59
|
+
const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(text)?.[1];
|
|
60
|
+
const candidate = fenced ?? text;
|
|
61
|
+
const start = candidate.indexOf("{");
|
|
62
|
+
if (start < 0) return undefined;
|
|
63
|
+
let depth = 0;
|
|
64
|
+
let inString = false;
|
|
65
|
+
let escaped = false;
|
|
66
|
+
for (let index = start; index < candidate.length; index++) {
|
|
67
|
+
const char = candidate.charAt(index);
|
|
68
|
+
if (inString) {
|
|
69
|
+
if (escaped) escaped = false;
|
|
70
|
+
else if (char === "\\") escaped = true;
|
|
71
|
+
else if (char === '"') inString = false;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (char === '"') inString = true;
|
|
75
|
+
else if (char === "{") depth++;
|
|
76
|
+
else if (char === "}" && --depth === 0) return candidate.slice(start, index + 1);
|
|
77
|
+
}
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function parseClassifierDecision(text: string): ClassifierDecision | undefined {
|
|
82
|
+
const object = firstJsonObject(text);
|
|
83
|
+
if (!object) return undefined;
|
|
84
|
+
try {
|
|
85
|
+
const parsed = JSON.parse(object) as Record<string, unknown>;
|
|
86
|
+
if (typeof parsed.model !== "string" || !parsed.model.trim()) return undefined;
|
|
87
|
+
if (typeof parsed.effort !== "string" || !THINKING_LEVELS.includes(parsed.effort as ThinkingLevel))
|
|
88
|
+
return undefined;
|
|
89
|
+
return {
|
|
90
|
+
model: parsed.model.trim(),
|
|
91
|
+
effort: parsed.effort as ThinkingLevel,
|
|
92
|
+
...(typeof parsed.rationale === "string" && parsed.rationale.trim()
|
|
93
|
+
? { rationale: parsed.rationale.trim() }
|
|
94
|
+
: {}),
|
|
95
|
+
};
|
|
96
|
+
} catch {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function parseModelRequest(request: string): ParsedModelRequest {
|
|
102
|
+
const trimmed = request.trim();
|
|
103
|
+
const separator = trimmed.lastIndexOf(":");
|
|
104
|
+
if (separator <= 0) return { reference: trimmed };
|
|
105
|
+
const suffix = trimmed.slice(separator + 1);
|
|
106
|
+
if (!THINKING_LEVELS.includes(suffix as ThinkingLevel)) return { reference: trimmed };
|
|
107
|
+
return { reference: trimmed.slice(0, separator), effort: suffix as ThinkingLevel };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function modelRef(model: ModelLike): string {
|
|
111
|
+
return `${model.provider}/${model.id}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function findRequestedModel(
|
|
115
|
+
request: string,
|
|
116
|
+
models: ModelLike[],
|
|
117
|
+
preferredProvider?: string,
|
|
118
|
+
): { model?: ModelLike; error?: string } {
|
|
119
|
+
const { reference } = parseModelRequest(request);
|
|
120
|
+
if (!reference) return { error: "Model request is empty." };
|
|
121
|
+
const providerSeparator = reference.indexOf("/");
|
|
122
|
+
if (providerSeparator > 0) {
|
|
123
|
+
const provider = reference.slice(0, providerSeparator);
|
|
124
|
+
const id = reference.slice(providerSeparator + 1);
|
|
125
|
+
const model = models.find((candidate) => candidate.provider === provider && candidate.id === id);
|
|
126
|
+
return model ? { model } : { error: `Model '${reference}' was not found.` };
|
|
127
|
+
}
|
|
128
|
+
const exact = models.filter((candidate) => candidate.id === reference);
|
|
129
|
+
const onlyExact = exact[0];
|
|
130
|
+
if (exact.length === 1 && onlyExact) return { model: onlyExact };
|
|
131
|
+
const preferred = exact.find((candidate) => candidate.provider === preferredProvider);
|
|
132
|
+
if (preferred) return { model: preferred };
|
|
133
|
+
if (exact.length > 1) {
|
|
134
|
+
return {
|
|
135
|
+
error: `Model '${reference}' is ambiguous; use a provider-qualified model: ${exact.map(modelRef).join(", ")}.`,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
return { error: `Model '${reference}' was not found.` };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function supportedThinkingLevels(model: ModelLike): ThinkingLevel[] {
|
|
142
|
+
if (model.reasoning === false) return ["off"];
|
|
143
|
+
// OpenAI's direct GPT-5.6 endpoint currently rejects `minimal` and `max`
|
|
144
|
+
// even though Pi's generated metadata leaves minimal implicit and
|
|
145
|
+
// maps max. Keep routing from selecting values the live API rejects.
|
|
146
|
+
if (model.provider.toLowerCase() === "openai" && /^gpt-5\.6(?:[-.]|$)/i.test(model.id)) {
|
|
147
|
+
return ["off", "low", "medium", "high", "xhigh"];
|
|
148
|
+
}
|
|
149
|
+
const map = model.thinkingLevelMap;
|
|
150
|
+
if (!map) return ["off", "minimal", "low", "medium", "high"];
|
|
151
|
+
return THINKING_LEVELS.filter((level) => {
|
|
152
|
+
const mapped = map[level];
|
|
153
|
+
if (mapped === null) return false;
|
|
154
|
+
if (level === "xhigh" || level === "max") return mapped !== undefined;
|
|
155
|
+
return true;
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function clampThinkingLevel(requested: ThinkingLevel, model: ModelLike): ThinkingLevel {
|
|
160
|
+
const supported = supportedThinkingLevels(model);
|
|
161
|
+
if (supported.includes(requested)) return requested;
|
|
162
|
+
const requestedIndex = THINKING_LEVELS.indexOf(requested);
|
|
163
|
+
// Match Pi's clamp policy: preserve at least the requested capability by
|
|
164
|
+
// searching upward first, then fall back downward only when necessary.
|
|
165
|
+
for (let index = requestedIndex + 1; index < THINKING_LEVELS.length; index++) {
|
|
166
|
+
const higher = THINKING_LEVELS[index];
|
|
167
|
+
if (higher && supported.includes(higher)) return higher;
|
|
168
|
+
}
|
|
169
|
+
for (let index = requestedIndex - 1; index >= 0; index--) {
|
|
170
|
+
const lower = THINKING_LEVELS[index];
|
|
171
|
+
if (lower && supported.includes(lower)) return lower;
|
|
172
|
+
}
|
|
173
|
+
return "off";
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function cost(value: number | undefined): string {
|
|
177
|
+
return Number.isFinite(value) ? String(value) : "?";
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function formatModelCatalog(models: ModelLike[]): string {
|
|
181
|
+
return models
|
|
182
|
+
.map((model) => {
|
|
183
|
+
const levels = supportedThinkingLevels(model).join("|");
|
|
184
|
+
const prices = model.cost
|
|
185
|
+
? `input=$${cost(model.cost.input)}/M output=$${cost(model.cost.output)}/M`
|
|
186
|
+
: "pricing=unknown";
|
|
187
|
+
const context = model.contextWindow === undefined ? "?" : String(model.contextWindow);
|
|
188
|
+
return `- ${model.provider}/${model.id}${model.name && model.name !== model.id ? ` (${model.name})` : ""}; effort=${levels}; context=${context}; ${prices}`;
|
|
189
|
+
})
|
|
190
|
+
.join("\n");
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function boundContextForModel(
|
|
194
|
+
summary: string,
|
|
195
|
+
task: string,
|
|
196
|
+
model: ModelLike,
|
|
197
|
+
absoluteMaxChars = 24_000,
|
|
198
|
+
): string {
|
|
199
|
+
if (!summary.trim()) return "";
|
|
200
|
+
const contextWindow = model.contextWindow ?? 128_000;
|
|
201
|
+
// Use at most ~40% of the child window for inherited context, leaving room
|
|
202
|
+
// for its system prompt, task, tools, and actual work. Three characters per
|
|
203
|
+
// token is intentionally conservative for code-heavy context.
|
|
204
|
+
const modelBound = Math.floor(contextWindow * 3 * 0.4) - task.length;
|
|
205
|
+
const maxChars = Math.min(absoluteMaxChars, Math.max(0, modelBound));
|
|
206
|
+
return maxChars < 256 ? "" : truncateMiddle(summary, maxChars);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function excludeCurrentDelegationTurn<T extends { role?: string }>(messages: T[]): T[] {
|
|
210
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
211
|
+
if (messages[index]?.role === "user") return messages.slice(0, index);
|
|
212
|
+
}
|
|
213
|
+
return [...messages];
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function appendBoundedTail(current: string, addition: string, maxChars: number): string {
|
|
217
|
+
const combined = current + addition;
|
|
218
|
+
if (combined.length <= maxChars) return combined;
|
|
219
|
+
return combined.slice(combined.length - maxChars);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function unsafeTerminalCodePoint(codePoint: number): boolean {
|
|
223
|
+
if (codePoint <= 0x1f) return codePoint !== 0x09 && codePoint !== 0x0a;
|
|
224
|
+
if (codePoint >= 0x7f && codePoint <= 0x9f) return true;
|
|
225
|
+
|
|
226
|
+
const directionalFormatting =
|
|
227
|
+
codePoint === 0x061c ||
|
|
228
|
+
codePoint === 0x200e ||
|
|
229
|
+
codePoint === 0x200f ||
|
|
230
|
+
(codePoint >= 0x202a && codePoint <= 0x202e) ||
|
|
231
|
+
(codePoint >= 0x2066 && codePoint <= 0x2069);
|
|
232
|
+
if (directionalFormatting) return true;
|
|
233
|
+
|
|
234
|
+
const privateUse = (codePoint >= 0xe000 && codePoint <= 0xf8ff) || (codePoint >= 0xf0000 && codePoint <= 0x10fffd);
|
|
235
|
+
const invalidScalar = codePoint >= 0xd800 && codePoint <= 0xdfff;
|
|
236
|
+
const nonCharacter =
|
|
237
|
+
(codePoint >= 0xfdd0 && codePoint <= 0xfdef) || (codePoint & 0xffff) === 0xfffe || (codePoint & 0xffff) === 0xffff;
|
|
238
|
+
return privateUse || invalidScalar || nonCharacter;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Escape untrusted child text for terminal display without changing the model-facing result. */
|
|
242
|
+
export function safeTerminalText(value: string): string {
|
|
243
|
+
let safe = "";
|
|
244
|
+
for (const character of value.replaceAll("\r\n", "\n")) {
|
|
245
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
246
|
+
safe += unsafeTerminalCodePoint(codePoint)
|
|
247
|
+
? `[U+${codePoint.toString(16).toUpperCase().padStart(4, "0")}]`
|
|
248
|
+
: character;
|
|
249
|
+
}
|
|
250
|
+
return safe;
|
|
251
|
+
}
|