@americanumberoneaokgoodtimes/p-plugin 0.0.0-stage → 1.0.1

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/plugin.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://antigravity.google/schemas/v1/plugin.json",
3
+ "name": "prompt-manager",
4
+ "displayName": "Prompt Manager",
5
+ "version": "1.0.0",
6
+ "description": "Save, edit, and trigger reusable prompt instructions by ID using /p <id> and /p e <id> <text>.",
7
+ "logo": "assets/logo.svg",
8
+ "repository": "https://github.com/americanumberoneaokgoodtimes/prompt-manager-plugin-opencode-claude-agy-etc",
9
+ "license": "MIT",
10
+ "keywords": [
11
+ "prompts",
12
+ "instructions",
13
+ "macros",
14
+ "shortcuts",
15
+ "productivity"
16
+ ],
17
+ "suggestedPrompts": [
18
+ "/p",
19
+ "List my saved prompts",
20
+ "Explain how to save and run prompts with /p"
21
+ ]
22
+ }
@@ -0,0 +1,49 @@
1
+ import fs from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { executePromptCommand } from "./handler.mjs";
4
+ import { isDirectEntrypoint, resolveStorePath } from "./store.mjs";
5
+
6
+ function readStdin() {
7
+ try {
8
+ return fs.readFileSync(0, "utf8");
9
+ } catch {
10
+ return "";
11
+ }
12
+ }
13
+
14
+ export function toClaudeResponse(result) {
15
+ const body =
16
+ result.action === "send" && result.found
17
+ ? `${result.systemInstruction}\n\n<resolved-user-instruction>\n${result.resolvedInstruction}\n</resolved-user-instruction>`
18
+ : result.systemInstruction;
19
+
20
+ return {
21
+ hookSpecificOutput: {
22
+ hookEventName: "UserPromptSubmit",
23
+ additionalContext: `<prompt-manager-hook action="${result.action}">\n${body}\n</prompt-manager-hook>`,
24
+ },
25
+ };
26
+ }
27
+
28
+ function main() {
29
+ const raw = readStdin();
30
+ if (!raw.trim()) {
31
+ return;
32
+ }
33
+ const input = JSON.parse(raw);
34
+ const promptText = input.prompt ?? input.lastUserInput ?? "";
35
+ const result = executePromptCommand(promptText, resolveStorePath());
36
+ if (!result) {
37
+ return;
38
+ }
39
+
40
+ process.stdout.write(JSON.stringify(toClaudeResponse(result)) + "\n");
41
+ }
42
+
43
+ if (isDirectEntrypoint(import.meta.url, process.argv[1], fileURLToPath)) {
44
+ try {
45
+ main();
46
+ } catch (err) {
47
+ process.stderr.write(`[prompt-manager claude hook error] ${err?.stack || err}\n`);
48
+ }
49
+ }
@@ -0,0 +1,197 @@
1
+ import {
2
+ deletePrompt,
3
+ getPrompt,
4
+ listPrompts,
5
+ parseSlashCommand,
6
+ resolveStorePath,
7
+ setPrompt,
8
+ } from "./store.mjs";
9
+
10
+ export function makePreview(text, maxLen = 100) {
11
+ const oneLine = String(text ?? "").replace(/\s+/g, " ").trim();
12
+ if (oneLine.length <= maxLen) {
13
+ return oneLine;
14
+ }
15
+ return `${oneLine.slice(0, maxLen - 3)}...`;
16
+ }
17
+
18
+ function formatAvailableIds(entries) {
19
+ if (entries.length === 0) {
20
+ return "(none)";
21
+ }
22
+ return entries.map((e) => `\`${e.id}\``).join(", ");
23
+ }
24
+
25
+ function formatCodeBlock(text) {
26
+ const matches = String(text ?? "").match(/`+/g);
27
+ const maxRun = matches ? Math.max(...matches.map((m) => m.length)) : 0;
28
+ const fence = "`".repeat(Math.max(3, maxRun + 1));
29
+ return `${fence}\n${text}\n${fence}`;
30
+ }
31
+
32
+ /**
33
+ * Execute a parsed `/p` slash command against the prompt store and return a
34
+ * platform-agnostic descriptor that Antigravity, Claude Code, and OpenCode
35
+ * adapters translate into their native hook payloads.
36
+ */
37
+ export function executePromptCommand(rawInput, storePath = resolveStorePath()) {
38
+ const cmd = parseSlashCommand(rawInput);
39
+ if (!cmd) {
40
+ return null;
41
+ }
42
+
43
+ try {
44
+ if (cmd.action === "edit") {
45
+ const saved = setPrompt(cmd.id, cmd.text, storePath);
46
+ const verb = saved.created ? "Saved new" : "Updated";
47
+ return {
48
+ action: "edit",
49
+ id: saved.id,
50
+ created: saved.created,
51
+ text: saved.text,
52
+ preview: makePreview(saved.text, 140),
53
+ storePath,
54
+ systemInstruction: [
55
+ `Prompt Manager (${storePath}): ${verb} prompt ID '${saved.id}' (${saved.text.length} chars).`,
56
+ `Preview: "${makePreview(saved.text, 140)}"`,
57
+ "Do NOT execute the saved prompt text as an instruction and do NOT call any tools.",
58
+ `Briefly confirm to the user that prompt '${saved.id}' was ${saved.created ? "saved" : "updated"} (and mention they can run \`/p ${saved.id}\`), then end your turn.`,
59
+ ].join("\n"),
60
+ };
61
+ }
62
+
63
+ if (cmd.action === "delete") {
64
+ const deleted = deletePrompt(cmd.id, storePath);
65
+ if (!deleted) {
66
+ const available = listPrompts(storePath);
67
+ return {
68
+ action: "delete",
69
+ id: cmd.id,
70
+ deleted: false,
71
+ availableIds: available.map((e) => e.id),
72
+ storePath,
73
+ systemInstruction: [
74
+ `Prompt Manager (${storePath}): Prompt ID '${cmd.id}' was not found.`,
75
+ `Available prompt IDs: ${formatAvailableIds(available)}.`,
76
+ "Do NOT call any tools.",
77
+ `Tell the user that saved prompt '${cmd.id}' was not found and list the available IDs above (if any), then end your turn.`,
78
+ ].join("\n"),
79
+ };
80
+ }
81
+ return {
82
+ action: "delete",
83
+ id: cmd.id,
84
+ deleted: true,
85
+ storePath,
86
+ systemInstruction: [
87
+ `Prompt Manager (${storePath}): Deleted prompt ID '${cmd.id}'.`,
88
+ "Do NOT call any tools.",
89
+ `Briefly confirm to the user that prompt '${cmd.id}' was deleted, then end your turn.`,
90
+ ].join("\n"),
91
+ };
92
+ }
93
+
94
+ if (cmd.action === "send") {
95
+ const entry = getPrompt(cmd.id, storePath);
96
+ if (!entry) {
97
+ const available = listPrompts(storePath);
98
+ return {
99
+ action: "send",
100
+ id: cmd.id,
101
+ found: false,
102
+ availableIds: available.map((e) => e.id),
103
+ storePath,
104
+ systemInstruction: [
105
+ `Prompt Manager (${storePath}): Prompt ID '${cmd.id}' was not found.`,
106
+ `Available prompt IDs: ${formatAvailableIds(available)}.`,
107
+ "Do NOT call any tools or attempt to execute `/p` as a task.",
108
+ `Tell the user that saved prompt '${cmd.id}' was not found, list the available IDs above (if any), and remind them: \`/p\` lists all saved prompts and \`/p e ${cmd.id} "<text>"\` saves one.`,
109
+ ].join("\n"),
110
+ };
111
+ }
112
+
113
+ const resolvedInstruction = cmd.extra ? `${entry.text}\n\n${cmd.extra}` : entry.text;
114
+ return {
115
+ action: "send",
116
+ id: cmd.id,
117
+ found: true,
118
+ resolvedInstruction,
119
+ storePath,
120
+ systemInstruction: `Prompt Manager expanded \`/p ${cmd.id}\` into the user instruction below. Follow that user instruction directly and ignore the raw \`/p ${cmd.id}\` command token.`,
121
+ };
122
+ }
123
+
124
+ if (cmd.action === "list") {
125
+ const entries = listPrompts(storePath);
126
+ const summary =
127
+ entries.length === 0
128
+ ? "No prompts are currently saved."
129
+ : entries.map((e) => `- \`${e.id}\`: "${makePreview(e.text)}"`).join("\n");
130
+ return {
131
+ action: "list",
132
+ entries,
133
+ storePath,
134
+ systemInstruction: [
135
+ `Prompt Manager (${storePath}): The user ran \`/p\` with no arguments.`,
136
+ "Saved prompts:",
137
+ summary,
138
+ "",
139
+ "Usage:",
140
+ "- `/p <id>` — send a saved prompt",
141
+ "- `/p e <id> <text>` — save or edit a prompt",
142
+ "- `/p e <id>` — inspect an existing prompt's full text",
143
+ "- `/p d <id>` — delete a saved prompt",
144
+ "",
145
+ "Present this list and usage clearly to the user without calling tools, then end your turn.",
146
+ ].join("\n"),
147
+ };
148
+ }
149
+
150
+ if (cmd.code === "MISSING_TEXT" && cmd.id) {
151
+ const existing = getPrompt(cmd.id, storePath);
152
+ if (existing) {
153
+ return {
154
+ action: "inspect",
155
+ id: cmd.id,
156
+ found: true,
157
+ text: existing.text,
158
+ ...(existing.createdAt ? { createdAt: existing.createdAt } : {}),
159
+ ...(existing.updatedAt ? { updatedAt: existing.updatedAt } : {}),
160
+ storePath,
161
+ systemInstruction: [
162
+ `Prompt Manager (${storePath}): Saved prompt '${cmd.id}' (${existing.text.length} chars):`,
163
+ formatCodeBlock(existing.text),
164
+ "",
165
+ `To update it, run \`/p e ${cmd.id} "<new text>"\`. To delete it, run \`/p d ${cmd.id}\`.`,
166
+ "Do NOT execute the saved prompt text and do NOT call any tools. Present the saved prompt text and usage clearly to the user, then end your turn.",
167
+ ].join("\n"),
168
+ };
169
+ }
170
+ }
171
+
172
+ return {
173
+ action: "error",
174
+ code: cmd.code,
175
+ id: cmd.id,
176
+ message: cmd.message,
177
+ storePath,
178
+ systemInstruction: [
179
+ `Prompt Manager: ${cmd.message}`,
180
+ "Do NOT call any tools. Present this message clearly to the user and end your turn.",
181
+ ].join("\n"),
182
+ };
183
+ } catch (err) {
184
+ const message = err?.message || String(err);
185
+ return {
186
+ action: "error",
187
+ code: "STORE_ERROR",
188
+ id: cmd.id,
189
+ message,
190
+ storePath,
191
+ systemInstruction: [
192
+ `Prompt Manager (${storePath}): ${message}`,
193
+ "Do NOT call any tools. Report this prompt store error clearly to the user and end your turn.",
194
+ ].join("\n"),
195
+ };
196
+ }
197
+ }
@@ -0,0 +1,206 @@
1
+ import readline from "node:readline";
2
+ import { fileURLToPath } from "node:url";
3
+ import {
4
+ deletePrompt,
5
+ getPrompt,
6
+ isDirectEntrypoint,
7
+ listPrompts,
8
+ resolveStorePath,
9
+ setPrompt,
10
+ } from "./store.mjs";
11
+
12
+ export const SERVER_INFO = {
13
+ name: "prompt-manager",
14
+ version: "1.0.0",
15
+ };
16
+
17
+ export const TOOLS = [
18
+ {
19
+ name: "list_prompts",
20
+ description: "List all saved prompts with their IDs, text, and timestamps.",
21
+ inputSchema: {
22
+ type: "object",
23
+ properties: {},
24
+ additionalProperties: false,
25
+ },
26
+ },
27
+ {
28
+ name: "get_prompt",
29
+ description: "Retrieve the full instruction text for a saved prompt ID.",
30
+ inputSchema: {
31
+ type: "object",
32
+ properties: {
33
+ id: {
34
+ type: "string",
35
+ description: "The saved prompt ID to look up.",
36
+ },
37
+ },
38
+ required: ["id"],
39
+ additionalProperties: false,
40
+ },
41
+ },
42
+ {
43
+ name: "save_prompt",
44
+ description: "Create or update a saved prompt instruction under the given ID.",
45
+ inputSchema: {
46
+ type: "object",
47
+ properties: {
48
+ id: {
49
+ type: "string",
50
+ description: "The prompt ID (cannot contain whitespace or be 'e' or 'd').",
51
+ },
52
+ text: {
53
+ type: "string",
54
+ description: "The prompt instruction text to save.",
55
+ },
56
+ },
57
+ required: ["id", "text"],
58
+ additionalProperties: false,
59
+ },
60
+ },
61
+ {
62
+ name: "delete_prompt",
63
+ description: "Delete a saved prompt by ID.",
64
+ inputSchema: {
65
+ type: "object",
66
+ properties: {
67
+ id: {
68
+ type: "string",
69
+ description: "The saved prompt ID to delete.",
70
+ },
71
+ },
72
+ required: ["id"],
73
+ additionalProperties: false,
74
+ },
75
+ },
76
+ ];
77
+
78
+ function send(msg) {
79
+ process.stdout.write(JSON.stringify(msg) + "\n");
80
+ }
81
+
82
+ function sendResult(id, result) {
83
+ send({ jsonrpc: "2.0", id, result });
84
+ }
85
+
86
+ function sendError(id, code, message) {
87
+ send({ jsonrpc: "2.0", id, error: { code, message } });
88
+ }
89
+
90
+ function textResult(text, isError = false) {
91
+ return isError
92
+ ? { content: [{ type: "text", text }], isError: true }
93
+ : { content: [{ type: "text", text }] };
94
+ }
95
+
96
+ export function handleToolCall(name, args, storePath = resolveStorePath()) {
97
+ const safeArgs = args && typeof args === "object" && !Array.isArray(args) ? args : {};
98
+ switch (name) {
99
+ case "list_prompts": {
100
+ const entries = listPrompts(storePath);
101
+ return textResult(JSON.stringify({ storePath, prompts: entries }, null, 2));
102
+ }
103
+ case "get_prompt": {
104
+ if (typeof safeArgs.id !== "string" || !safeArgs.id.trim()) {
105
+ return textResult("Missing required string parameter 'id'.", true);
106
+ }
107
+ const entry = getPrompt(safeArgs.id, storePath);
108
+ if (!entry) {
109
+ return textResult(`Prompt '${safeArgs.id}' not found.`, true);
110
+ }
111
+ return textResult(JSON.stringify(entry, null, 2));
112
+ }
113
+ case "save_prompt": {
114
+ if (typeof safeArgs.id !== "string" || !safeArgs.id.trim()) {
115
+ return textResult("Missing required string parameter 'id'.", true);
116
+ }
117
+ if (typeof safeArgs.text !== "string" || !safeArgs.text.trim()) {
118
+ return textResult("Missing required string parameter 'text'.", true);
119
+ }
120
+ const saved = setPrompt(safeArgs.id, safeArgs.text, storePath);
121
+ return textResult(JSON.stringify(saved, null, 2));
122
+ }
123
+ case "delete_prompt": {
124
+ if (typeof safeArgs.id !== "string" || !safeArgs.id.trim()) {
125
+ return textResult("Missing required string parameter 'id'.", true);
126
+ }
127
+ const deleted = deletePrompt(safeArgs.id, storePath);
128
+ if (!deleted) {
129
+ return textResult(`Prompt '${safeArgs.id}' not found.`, true);
130
+ }
131
+ return textResult(`Deleted prompt '${safeArgs.id}'.`);
132
+ }
133
+ default:
134
+ return textResult(`Unknown tool '${name}'.`, true);
135
+ }
136
+ }
137
+
138
+ export function handleMessage(msg, storePath = resolveStorePath(), sendFn = send) {
139
+ if (!msg || typeof msg !== "object") {
140
+ return;
141
+ }
142
+ const { id, method, params } = msg;
143
+
144
+ // Notifications have no id and expect no response.
145
+ if (id === undefined || id === null) {
146
+ return;
147
+ }
148
+
149
+ switch (method) {
150
+ case "initialize":
151
+ sendFn({
152
+ jsonrpc: "2.0",
153
+ id,
154
+ result: {
155
+ protocolVersion: params?.protocolVersion || "2024-11-05",
156
+ capabilities: {
157
+ tools: {},
158
+ },
159
+ serverInfo: SERVER_INFO,
160
+ },
161
+ });
162
+ return;
163
+ case "ping":
164
+ sendFn({ jsonrpc: "2.0", id, result: {} });
165
+ return;
166
+ case "tools/list":
167
+ sendFn({ jsonrpc: "2.0", id, result: { tools: TOOLS } });
168
+ return;
169
+ case "tools/call":
170
+ try {
171
+ const result = handleToolCall(params?.name, params?.arguments, storePath);
172
+ sendFn({ jsonrpc: "2.0", id, result });
173
+ } catch (err) {
174
+ sendFn({ jsonrpc: "2.0", id, result: textResult(err?.message || String(err), true) });
175
+ }
176
+ return;
177
+ default:
178
+ sendFn({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });
179
+ }
180
+ }
181
+
182
+ if (isDirectEntrypoint(import.meta.url, process.argv[1], fileURLToPath)) {
183
+ process.stdout.on("error", (err) => {
184
+ if (err?.code === "EPIPE") {
185
+ process.exit(0);
186
+ }
187
+ });
188
+
189
+ const rl = readline.createInterface({
190
+ input: process.stdin,
191
+ crlfDelay: Infinity,
192
+ });
193
+
194
+ rl.on("line", (line) => {
195
+ const trimmed = line.trim();
196
+ if (!trimmed) {
197
+ return;
198
+ }
199
+ try {
200
+ const msg = JSON.parse(trimmed);
201
+ handleMessage(msg);
202
+ } catch (err) {
203
+ sendError(null, -32700, `Parse error: ${err?.message || String(err)}`);
204
+ }
205
+ });
206
+ }
@@ -0,0 +1,117 @@
1
+ import fs from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { executePromptCommand } from "./handler.mjs";
4
+ import { isDirectEntrypoint, resolveStorePath } from "./store.mjs";
5
+
6
+ function readStdin() {
7
+ try {
8
+ return fs.readFileSync(0, "utf8");
9
+ } catch {
10
+ return "";
11
+ }
12
+ }
13
+
14
+ /**
15
+ * Determine if this PreInvocation call is the first model invocation for the
16
+ * latest user turn. Normally invocationNum === 0 on every new turn; if a client
17
+ * keeps incrementing invocationNum across turns, fall back to inspecting the
18
+ * tail of transcriptPath for any PLANNER_RESPONSE after the last USER_INPUT.
19
+ */
20
+ export function isFirstInvocationOfTurn(input) {
21
+ if (input.invocationNum === 0) {
22
+ return true;
23
+ }
24
+ const transcriptPath = input.transcriptPath;
25
+ if (!transcriptPath || !fs.existsSync(transcriptPath)) {
26
+ return false;
27
+ }
28
+ try {
29
+ const stat = fs.statSync(transcriptPath);
30
+ if (stat.size === 0) {
31
+ return false;
32
+ }
33
+ const chunkSize = 65536;
34
+ const maxScanBytes = 1024 * 1024;
35
+ let offset = stat.size;
36
+ let scanned = 0;
37
+ let trailing = "";
38
+ const fd = fs.openSync(transcriptPath, "r");
39
+ try {
40
+ while (offset > 0 && scanned < maxScanBytes) {
41
+ const readBytes = Math.min(offset, chunkSize);
42
+ offset -= readBytes;
43
+ scanned += readBytes;
44
+ const buf = Buffer.alloc(readBytes);
45
+ fs.readSync(fd, buf, 0, readBytes, offset);
46
+ const lines = (buf.toString("utf8") + trailing).split(/\r?\n/);
47
+ trailing = offset > 0 ? (lines.shift() ?? "") : "";
48
+ // Scan backwards: if we hit USER_INPUT before PLANNER_RESPONSE, no model
49
+ // response has happened yet for the current user prompt.
50
+ for (let i = lines.length - 1; i >= 0; i--) {
51
+ const line = lines[i].trim();
52
+ if (!line) continue;
53
+ try {
54
+ const entry = JSON.parse(line);
55
+ if (entry.type === "USER_INPUT") {
56
+ return true;
57
+ }
58
+ if (entry.type === "PLANNER_RESPONSE") {
59
+ return false;
60
+ }
61
+ } catch {
62
+ // Ignore malformed or partial lines.
63
+ }
64
+ }
65
+ }
66
+ } finally {
67
+ fs.closeSync(fd);
68
+ }
69
+ } catch {
70
+ return false;
71
+ }
72
+ return false;
73
+ }
74
+
75
+ export function toAntigravityResponse(result) {
76
+ const injectSteps = [
77
+ {
78
+ systemMessage: {
79
+ systemMessage: result.systemInstruction,
80
+ },
81
+ },
82
+ ];
83
+ if (result.action === "send" && result.found) {
84
+ injectSteps.push({ userMessage: result.resolvedInstruction });
85
+ }
86
+ return { injectSteps };
87
+ }
88
+
89
+ function main() {
90
+ const raw = readStdin();
91
+ if (!raw.trim()) {
92
+ process.stdout.write("{}\n");
93
+ return;
94
+ }
95
+ const input = JSON.parse(raw);
96
+ if (!isFirstInvocationOfTurn(input)) {
97
+ process.stdout.write("{}\n");
98
+ return;
99
+ }
100
+
101
+ const result = executePromptCommand(input.lastUserInput ?? "", resolveStorePath());
102
+ if (!result) {
103
+ process.stdout.write("{}\n");
104
+ return;
105
+ }
106
+
107
+ process.stdout.write(JSON.stringify(toAntigravityResponse(result)) + "\n");
108
+ }
109
+
110
+ if (isDirectEntrypoint(import.meta.url, process.argv[1], fileURLToPath)) {
111
+ try {
112
+ main();
113
+ } catch (err) {
114
+ process.stderr.write(`[prompt-manager hook error] ${err?.stack || err}\n`);
115
+ process.stdout.write("{}\n");
116
+ }
117
+ }