system-prompt-omni 0.2.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/LICENSE +217 -0
- package/README.md +91 -0
- package/extensions/pi-system-prompt-recorder.ts +58 -0
- package/extensions/system-prompt.ts +616 -0
- package/lib/export-content.ts +114 -0
- package/lib/system-prompt-recorder.ts +111 -0
- package/package.json +27 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
203
|
+
|
|
204
|
+
COPYRIGHT AND ATTRIBUTION NOTICE
|
|
205
|
+
|
|
206
|
+
pi-system-prompt
|
|
207
|
+
Copyright 2026 Alex (jandrikus) and pi-system-prompt contributors
|
|
208
|
+
https://github.com/jandrikus/pi-system-prompt
|
|
209
|
+
|
|
210
|
+
system-prompt-omni modifications
|
|
211
|
+
Copyright 2026 weiwch
|
|
212
|
+
https://github.com/weiwch/system-prompt-omni
|
|
213
|
+
|
|
214
|
+
system-prompt-omni is a modified fork of pi-system-prompt. Modifications
|
|
215
|
+
include prompt-source export, effective system-prompt session recording,
|
|
216
|
+
tests, documentation, and compatibility updates. The Apache License,
|
|
217
|
+
Version 2.0 above applies to the original work and this fork.
|
package/README.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# system-prompt-omni
|
|
2
|
+
|
|
3
|
+
Display the full [pi coding agent](https://pi.dev) system prompt — with all injected tools,
|
|
4
|
+
guidelines, context files, and skills — in a scrollable full-screen overlay. The extension can
|
|
5
|
+
also export safe `SYSTEM.md` and `APPEND_SYSTEM.md` source files globally or for the current
|
|
6
|
+
project, and records each changed effective prompt in the current session.
|
|
7
|
+
|
|
8
|
+
## Usage
|
|
9
|
+
|
|
10
|
+
```text
|
|
11
|
+
/system-prompt
|
|
12
|
+
/system-prompt export
|
|
13
|
+
/system-prompt export system global
|
|
14
|
+
/system-prompt export system project
|
|
15
|
+
/system-prompt export append global
|
|
16
|
+
/system-prompt export append project
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Inside the prompt viewer:
|
|
20
|
+
|
|
21
|
+
| Key | Action |
|
|
22
|
+
|-----|--------|
|
|
23
|
+
| `↑↓` / `j` `k` | Scroll line |
|
|
24
|
+
| `PgUp` / `PgDn` | Scroll page |
|
|
25
|
+
| `Home` / `End` | Jump to top/bottom |
|
|
26
|
+
| `c` | Copy full prompt and tool definitions to clipboard |
|
|
27
|
+
| `e` | Open the export wizard |
|
|
28
|
+
| `Esc` / `q` | Close |
|
|
29
|
+
|
|
30
|
+
The export wizard writes to one of these locations:
|
|
31
|
+
|
|
32
|
+
| Scope | `SYSTEM.md` | `APPEND_SYSTEM.md` |
|
|
33
|
+
|-------|-------------|--------------------|
|
|
34
|
+
| Global | `$PI_CODING_AGENT_DIR/SYSTEM.md` or `~/.pi/agent/SYSTEM.md` | `$PI_CODING_AGENT_DIR/APPEND_SYSTEM.md` or `~/.pi/agent/APPEND_SYSTEM.md` |
|
|
35
|
+
| Project | `<cwd>/.pi/SYSTEM.md` | `<cwd>/.pi/APPEND_SYSTEM.md` |
|
|
36
|
+
|
|
37
|
+
`SYSTEM.md` export is intentionally safe: if a custom prompt is already configured, its source
|
|
38
|
+
text is exported. Otherwise, the extension removes dynamically injected append text, project
|
|
39
|
+
context, skills, and current working directory from the assembled prompt before writing the
|
|
40
|
+
static default prefix. Pi will inject those dynamic sections again when it loads the exported
|
|
41
|
+
file.
|
|
42
|
+
|
|
43
|
+
`APPEND_SYSTEM.md` export writes the currently configured append text. If none is configured,
|
|
44
|
+
the wizard can create an empty starter file. Existing files are never overwritten without
|
|
45
|
+
confirmation. Run `/reload` after exporting to load the new file.
|
|
46
|
+
|
|
47
|
+
## Prompt recording
|
|
48
|
+
|
|
49
|
+
Before each provider request, the package compares the SHA-256 hash of the effective system
|
|
50
|
+
prompt with the latest snapshot on the active session branch. When it changes, a durable custom
|
|
51
|
+
session entry with type `pi-system-prompt` records:
|
|
52
|
+
|
|
53
|
+
- the full effective system prompt, its hash, and UTF-8 byte length;
|
|
54
|
+
- provider, model, API, and thinking-level metadata;
|
|
55
|
+
- active tool names and definitions; and
|
|
56
|
+
- provider-level system/developer instructions extracted from the serialized request.
|
|
57
|
+
|
|
58
|
+
The recorder never stores the complete provider payload, never adds its custom entries to the
|
|
59
|
+
LLM context, and returns the payload unchanged. Load this package after extensions that rewrite
|
|
60
|
+
provider requests if you want those rewritten provider instructions included in the snapshot.
|
|
61
|
+
|
|
62
|
+
## Install
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
pi install git:github.com/weiwch/system-prompt-omni
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
For local development:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
pi install /path/to/system-prompt-omni
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
npm test
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## License
|
|
81
|
+
|
|
82
|
+
Apache-2.0. See [LICENSE](LICENSE), which also contains the upstream attribution and a summary
|
|
83
|
+
of this fork's modifications.
|
|
84
|
+
|
|
85
|
+
## Upstream and acknowledgements
|
|
86
|
+
|
|
87
|
+
This project is a modified fork of
|
|
88
|
+
[jandrikus/pi-system-prompt](https://github.com/jandrikus/pi-system-prompt). Many thanks to
|
|
89
|
+
Alex (`jandrikus`) and the upstream contributors for the original system-prompt viewer. The
|
|
90
|
+
upstream work and this fork are distributed under the Apache License 2.0; the original license
|
|
91
|
+
and attribution are retained.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persist the effective system prompt when it changes.
|
|
3
|
+
*
|
|
4
|
+
* Custom entries are durable but are not added to the LLM context. Load this
|
|
5
|
+
* extension last if another extension rewrites the serialized provider payload
|
|
6
|
+
* in before_provider_request.
|
|
7
|
+
*/
|
|
8
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
extractProviderSystemInstructions,
|
|
12
|
+
latestSystemPromptSha256,
|
|
13
|
+
sha256,
|
|
14
|
+
SYSTEM_PROMPT_ENTRY_SCHEMA_VERSION,
|
|
15
|
+
SYSTEM_PROMPT_ENTRY_TYPE,
|
|
16
|
+
} from "../lib/system-prompt-recorder.ts";
|
|
17
|
+
|
|
18
|
+
export default function systemPromptRecorder(pi: ExtensionAPI): void {
|
|
19
|
+
pi.on("before_provider_request", (event, ctx) => {
|
|
20
|
+
const systemPrompt = ctx.getSystemPrompt();
|
|
21
|
+
const systemPromptSha256 = sha256(systemPrompt);
|
|
22
|
+
|
|
23
|
+
// Compare with the latest snapshot on the active branch. This also avoids
|
|
24
|
+
// duplicates after process restarts, session resume, and extension reloads.
|
|
25
|
+
if (latestSystemPromptSha256(ctx.sessionManager.getBranch()) === systemPromptSha256) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const providerSystemInstructions = extractProviderSystemInstructions(event.payload);
|
|
30
|
+
const model = ctx.model;
|
|
31
|
+
const activeTools = pi.getActiveTools();
|
|
32
|
+
const toolsByName = new Map(pi.getAllTools().map((tool) => [tool.name, tool]));
|
|
33
|
+
const tools = activeTools.flatMap((name) => {
|
|
34
|
+
const tool = toolsByName.get(name);
|
|
35
|
+
if (!tool) return [];
|
|
36
|
+
return [{ name: tool.name, description: tool.description, parameters: tool.parameters }];
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
pi.appendEntry(SYSTEM_PROMPT_ENTRY_TYPE, {
|
|
40
|
+
schemaVersion: SYSTEM_PROMPT_ENTRY_SCHEMA_VERSION,
|
|
41
|
+
captureStage: "before_provider_request",
|
|
42
|
+
capturedAt: new Date().toISOString(),
|
|
43
|
+
systemPrompt,
|
|
44
|
+
systemPromptSha256,
|
|
45
|
+
systemPromptUtf8Bytes: Buffer.byteLength(systemPrompt, "utf8"),
|
|
46
|
+
provider: model?.provider,
|
|
47
|
+
modelId: model?.id,
|
|
48
|
+
api: model?.api,
|
|
49
|
+
thinkingLevel: pi.getThinkingLevel(),
|
|
50
|
+
activeTools,
|
|
51
|
+
tools,
|
|
52
|
+
providerSystemInstructions,
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// Returning undefined leaves the provider payload unchanged.
|
|
56
|
+
return undefined;
|
|
57
|
+
});
|
|
58
|
+
}
|
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /system-prompt — Display the full system prompt and tool definitions
|
|
3
|
+
* in a full-screen scrollable overlay, with safe prompt-file export.
|
|
4
|
+
*
|
|
5
|
+
* Modified from jandrikus/pi-system-prompt for system-prompt-omni.
|
|
6
|
+
*/
|
|
7
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
CONFIG_DIR_NAME,
|
|
12
|
+
getAgentDir,
|
|
13
|
+
type ExtensionAPI,
|
|
14
|
+
type ExtensionCommandContext,
|
|
15
|
+
type Theme,
|
|
16
|
+
type ToolInfo,
|
|
17
|
+
} from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import {
|
|
19
|
+
matchesKey,
|
|
20
|
+
truncateToWidth,
|
|
21
|
+
type TUI,
|
|
22
|
+
visibleWidth,
|
|
23
|
+
wrapTextWithAnsi,
|
|
24
|
+
} from "@earendil-works/pi-tui";
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
getPromptFileContent,
|
|
28
|
+
type PromptFileKind,
|
|
29
|
+
} from "../lib/export-content.ts";
|
|
30
|
+
|
|
31
|
+
type ExportScope = "global" | "project";
|
|
32
|
+
type ViewResult = "export" | null;
|
|
33
|
+
|
|
34
|
+
interface ExportRequest {
|
|
35
|
+
kind?: PromptFileKind;
|
|
36
|
+
scope?: ExportScope;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export default function (pi: ExtensionAPI) {
|
|
40
|
+
// Listen for date from pi-today extension.
|
|
41
|
+
let todayDate: string | undefined;
|
|
42
|
+
pi.events.on("today:date", (data: unknown) => {
|
|
43
|
+
if (typeof data === "string") {
|
|
44
|
+
todayDate = data;
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
pi.registerCommand("system-prompt", {
|
|
49
|
+
description: "Show or export the current system prompt and tool definitions",
|
|
50
|
+
getArgumentCompletions: (prefix: string) => {
|
|
51
|
+
const choices = [
|
|
52
|
+
{ value: "export", label: "export", description: "Open the export wizard" },
|
|
53
|
+
{
|
|
54
|
+
value: "export system global",
|
|
55
|
+
label: "export system global",
|
|
56
|
+
description: "Write global SYSTEM.md",
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
value: "export system project",
|
|
60
|
+
label: "export system project",
|
|
61
|
+
description: "Write project .pi/SYSTEM.md",
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
value: "export append global",
|
|
65
|
+
label: "export append global",
|
|
66
|
+
description: "Write global APPEND_SYSTEM.md",
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
value: "export append project",
|
|
70
|
+
label: "export append project",
|
|
71
|
+
description: "Write project .pi/APPEND_SYSTEM.md",
|
|
72
|
+
},
|
|
73
|
+
];
|
|
74
|
+
const normalized = prefix.trim().toLowerCase();
|
|
75
|
+
const matches = choices.filter((choice) => choice.value.startsWith(normalized));
|
|
76
|
+
return matches.length > 0 ? matches : null;
|
|
77
|
+
},
|
|
78
|
+
handler: async (args, ctx) => {
|
|
79
|
+
await ctx.waitForIdle();
|
|
80
|
+
|
|
81
|
+
const parsed = parseCommandArgs(args);
|
|
82
|
+
if (parsed.error) {
|
|
83
|
+
ctx.ui.notify(parsed.error, "error");
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (parsed.exportRequest) {
|
|
87
|
+
await exportPromptFile(ctx, parsed.exportRequest);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
let prompt = ctx.getSystemPrompt();
|
|
92
|
+
|
|
93
|
+
// Prepend the date from pi-today for display only. Export uses Pi's base
|
|
94
|
+
// prompt inputs and never persists this display-only line.
|
|
95
|
+
if (todayDate) {
|
|
96
|
+
prompt = `${todayDate}\n\n${prompt}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const promptLines = prompt.split("\n");
|
|
100
|
+
const charCount = prompt.length;
|
|
101
|
+
const lineCount = promptLines.length;
|
|
102
|
+
|
|
103
|
+
// Gather tool definitions.
|
|
104
|
+
const active = new Set(pi.getActiveTools());
|
|
105
|
+
const activeTools = pi.getAllTools().filter((tool) => active.has(tool.name));
|
|
106
|
+
const toolLines = buildToolLines(activeTools);
|
|
107
|
+
|
|
108
|
+
const allLines = [
|
|
109
|
+
...promptLines,
|
|
110
|
+
"",
|
|
111
|
+
"────────────────────────────────────────",
|
|
112
|
+
"",
|
|
113
|
+
...toolLines,
|
|
114
|
+
];
|
|
115
|
+
|
|
116
|
+
const result = await ctx.ui.custom<ViewResult>(
|
|
117
|
+
(tui, theme, _keybindings, done) =>
|
|
118
|
+
new SystemPromptView(
|
|
119
|
+
tui,
|
|
120
|
+
allLines,
|
|
121
|
+
activeTools,
|
|
122
|
+
lineCount,
|
|
123
|
+
charCount,
|
|
124
|
+
allLines.length,
|
|
125
|
+
theme,
|
|
126
|
+
done,
|
|
127
|
+
),
|
|
128
|
+
{
|
|
129
|
+
overlay: true,
|
|
130
|
+
overlayOptions: {
|
|
131
|
+
width: "95%",
|
|
132
|
+
maxHeight: "92%",
|
|
133
|
+
anchor: "center",
|
|
134
|
+
margin: 0,
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
if (result === "export") {
|
|
140
|
+
await exportPromptFile(ctx, {});
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function parseCommandArgs(args: string): {
|
|
147
|
+
exportRequest?: ExportRequest;
|
|
148
|
+
error?: string;
|
|
149
|
+
} {
|
|
150
|
+
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
151
|
+
if (tokens.length === 0) {
|
|
152
|
+
return {};
|
|
153
|
+
}
|
|
154
|
+
if (tokens[0]?.toLowerCase() !== "export") {
|
|
155
|
+
return { error: exportUsage() };
|
|
156
|
+
}
|
|
157
|
+
if (tokens.length > 3) {
|
|
158
|
+
return { error: exportUsage() };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const kind = tokens[1] ? parsePromptFileKind(tokens[1]) : undefined;
|
|
162
|
+
if (tokens[1] && !kind) {
|
|
163
|
+
return { error: `Unknown prompt file ${JSON.stringify(tokens[1])}.\n${exportUsage()}` };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const scope = tokens[2] ? parseExportScope(tokens[2]) : undefined;
|
|
167
|
+
if (tokens[2] && !scope) {
|
|
168
|
+
return { error: `Unknown export scope ${JSON.stringify(tokens[2])}.\n${exportUsage()}` };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return { exportRequest: { kind, scope } };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function parsePromptFileKind(value: string): PromptFileKind | undefined {
|
|
175
|
+
switch (value.toLowerCase()) {
|
|
176
|
+
case "system":
|
|
177
|
+
case "system.md":
|
|
178
|
+
return "system";
|
|
179
|
+
case "append":
|
|
180
|
+
case "append_system.md":
|
|
181
|
+
case "append-system":
|
|
182
|
+
return "append";
|
|
183
|
+
default:
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function parseExportScope(value: string): ExportScope | undefined {
|
|
189
|
+
switch (value.toLowerCase()) {
|
|
190
|
+
case "global":
|
|
191
|
+
case "user":
|
|
192
|
+
return "global";
|
|
193
|
+
case "project":
|
|
194
|
+
case "current":
|
|
195
|
+
case "local":
|
|
196
|
+
return "project";
|
|
197
|
+
default:
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function exportUsage(): string {
|
|
203
|
+
return [
|
|
204
|
+
"Usage:",
|
|
205
|
+
" /system-prompt",
|
|
206
|
+
" /system-prompt export [system|append] [global|project]",
|
|
207
|
+
].join("\n");
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function exportPromptFile(
|
|
211
|
+
ctx: ExtensionCommandContext,
|
|
212
|
+
request: ExportRequest,
|
|
213
|
+
): Promise<void> {
|
|
214
|
+
const kind = request.kind ?? (await selectPromptFileKind(ctx));
|
|
215
|
+
if (!kind) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const scope = request.scope ?? (await selectExportScope(ctx));
|
|
220
|
+
if (!scope) {
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (scope === "project" && !ctx.isProjectTrusted()) {
|
|
225
|
+
const proceed = await ctx.ui.confirm(
|
|
226
|
+
"Project is not trusted",
|
|
227
|
+
`Write ${fileNameForKind(kind)} under ${join(ctx.cwd, CONFIG_DIR_NAME)} anyway? ` +
|
|
228
|
+
"Pi will not load it until the project is trusted and reloaded.",
|
|
229
|
+
);
|
|
230
|
+
if (!proceed) {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
let content: string;
|
|
236
|
+
try {
|
|
237
|
+
content = getPromptFileContent(kind, ctx.getSystemPrompt(), ctx.getSystemPromptOptions());
|
|
238
|
+
} catch (error) {
|
|
239
|
+
ctx.ui.notify(`Could not export ${fileNameForKind(kind)}: ${formatError(error)}`, "error");
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const targetPath = resolveExportPath(kind, scope, ctx.cwd);
|
|
244
|
+
|
|
245
|
+
let existingContent: string | undefined;
|
|
246
|
+
try {
|
|
247
|
+
existingContent = await readFile(targetPath, "utf8");
|
|
248
|
+
} catch (error) {
|
|
249
|
+
if (!isNotFoundError(error)) {
|
|
250
|
+
ctx.ui.notify(`Could not read ${targetPath}: ${formatError(error)}`, "error");
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (existingContent === content) {
|
|
256
|
+
ctx.ui.notify(`${targetPath} is already up to date.`, "info");
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (kind === "append" && content.length === 0) {
|
|
261
|
+
const createEmpty = await ctx.ui.confirm(
|
|
262
|
+
"No append prompt is active",
|
|
263
|
+
`Create an empty starter file at ${targetPath}?`,
|
|
264
|
+
);
|
|
265
|
+
if (!createEmpty) {
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (existingContent !== undefined) {
|
|
271
|
+
const overwrite = await ctx.ui.confirm(
|
|
272
|
+
`Overwrite ${fileNameForKind(kind)}?`,
|
|
273
|
+
`${targetPath} already exists and contains different content.`,
|
|
274
|
+
);
|
|
275
|
+
if (!overwrite) {
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
try {
|
|
281
|
+
await mkdir(dirname(targetPath), { recursive: true });
|
|
282
|
+
await writeFile(targetPath, content, "utf8");
|
|
283
|
+
} catch (error) {
|
|
284
|
+
ctx.ui.notify(`Could not write ${targetPath}: ${formatError(error)}`, "error");
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
ctx.ui.notify(`Exported ${fileNameForKind(kind)} to ${targetPath}. Run /reload to load it.`, "info");
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function selectPromptFileKind(
|
|
292
|
+
ctx: ExtensionCommandContext,
|
|
293
|
+
): Promise<PromptFileKind | undefined> {
|
|
294
|
+
const selected = await ctx.ui.select("Export which prompt source?", [
|
|
295
|
+
"SYSTEM.md — custom/default static prefix",
|
|
296
|
+
"APPEND_SYSTEM.md — appended instructions",
|
|
297
|
+
]);
|
|
298
|
+
if (selected?.startsWith("SYSTEM.md")) {
|
|
299
|
+
return "system";
|
|
300
|
+
}
|
|
301
|
+
if (selected?.startsWith("APPEND_SYSTEM.md")) {
|
|
302
|
+
return "append";
|
|
303
|
+
}
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function selectExportScope(ctx: ExtensionCommandContext): Promise<ExportScope | undefined> {
|
|
308
|
+
const selected = await ctx.ui.select("Export scope", [
|
|
309
|
+
`Global — ${getAgentDir()}`,
|
|
310
|
+
`Current project — ${join(ctx.cwd, CONFIG_DIR_NAME)}`,
|
|
311
|
+
]);
|
|
312
|
+
if (selected?.startsWith("Global")) {
|
|
313
|
+
return "global";
|
|
314
|
+
}
|
|
315
|
+
if (selected?.startsWith("Current project")) {
|
|
316
|
+
return "project";
|
|
317
|
+
}
|
|
318
|
+
return undefined;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function resolveExportPath(kind: PromptFileKind, scope: ExportScope, cwd: string): string {
|
|
322
|
+
const directory = scope === "global" ? getAgentDir() : join(cwd, CONFIG_DIR_NAME);
|
|
323
|
+
return join(directory, fileNameForKind(kind));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function fileNameForKind(kind: PromptFileKind): "SYSTEM.md" | "APPEND_SYSTEM.md" {
|
|
327
|
+
return kind === "system" ? "SYSTEM.md" : "APPEND_SYSTEM.md";
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function isNotFoundError(error: unknown): boolean {
|
|
331
|
+
return (
|
|
332
|
+
typeof error === "object" &&
|
|
333
|
+
error !== null &&
|
|
334
|
+
"code" in error &&
|
|
335
|
+
(error as { code?: unknown }).code === "ENOENT"
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function formatError(error: unknown): string {
|
|
340
|
+
return error instanceof Error ? error.message : String(error);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function buildToolLines(tools: ToolInfo[]): string[] {
|
|
344
|
+
const lines: string[] = [];
|
|
345
|
+
if (tools.length === 0) {
|
|
346
|
+
lines.push("No tools registered.");
|
|
347
|
+
return lines;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
lines.push(`Tool Definitions (${tools.length} tools)`);
|
|
351
|
+
lines.push("");
|
|
352
|
+
|
|
353
|
+
for (const tool of tools) {
|
|
354
|
+
const source = tool.sourceInfo?.source ?? "unknown";
|
|
355
|
+
const sourceText = source === "builtin" ? "built-in" : source === "sdk" ? "SDK" : source;
|
|
356
|
+
|
|
357
|
+
lines.push(`name: ${tool.name}`);
|
|
358
|
+
lines.push(` description: ${tool.description}`);
|
|
359
|
+
lines.push(` source: ${sourceText}`);
|
|
360
|
+
lines.push(" parameters:");
|
|
361
|
+
|
|
362
|
+
const paramLines = JSON.stringify(tool.parameters, null, 2).split("\n");
|
|
363
|
+
for (const line of paramLines) {
|
|
364
|
+
lines.push(` ${line}`);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
lines.push("");
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
return lines;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
interface DisplayLine {
|
|
374
|
+
text: string;
|
|
375
|
+
originalIndex: number;
|
|
376
|
+
continuation: boolean;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
type LineStyle = "tools" | "guidelines" | "heading" | "bullet" | "toolLine" | "plain";
|
|
380
|
+
|
|
381
|
+
function lineStyle(originalLine: string): LineStyle {
|
|
382
|
+
if (originalLine.startsWith("Available tools:")) return "tools";
|
|
383
|
+
if (originalLine.startsWith("Guidelines:")) return "guidelines";
|
|
384
|
+
if (/^#+\s/.test(originalLine)) return "heading";
|
|
385
|
+
if (originalLine.startsWith("- ")) return "bullet";
|
|
386
|
+
if (originalLine.startsWith(" ") || originalLine.startsWith(" ")) return "toolLine";
|
|
387
|
+
return "plain";
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function styleFirstLine(theme: Theme, text: string, style: LineStyle): string {
|
|
391
|
+
switch (style) {
|
|
392
|
+
case "tools":
|
|
393
|
+
return theme.fg("success", theme.bold(text));
|
|
394
|
+
case "guidelines":
|
|
395
|
+
case "heading":
|
|
396
|
+
return theme.fg("accent", theme.bold(text));
|
|
397
|
+
case "bullet":
|
|
398
|
+
return theme.fg("muted", text);
|
|
399
|
+
default:
|
|
400
|
+
return text;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function styleContinuation(theme: Theme, text: string, style: LineStyle): string {
|
|
405
|
+
switch (style) {
|
|
406
|
+
case "bullet":
|
|
407
|
+
return theme.fg("muted", text);
|
|
408
|
+
case "heading":
|
|
409
|
+
return theme.fg("dim", text);
|
|
410
|
+
default:
|
|
411
|
+
return theme.fg("dim", text);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function enableMouse(): void {
|
|
416
|
+
process.stdout.write("\x1b[?1000h");
|
|
417
|
+
process.stdout.write("\x1b[?1006h");
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function disableMouse(): void {
|
|
421
|
+
process.stdout.write("\x1b[?1006l");
|
|
422
|
+
process.stdout.write("\x1b[?1000l");
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function parseSgrMouse(data: string): { wheelUp: number; wheelDown: number } | null {
|
|
426
|
+
if (!data.startsWith("\x1b[<") || !data.endsWith("M")) return null;
|
|
427
|
+
const parts = data.slice(3, -1).split(";");
|
|
428
|
+
if (parts.length !== 3) return null;
|
|
429
|
+
const button = Number.parseInt(parts[0] ?? "", 10);
|
|
430
|
+
if (Number.isNaN(button)) return null;
|
|
431
|
+
if (button === 64) return { wheelUp: 3, wheelDown: 0 };
|
|
432
|
+
if (button === 65) return { wheelUp: 0, wheelDown: 3 };
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
class SystemPromptView {
|
|
437
|
+
private scrollOffset = 0;
|
|
438
|
+
private copiedAt = 0;
|
|
439
|
+
private readonly fullText: string;
|
|
440
|
+
private totalDisplayLines = 0;
|
|
441
|
+
|
|
442
|
+
constructor(
|
|
443
|
+
private readonly tui: TUI,
|
|
444
|
+
private readonly allLines: string[],
|
|
445
|
+
private readonly allTools: ToolInfo[],
|
|
446
|
+
private readonly promptLineCount: number,
|
|
447
|
+
private readonly promptCharCount: number,
|
|
448
|
+
private readonly combinedLineCount: number,
|
|
449
|
+
private readonly theme: Theme,
|
|
450
|
+
private readonly done: (result: ViewResult) => void,
|
|
451
|
+
) {
|
|
452
|
+
this.fullText = allLines.join("\n");
|
|
453
|
+
enableMouse();
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
handleInput(data: string): void {
|
|
457
|
+
const visible = this.visibleLines();
|
|
458
|
+
const total = this.totalDisplayLines || this.combinedLineCount;
|
|
459
|
+
|
|
460
|
+
const mouse = parseSgrMouse(data);
|
|
461
|
+
if (mouse) {
|
|
462
|
+
if (mouse.wheelUp > 0) {
|
|
463
|
+
this.scrollOffset = Math.max(0, this.scrollOffset - mouse.wheelUp);
|
|
464
|
+
}
|
|
465
|
+
if (mouse.wheelDown > 0) {
|
|
466
|
+
this.scrollOffset = Math.min(
|
|
467
|
+
Math.max(0, total - visible),
|
|
468
|
+
this.scrollOffset + mouse.wheelDown,
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
this.tui.requestRender?.();
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
if (matchesKey(data, "up") || matchesKey(data, "k")) {
|
|
476
|
+
if (this.scrollOffset > 0) this.scrollOffset--;
|
|
477
|
+
this.tui.requestRender?.();
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
if (matchesKey(data, "down") || matchesKey(data, "j")) {
|
|
481
|
+
if (this.scrollOffset < total - visible) this.scrollOffset++;
|
|
482
|
+
this.tui.requestRender?.();
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
if (matchesKey(data, "pageUp")) {
|
|
486
|
+
this.scrollOffset = Math.max(0, this.scrollOffset - visible);
|
|
487
|
+
this.tui.requestRender?.();
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
if (matchesKey(data, "pageDown")) {
|
|
491
|
+
this.scrollOffset = Math.min(Math.max(0, total - visible), this.scrollOffset + visible);
|
|
492
|
+
this.tui.requestRender?.();
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
if (matchesKey(data, "home")) {
|
|
496
|
+
this.scrollOffset = 0;
|
|
497
|
+
this.tui.requestRender?.();
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (matchesKey(data, "end")) {
|
|
501
|
+
this.scrollOffset = Math.max(0, total - visible);
|
|
502
|
+
this.tui.requestRender?.();
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
if (matchesKey(data, "c")) {
|
|
506
|
+
this.copyToClipboard();
|
|
507
|
+
this.tui.requestRender?.();
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
if (matchesKey(data, "e")) {
|
|
511
|
+
this.done("export");
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
if (matchesKey(data, "escape") || matchesKey(data, "q")) {
|
|
515
|
+
this.done(null);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
private visibleLines(): number {
|
|
520
|
+
const height = this.tui.terminal.rows;
|
|
521
|
+
if (!height || height <= 0) return 30;
|
|
522
|
+
return Math.max(1, Math.floor(height * 0.92) - 4);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
private buildDisplayLines(contentWidth: number): DisplayLine[] {
|
|
526
|
+
const displayLines: DisplayLine[] = [];
|
|
527
|
+
for (let index = 0; index < this.allLines.length; index++) {
|
|
528
|
+
const wrapped = wrapTextWithAnsi(this.allLines[index] ?? "", contentWidth);
|
|
529
|
+
for (let wrappedIndex = 0; wrappedIndex < wrapped.length; wrappedIndex++) {
|
|
530
|
+
displayLines.push({
|
|
531
|
+
text: wrapped[wrappedIndex] ?? "",
|
|
532
|
+
originalIndex: index,
|
|
533
|
+
continuation: wrappedIndex > 0,
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
return displayLines;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
render(width: number): string[] {
|
|
541
|
+
const theme = this.theme;
|
|
542
|
+
const innerWidth = Math.max(1, width - 2);
|
|
543
|
+
const contentWidth = Math.max(1, innerWidth - 1);
|
|
544
|
+
const visible = this.visibleLines();
|
|
545
|
+
|
|
546
|
+
const displayLines = this.buildDisplayLines(contentWidth);
|
|
547
|
+
this.totalDisplayLines = displayLines.length;
|
|
548
|
+
|
|
549
|
+
const pad = (text: string, length: number) => {
|
|
550
|
+
const currentWidth = visibleWidth(text);
|
|
551
|
+
return text + " ".repeat(Math.max(0, length - currentWidth));
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
const row = (content: string) => {
|
|
555
|
+
const fitted = truncateToWidth(content, innerWidth, "");
|
|
556
|
+
return theme.fg("border", "│") + pad(fitted, innerWidth) + theme.fg("border", "│");
|
|
557
|
+
};
|
|
558
|
+
|
|
559
|
+
const output: string[] = [];
|
|
560
|
+
output.push(theme.fg("border", `╭${"─".repeat(innerWidth)}╮`));
|
|
561
|
+
output.push(
|
|
562
|
+
row(
|
|
563
|
+
` ${theme.fg("accent", theme.bold("System Prompt"))} ${theme.fg("dim", `— ${this.promptLineCount} lines, ${this.promptCharCount.toLocaleString()} chars`)} ${theme.fg("dim", `| ${this.allTools.length} tools`)}`,
|
|
564
|
+
),
|
|
565
|
+
);
|
|
566
|
+
output.push(row(""));
|
|
567
|
+
|
|
568
|
+
const end = Math.min(this.scrollOffset + visible, displayLines.length);
|
|
569
|
+
for (let index = this.scrollOffset; index < end; index++) {
|
|
570
|
+
const displayLine = displayLines[index];
|
|
571
|
+
if (!displayLine) continue;
|
|
572
|
+
const originalLine = this.allLines[displayLine.originalIndex] ?? "";
|
|
573
|
+
const style = lineStyle(originalLine);
|
|
574
|
+
const styled = displayLine.continuation
|
|
575
|
+
? styleContinuation(theme, displayLine.text, style)
|
|
576
|
+
: styleFirstLine(theme, displayLine.text, style);
|
|
577
|
+
output.push(row(` ${styled}`));
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
for (let index = end - this.scrollOffset; index < visible; index++) {
|
|
581
|
+
output.push(row(""));
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
const percentage =
|
|
585
|
+
displayLines.length > 0
|
|
586
|
+
? Math.round((this.scrollOffset / displayLines.length) * 100)
|
|
587
|
+
: 0;
|
|
588
|
+
const footerLeft = `${this.scrollOffset + 1}-${end}/${displayLines.length} (${percentage}%)`;
|
|
589
|
+
const copyLabel = Date.now() - this.copiedAt < 2000 ? theme.fg("success", "copied") : "copy";
|
|
590
|
+
const footerRight = `e export c ${copyLabel} ↑↓/jk pgup/pgdn home/end Esc/q`;
|
|
591
|
+
const gap = Math.max(
|
|
592
|
+
1,
|
|
593
|
+
innerWidth - 1 - visibleWidth(footerLeft) - visibleWidth(footerRight),
|
|
594
|
+
);
|
|
595
|
+
const footer =
|
|
596
|
+
` ${theme.fg("dim", footerLeft)}` +
|
|
597
|
+
`${" ".repeat(gap)}${theme.fg("dim", footerRight)}`;
|
|
598
|
+
output.push(row(""));
|
|
599
|
+
output.push(row(footer));
|
|
600
|
+
output.push(theme.fg("border", `╰${"─".repeat(innerWidth)}╯`));
|
|
601
|
+
|
|
602
|
+
return output;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
private copyToClipboard(): void {
|
|
606
|
+
const base64 = Buffer.from(this.fullText, "utf8").toString("base64");
|
|
607
|
+
process.stdout.write(`\x1b]52;c;${base64}\x07`);
|
|
608
|
+
this.copiedAt = Date.now();
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
invalidate(): void {}
|
|
612
|
+
|
|
613
|
+
dispose(): void {
|
|
614
|
+
disableMouse();
|
|
615
|
+
}
|
|
616
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
export type PromptFileKind = "system" | "append";
|
|
2
|
+
|
|
3
|
+
export interface PromptContextFile {
|
|
4
|
+
path: string;
|
|
5
|
+
content: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface PromptSkill {
|
|
9
|
+
name: string;
|
|
10
|
+
description: string;
|
|
11
|
+
filePath: string;
|
|
12
|
+
disableModelInvocation?: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface PromptBuildOptions {
|
|
16
|
+
customPrompt?: string;
|
|
17
|
+
selectedTools?: string[];
|
|
18
|
+
appendSystemPrompt?: string;
|
|
19
|
+
cwd: string;
|
|
20
|
+
contextFiles?: PromptContextFile[];
|
|
21
|
+
skills?: PromptSkill[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Return content that is safe to persist as one of Pi's prompt source files.
|
|
26
|
+
* SYSTEM.md contains only the custom/default prefix; Pi will append dynamic
|
|
27
|
+
* context, skills, and cwd again when it loads the file.
|
|
28
|
+
*/
|
|
29
|
+
export function getPromptFileContent(
|
|
30
|
+
kind: PromptFileKind,
|
|
31
|
+
systemPrompt: string,
|
|
32
|
+
options: PromptBuildOptions,
|
|
33
|
+
): string {
|
|
34
|
+
if (kind === "append") {
|
|
35
|
+
return options.appendSystemPrompt ?? "";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Pi treats a truthy customPrompt as the complete SYSTEM.md/template prefix.
|
|
39
|
+
if (options.customPrompt) {
|
|
40
|
+
return options.customPrompt;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const dynamicSuffix = buildDynamicSuffix(options);
|
|
44
|
+
if (!systemPrompt.endsWith(dynamicSuffix)) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
"The current prompt does not match Pi's base prompt layout. " +
|
|
47
|
+
"A per-turn extension may have changed it; refusing to export dynamic context into SYSTEM.md.",
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return systemPrompt.slice(0, -dynamicSuffix.length);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function buildDynamicSuffix(options: PromptBuildOptions): string {
|
|
55
|
+
let suffix = "";
|
|
56
|
+
|
|
57
|
+
if (options.appendSystemPrompt) {
|
|
58
|
+
suffix += `\n\n${options.appendSystemPrompt}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const contextFiles = options.contextFiles ?? [];
|
|
62
|
+
if (contextFiles.length > 0) {
|
|
63
|
+
suffix += "\n\n<project_context>\n\n";
|
|
64
|
+
suffix += "Project-specific instructions and guidelines:\n\n";
|
|
65
|
+
for (const contextFile of contextFiles) {
|
|
66
|
+
suffix += `<project_instructions path="${contextFile.path}">\n`;
|
|
67
|
+
suffix += `${contextFile.content}\n`;
|
|
68
|
+
suffix += "</project_instructions>\n\n";
|
|
69
|
+
}
|
|
70
|
+
suffix += "</project_context>\n";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const hasReadTool = !options.selectedTools || options.selectedTools.includes("read");
|
|
74
|
+
if (hasReadTool) {
|
|
75
|
+
suffix += formatSkills(options.skills ?? []);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
suffix += `\nCurrent working directory: ${options.cwd.replace(/\\/g, "/")}`;
|
|
79
|
+
return suffix;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function formatSkills(skills: PromptSkill[]): string {
|
|
83
|
+
const visibleSkills = skills.filter((skill) => !skill.disableModelInvocation);
|
|
84
|
+
if (visibleSkills.length === 0) {
|
|
85
|
+
return "";
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const lines = [
|
|
89
|
+
"\n\nThe following skills provide specialized instructions for specific tasks.",
|
|
90
|
+
"Use the read tool to load a skill's file when the task matches its description.",
|
|
91
|
+
"When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.",
|
|
92
|
+
"",
|
|
93
|
+
"<available_skills>",
|
|
94
|
+
];
|
|
95
|
+
|
|
96
|
+
for (const skill of visibleSkills) {
|
|
97
|
+
lines.push(" <skill>");
|
|
98
|
+
lines.push(` <name>${escapeXml(skill.name)}</name>`);
|
|
99
|
+
lines.push(` <description>${escapeXml(skill.description)}</description>`);
|
|
100
|
+
lines.push(` <location>${escapeXml(skill.filePath)}</location>`);
|
|
101
|
+
lines.push(" </skill>");
|
|
102
|
+
}
|
|
103
|
+
lines.push("</available_skills>");
|
|
104
|
+
return lines.join("\n");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function escapeXml(value: string): string {
|
|
108
|
+
return value
|
|
109
|
+
.replace(/&/g, "&")
|
|
110
|
+
.replace(/</g, "<")
|
|
111
|
+
.replace(/>/g, ">")
|
|
112
|
+
.replace(/"/g, """)
|
|
113
|
+
.replace(/'/g, "'");
|
|
114
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
export const SYSTEM_PROMPT_ENTRY_TYPE = "pi-system-prompt";
|
|
4
|
+
export const SYSTEM_PROMPT_ENTRY_SCHEMA_VERSION = 1;
|
|
5
|
+
|
|
6
|
+
interface CustomEntryLike {
|
|
7
|
+
type?: unknown;
|
|
8
|
+
customType?: unknown;
|
|
9
|
+
data?: unknown;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
13
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function jsonSnapshot(value: unknown): unknown {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(JSON.stringify(value));
|
|
19
|
+
} catch {
|
|
20
|
+
return "[unserializable provider system instruction]";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function pushField(
|
|
25
|
+
result: Array<Record<string, unknown>>,
|
|
26
|
+
root: Record<string, unknown>,
|
|
27
|
+
key: string,
|
|
28
|
+
prefix = "$",
|
|
29
|
+
): void {
|
|
30
|
+
if (!Object.prototype.hasOwnProperty.call(root, key)) return;
|
|
31
|
+
const value = root[key];
|
|
32
|
+
if (value === undefined || value === null) return;
|
|
33
|
+
result.push({ path: `${prefix}.${key}`, value: jsonSnapshot(value) });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function pushRoleMessages(
|
|
37
|
+
result: Array<Record<string, unknown>>,
|
|
38
|
+
root: Record<string, unknown>,
|
|
39
|
+
key: string,
|
|
40
|
+
prefix = "$",
|
|
41
|
+
): void {
|
|
42
|
+
const messages = root[key];
|
|
43
|
+
if (!Array.isArray(messages)) return;
|
|
44
|
+
|
|
45
|
+
for (let index = 0; index < messages.length; index += 1) {
|
|
46
|
+
const message = messages[index];
|
|
47
|
+
if (!isRecord(message)) continue;
|
|
48
|
+
if (message.role !== "system" && message.role !== "developer") continue;
|
|
49
|
+
|
|
50
|
+
result.push({
|
|
51
|
+
path: `${prefix}.${key}[${index}].content`,
|
|
52
|
+
role: message.role,
|
|
53
|
+
value: jsonSnapshot(message.content),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Extract provider-level system instructions without persisting the complete
|
|
60
|
+
* request payload, which would duplicate the conversation and tool schemas.
|
|
61
|
+
*/
|
|
62
|
+
export function extractProviderSystemInstructions(
|
|
63
|
+
payload: unknown,
|
|
64
|
+
): Array<Record<string, unknown>> {
|
|
65
|
+
if (!isRecord(payload)) return [];
|
|
66
|
+
|
|
67
|
+
const result: Array<Record<string, unknown>> = [];
|
|
68
|
+
const roots = [{ value: payload, prefix: "$" }];
|
|
69
|
+
|
|
70
|
+
// Some custom transports wrap the JSON body one level down.
|
|
71
|
+
if (isRecord(payload.body)) {
|
|
72
|
+
roots.push({ value: payload.body, prefix: "$.body" });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
for (const { value: root, prefix } of roots) {
|
|
76
|
+
for (const key of [
|
|
77
|
+
"instructions",
|
|
78
|
+
"system",
|
|
79
|
+
"system_instruction",
|
|
80
|
+
"systemInstruction",
|
|
81
|
+
"systemPrompt",
|
|
82
|
+
"preamble",
|
|
83
|
+
]) {
|
|
84
|
+
pushField(result, root, key, prefix);
|
|
85
|
+
}
|
|
86
|
+
pushRoleMessages(result, root, "messages", prefix);
|
|
87
|
+
pushRoleMessages(result, root, "input", prefix);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return result;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function sha256(text: string): string {
|
|
94
|
+
return createHash("sha256").update(text, "utf8").digest("hex");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function latestSystemPromptSha256(entries: readonly CustomEntryLike[]): string | undefined {
|
|
98
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
99
|
+
const entry = entries[index];
|
|
100
|
+
if (entry?.type !== "custom" || entry.customType !== SYSTEM_PROMPT_ENTRY_TYPE) continue;
|
|
101
|
+
if (!isRecord(entry.data)) continue;
|
|
102
|
+
if (typeof entry.data.systemPromptSha256 === "string") {
|
|
103
|
+
return entry.data.systemPromptSha256;
|
|
104
|
+
}
|
|
105
|
+
// Compatibility with snapshots written before the hash field existed.
|
|
106
|
+
if (typeof entry.data.systemPrompt === "string") {
|
|
107
|
+
return sha256(entry.data.systemPrompt);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "system-prompt-omni",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Display, export, and record the effective pi coding agent system prompt",
|
|
6
|
+
"keywords": ["pi-package", "pi-extension", "system-prompt", "debugging", "recorder"],
|
|
7
|
+
"license": "Apache-2.0",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/weiwch/system-prompt-omni"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/weiwch/system-prompt-omni#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/weiwch/system-prompt-omni/issues"
|
|
15
|
+
},
|
|
16
|
+
"files": ["extensions", "lib"],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"test": "node --test test/*.test.ts"
|
|
19
|
+
},
|
|
20
|
+
"peerDependencies": {
|
|
21
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
22
|
+
"@earendil-works/pi-tui": "*"
|
|
23
|
+
},
|
|
24
|
+
"pi": {
|
|
25
|
+
"extensions": ["./extensions"]
|
|
26
|
+
}
|
|
27
|
+
}
|