promptlike 0.5.0 → 0.6.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/CHANGELOG.md +35 -0
- package/README.md +101 -0
- package/dist/commands/config.js +41 -0
- package/dist/commands/diff.js +59 -0
- package/dist/commands/history.js +63 -0
- package/dist/commands/import.js +250 -0
- package/dist/commands/list.js +4 -0
- package/dist/commands/log.js +48 -0
- package/dist/commands/rollback.js +88 -0
- package/dist/commands/stats.js +112 -0
- package/dist/commands/suggest.js +244 -0
- package/dist/commands/sync.js +4 -0
- package/dist/index.js +59 -0
- package/dist/lib/api-client.js +91 -8
- package/dist/lib/diff.js +149 -0
- package/dist/lib/frontmatter.js +67 -0
- package/dist/lib/libraryCache.js +222 -0
- package/dist/lib/promptVariables.js +4 -2
- package/dist/lib/rank.js +123 -0
- package/dist/lib/scanners/index.js +252 -0
- package/dist/lib/secretGuard.js +92 -0
- package/dist/lib/settings.js +105 -0
- package/package.json +1 -1
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `ple rollback <name> <version> [--yes]` — restore an old version (W1-4).
|
|
4
|
+
*
|
|
5
|
+
* Non-destructive, same as the web: the chosen version is copied forward as
|
|
6
|
+
* a NEW version; nothing is deleted, so a rollback can itself be rolled back.
|
|
7
|
+
* Asks first on a terminal; scripts must pass `--yes`.
|
|
8
|
+
*/
|
|
9
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
12
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
13
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
14
|
+
}
|
|
15
|
+
Object.defineProperty(o, k2, desc);
|
|
16
|
+
}) : (function(o, m, k, k2) {
|
|
17
|
+
if (k2 === undefined) k2 = k;
|
|
18
|
+
o[k2] = m[k];
|
|
19
|
+
}));
|
|
20
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
21
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
22
|
+
}) : function(o, v) {
|
|
23
|
+
o["default"] = v;
|
|
24
|
+
});
|
|
25
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
26
|
+
var ownKeys = function(o) {
|
|
27
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
28
|
+
var ar = [];
|
|
29
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
30
|
+
return ar;
|
|
31
|
+
};
|
|
32
|
+
return ownKeys(o);
|
|
33
|
+
};
|
|
34
|
+
return function (mod) {
|
|
35
|
+
if (mod && mod.__esModule) return mod;
|
|
36
|
+
var result = {};
|
|
37
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
38
|
+
__setModuleDefault(result, mod);
|
|
39
|
+
return result;
|
|
40
|
+
};
|
|
41
|
+
})();
|
|
42
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
43
|
+
exports.rollbackCommand = rollbackCommand;
|
|
44
|
+
const readline = __importStar(require("readline"));
|
|
45
|
+
const api_client_1 = require("../lib/api-client");
|
|
46
|
+
const format_1 = require("../lib/format");
|
|
47
|
+
const history_1 = require("./history");
|
|
48
|
+
function defaultConfirm(question) {
|
|
49
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
50
|
+
return new Promise((resolve) => {
|
|
51
|
+
rl.question(question, (answer) => {
|
|
52
|
+
rl.close();
|
|
53
|
+
resolve(/^y(es)?$/i.test(answer.trim()));
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
async function rollbackCommand(name, ref, options = {}, deps = {}) {
|
|
58
|
+
const prompt = await (0, history_1.resolveForHistory)(name, options.project);
|
|
59
|
+
if (!prompt) {
|
|
60
|
+
process.exitCode = 1;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const history = await (0, api_client_1.getPromptHistory)(prompt.id);
|
|
64
|
+
const target = (0, history_1.findVersion)(history.versions, ref);
|
|
65
|
+
if (!target)
|
|
66
|
+
throw (0, history_1.versionNotFound)(ref, history.versions);
|
|
67
|
+
const current = (0, history_1.currentVersion)(history);
|
|
68
|
+
if (current && current.id === target.id) {
|
|
69
|
+
console.log(format_1.c.muted(`v${target.version_number} is already the current version — nothing to do.`));
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (!options.yes) {
|
|
73
|
+
const interactive = deps.isTTY ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
74
|
+
if (!interactive) {
|
|
75
|
+
throw new Error('Refusing to roll back without confirmation. Re-run with --yes.');
|
|
76
|
+
}
|
|
77
|
+
const ok = await (deps.confirm ?? defaultConfirm)(`Restore '${history.title}' to v${target.version_number} (${(0, history_1.semverOf)(target)})? ` +
|
|
78
|
+
`This adds a new version; nothing is deleted. [y/N] `);
|
|
79
|
+
if (!ok) {
|
|
80
|
+
console.log(format_1.c.muted('Cancelled.'));
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const res = await (0, api_client_1.rollbackPrompt)(history.id, target.id);
|
|
85
|
+
const newNo = res.new_version_number != null ? `v${res.new_version_number}` : 'a new version';
|
|
86
|
+
console.log(format_1.c.success(`✓ Restored v${target.version_number} as ${newNo}`) + format_1.c.muted(` — ${history.title}`));
|
|
87
|
+
console.log(format_1.c.muted(`Undo with: ple rollback "${history.title}" ${current ? `v${current.version_number}` : '<version>'}`));
|
|
88
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `ple stats [--range 7|30|365]` — the Insights panel in the terminal (W1-1).
|
|
4
|
+
*
|
|
5
|
+
* Same numbers as /dashboard/insights: uses in the window, where they came
|
|
6
|
+
* from (web / CLI / agents), the most used prompts and the ones gathering
|
|
7
|
+
* dust. Free accounts get a 7-day view; asking for more says so plainly
|
|
8
|
+
* instead of silently shrinking the window.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.parseRange = parseRange;
|
|
12
|
+
exports.renderStats = renderStats;
|
|
13
|
+
exports.statsCommand = statsCommand;
|
|
14
|
+
const api_client_1 = require("../lib/api-client");
|
|
15
|
+
const local_1 = require("./local");
|
|
16
|
+
const format_1 = require("../lib/format");
|
|
17
|
+
const libraryCache_1 = require("../lib/libraryCache");
|
|
18
|
+
const RANGES = [7, 30, 365];
|
|
19
|
+
const SURFACE_LABELS = {
|
|
20
|
+
web: 'Web',
|
|
21
|
+
cli: 'CLI',
|
|
22
|
+
mcp_tool: 'MCP tool',
|
|
23
|
+
mcp_prompt: 'MCP slash',
|
|
24
|
+
mcp_resource: 'MCP @-mention',
|
|
25
|
+
extension: 'Extension',
|
|
26
|
+
hook: 'Agent hook',
|
|
27
|
+
repo: 'Repo',
|
|
28
|
+
api: 'API',
|
|
29
|
+
unknown: 'Other',
|
|
30
|
+
};
|
|
31
|
+
/** Parse `--range`; accepts 7/30/365 (also "12m"/"1y" for the year). */
|
|
32
|
+
function parseRange(value) {
|
|
33
|
+
if (!value)
|
|
34
|
+
return 7;
|
|
35
|
+
const v = value.trim().toLowerCase();
|
|
36
|
+
if (v === '12m' || v === '1y' || v === 'year')
|
|
37
|
+
return 365;
|
|
38
|
+
const n = Number.parseInt(v, 10);
|
|
39
|
+
if (RANGES.includes(n))
|
|
40
|
+
return n;
|
|
41
|
+
throw new Error(`--range must be one of ${RANGES.join(', ')}.`);
|
|
42
|
+
}
|
|
43
|
+
function bar(count, max, width = 20) {
|
|
44
|
+
const n = max > 0 ? Math.max(1, Math.round((count / max) * width)) : 0;
|
|
45
|
+
return '█'.repeat(n);
|
|
46
|
+
}
|
|
47
|
+
function renderStats(s) {
|
|
48
|
+
const out = [];
|
|
49
|
+
const window = s.range_days === 365 ? '12 months' : `${s.range_days} days`;
|
|
50
|
+
out.push(format_1.c.title(`Usage — last ${window}`));
|
|
51
|
+
if (s.locked) {
|
|
52
|
+
out.push(format_1.c.warn(`Free keeps a 7-day view (you asked for ${s.requested_days}). Your history is kept — Pro unlocks it.`));
|
|
53
|
+
}
|
|
54
|
+
if (s.total === 0) {
|
|
55
|
+
out.push(format_1.c.muted('No uses in this period yet. `ple get <name>` and `ple copy <name>` count here.'));
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
const nonWeb = Math.round((s.non_web / s.total) * 100);
|
|
59
|
+
out.push(`${format_1.c.label('Uses')} ${s.total}`);
|
|
60
|
+
out.push(`${format_1.c.label('Outside the web')} ${nonWeb}%`);
|
|
61
|
+
if (s.suggestion > 0)
|
|
62
|
+
out.push(`${format_1.c.label('From suggestions')} ${s.suggestion}`);
|
|
63
|
+
out.push('');
|
|
64
|
+
out.push(format_1.c.label('Where'));
|
|
65
|
+
const max = Math.max(...s.by_surface.map((x) => x.count));
|
|
66
|
+
for (const x of s.by_surface) {
|
|
67
|
+
const label = (SURFACE_LABELS[x.surface] ?? x.surface).padEnd(14);
|
|
68
|
+
out.push(` ${label} ${String(x.count).padStart(5)} ${format_1.c.accent(bar(x.count, max))}`);
|
|
69
|
+
}
|
|
70
|
+
if (s.by_client.length > 0) {
|
|
71
|
+
out.push(format_1.c.muted(` agents: ${s.by_client.map((x) => `${x.client} (${x.count})`).join(', ')}`));
|
|
72
|
+
}
|
|
73
|
+
out.push('');
|
|
74
|
+
out.push(format_1.c.label('Most used'));
|
|
75
|
+
s.top_prompts.forEach((p, i) => {
|
|
76
|
+
out.push(` ${String(i + 1).padStart(2)}. ${p.title} ${format_1.c.muted(`${p.count}×`)}`);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
if (s.unused_30d.length > 0) {
|
|
80
|
+
out.push('');
|
|
81
|
+
out.push(format_1.c.label('Not used in 30 days'));
|
|
82
|
+
for (const p of s.unused_30d) {
|
|
83
|
+
out.push(` ${p.title} ${format_1.c.muted(p.last_used_at ? `last ${(0, format_1.timeAgo)(p.last_used_at)}` : 'never used')}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
async function statsCommand(options = {}) {
|
|
89
|
+
const range = parseRange(options.range);
|
|
90
|
+
if ((0, local_1.isSignedOut)()) {
|
|
91
|
+
throw new Error('Usage stats live in your account. Run `ple login` first (local prompts are not tracked).');
|
|
92
|
+
}
|
|
93
|
+
await (0, api_client_1.ensureAuthed)();
|
|
94
|
+
const insights = await (0, api_client_1.getUsageInsights)(range);
|
|
95
|
+
if (!insights || !insights.available) {
|
|
96
|
+
console.log(format_1.c.muted('Usage tracking is not switched on for your account yet — check back soon.'));
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
// Suggestion impressions are counted on this machine only (W1-5): the
|
|
100
|
+
// server sees an accepted suggestion (via=suggestion), never a shown one.
|
|
101
|
+
const shown = (0, libraryCache_1.readState)().impressions;
|
|
102
|
+
if (options.json) {
|
|
103
|
+
console.log(JSON.stringify({ ...insights, local_suggestions_shown: shown }, null, 2));
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
for (const line of renderStats(insights))
|
|
107
|
+
console.log(line);
|
|
108
|
+
if (shown > 0) {
|
|
109
|
+
const rate = Math.round((insights.suggestion / shown) * 100);
|
|
110
|
+
console.log(format_1.c.muted(`\nSuggestions shown on this machine: ${shown} · picked up: ${insights.suggestion} (${rate}%, this window)`));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `ple suggest "<text>" [--json] [--limit 3] [--hook] [--refresh-cache]` (W1-5).
|
|
4
|
+
*
|
|
5
|
+
* Which saved prompt fits this task? Matching is LOCAL (cached library, or the
|
|
6
|
+
* local store when signed out) — the text never leaves the machine.
|
|
7
|
+
*
|
|
8
|
+
* `--hook` is the Claude Code `UserPromptSubmit` mode (plugin
|
|
9
|
+
* `scripts/suggest.sh`): reads the hook JSON from stdin, prints at most one
|
|
10
|
+
* short block that Claude Code adds to the model's context, and otherwise
|
|
11
|
+
* prints NOTHING. It is silent when:
|
|
12
|
+
* - suggestions are off (`PLE_SUGGEST=off`, plugin option, `ple config set suggest off`)
|
|
13
|
+
* - the message is a slash command or shorter than 20 characters
|
|
14
|
+
* - nothing scores above the noise gate
|
|
15
|
+
* - every match was already suggested in this session
|
|
16
|
+
* - anything at all goes wrong (the hook must never get in the way)
|
|
17
|
+
* It never waits on the network: a stale/missing cache triggers a detached
|
|
18
|
+
* background refresh and this run stays silent or uses the old snapshot.
|
|
19
|
+
*/
|
|
20
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
23
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
24
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(o, k2, desc);
|
|
27
|
+
}) : (function(o, m, k, k2) {
|
|
28
|
+
if (k2 === undefined) k2 = k;
|
|
29
|
+
o[k2] = m[k];
|
|
30
|
+
}));
|
|
31
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
32
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
33
|
+
}) : function(o, v) {
|
|
34
|
+
o["default"] = v;
|
|
35
|
+
});
|
|
36
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
37
|
+
var ownKeys = function(o) {
|
|
38
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
39
|
+
var ar = [];
|
|
40
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
41
|
+
return ar;
|
|
42
|
+
};
|
|
43
|
+
return ownKeys(o);
|
|
44
|
+
};
|
|
45
|
+
return function (mod) {
|
|
46
|
+
if (mod && mod.__esModule) return mod;
|
|
47
|
+
var result = {};
|
|
48
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
49
|
+
__setModuleDefault(result, mod);
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
52
|
+
})();
|
|
53
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
54
|
+
exports.HOOK_BUDGET_MS = exports.HOOK_MIN_CHARS = void 0;
|
|
55
|
+
exports.stripPasted = stripPasted;
|
|
56
|
+
exports.hookShouldSkip = hookShouldSkip;
|
|
57
|
+
exports.renderHookBlock = renderHookBlock;
|
|
58
|
+
exports.runHook = runHook;
|
|
59
|
+
exports.refreshLibraryCache = refreshLibraryCache;
|
|
60
|
+
exports.suggestCommand = suggestCommand;
|
|
61
|
+
const api_client_1 = require("../lib/api-client");
|
|
62
|
+
const config_1 = require("../lib/config");
|
|
63
|
+
const format_1 = require("../lib/format");
|
|
64
|
+
const libraryCache_1 = require("../lib/libraryCache");
|
|
65
|
+
const store = __importStar(require("../lib/localStore"));
|
|
66
|
+
const rank_1 = require("../lib/rank");
|
|
67
|
+
const settings_1 = require("../lib/settings");
|
|
68
|
+
/** Hook input must be at least this long to be worth matching. */
|
|
69
|
+
exports.HOOK_MIN_CHARS = 20;
|
|
70
|
+
/** Hard wall-clock budget for hook mode (Claude Code waits on us). */
|
|
71
|
+
exports.HOOK_BUDGET_MS = 800;
|
|
72
|
+
/** Text considered from a message (pasted logs can be huge). */
|
|
73
|
+
const MAX_TASK_CHARS = 2000;
|
|
74
|
+
function parseLimit(raw) {
|
|
75
|
+
const n = Number.parseInt(raw ?? '3', 10);
|
|
76
|
+
return Number.isFinite(n) ? Math.max(1, Math.min(n, 10)) : 3;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Drop pasted blocks (`<pasted_content id=…>…</pasted_content id=…>`, see the
|
|
80
|
+
* Claude Code hooks docs) — a pasted stack trace says little about which of the
|
|
81
|
+
* user's prompts fits, and would drown the actual request.
|
|
82
|
+
*/
|
|
83
|
+
function stripPasted(text) {
|
|
84
|
+
return text.replace(/<pasted_content\b[^>]*>[\s\S]*?<\/pasted_content\b[^>]*>/g, ' ');
|
|
85
|
+
}
|
|
86
|
+
/** The hook's silence rules for the message itself. */
|
|
87
|
+
function hookShouldSkip(prompt) {
|
|
88
|
+
const t = prompt.trim();
|
|
89
|
+
return t.startsWith('/') || t.length < exports.HOOK_MIN_CHARS;
|
|
90
|
+
}
|
|
91
|
+
/** Library to match against, without touching the network. */
|
|
92
|
+
function localLibrary(now) {
|
|
93
|
+
const config = (0, config_1.readConfig)();
|
|
94
|
+
if (!config)
|
|
95
|
+
return { entries: (0, libraryCache_1.entriesFromLocal)(store.list()), signedIn: false, stale: false };
|
|
96
|
+
const cache = (0, libraryCache_1.readCache)(config.user_id);
|
|
97
|
+
if (!cache)
|
|
98
|
+
return { entries: [], signedIn: true, stale: true };
|
|
99
|
+
return { entries: cache.entries, signedIn: true, stale: !(0, libraryCache_1.isFresh)(cache, now) };
|
|
100
|
+
}
|
|
101
|
+
/** The ≤3-line block Claude Code injects into the model's context. */
|
|
102
|
+
function renderHookBlock(ranked, signedIn) {
|
|
103
|
+
const list = ranked
|
|
104
|
+
.map(({ item }) => `"${item.name}"${item.uses ? ` (used ${item.uses}×)` : ''}`)
|
|
105
|
+
.join(', ');
|
|
106
|
+
const how = signedIn
|
|
107
|
+
? 'fetch it with the promptlike get_prompt tool (name as quoted, via: "suggestion")'
|
|
108
|
+
: 'read it with `PLE_SURFACE=hook PLE_VIA=suggestion ple get "<name>"`';
|
|
109
|
+
return [
|
|
110
|
+
`PromptLikeEngineer: the user has saved prompts that may fit this request: ${list}.`,
|
|
111
|
+
`If one is clearly relevant, ${how} and follow it; otherwise ignore this note and do not mention it.`,
|
|
112
|
+
].join('\n');
|
|
113
|
+
}
|
|
114
|
+
function readStdin(budgetMs) {
|
|
115
|
+
if (process.stdin.isTTY)
|
|
116
|
+
return Promise.resolve('');
|
|
117
|
+
return new Promise((resolve) => {
|
|
118
|
+
let data = '';
|
|
119
|
+
const done = () => resolve(data);
|
|
120
|
+
const timer = setTimeout(done, budgetMs);
|
|
121
|
+
timer.unref();
|
|
122
|
+
process.stdin.setEncoding('utf-8');
|
|
123
|
+
process.stdin.on('data', (chunk) => {
|
|
124
|
+
if (data.length < 1000000)
|
|
125
|
+
data += chunk;
|
|
126
|
+
});
|
|
127
|
+
process.stdin.on('end', () => {
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
done();
|
|
130
|
+
});
|
|
131
|
+
process.stdin.on('error', () => {
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
done();
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/** Hook mode. Every failure path is silent and exits 0. */
|
|
138
|
+
async function runHook(raw, now = Date.now()) {
|
|
139
|
+
if (!(0, settings_1.suggestEnabled)())
|
|
140
|
+
return '';
|
|
141
|
+
let input;
|
|
142
|
+
try {
|
|
143
|
+
input = JSON.parse(raw);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return '';
|
|
147
|
+
}
|
|
148
|
+
const prompt = typeof input.prompt === 'string' ? input.prompt : '';
|
|
149
|
+
const sessionId = typeof input.session_id === 'string' ? input.session_id : undefined;
|
|
150
|
+
if (hookShouldSkip(prompt))
|
|
151
|
+
return '';
|
|
152
|
+
const { entries, signedIn, stale } = localLibrary(now);
|
|
153
|
+
if (signedIn && stale)
|
|
154
|
+
(0, libraryCache_1.startBackgroundRefresh)({ now });
|
|
155
|
+
if (entries.length === 0)
|
|
156
|
+
return '';
|
|
157
|
+
const text = stripPasted(prompt).slice(0, MAX_TASK_CHARS);
|
|
158
|
+
const state = (0, libraryCache_1.readState)();
|
|
159
|
+
const already = (0, libraryCache_1.shownIn)(state, sessionId);
|
|
160
|
+
const fresh = (0, rank_1.rankLibrary)(entries, text, 3 + already.size).filter((r) => !already.has(r.item.id)).slice(0, 3);
|
|
161
|
+
if (fresh.length === 0)
|
|
162
|
+
return '';
|
|
163
|
+
(0, libraryCache_1.recordShown)(state, sessionId, fresh.map((r) => r.item.id), now);
|
|
164
|
+
return renderHookBlock(fresh, signedIn);
|
|
165
|
+
}
|
|
166
|
+
/** Refresh the account cache now (used by `--refresh-cache`, `ple list`, `ple sync`). */
|
|
167
|
+
async function refreshLibraryCache() {
|
|
168
|
+
const config = (0, config_1.readConfig)();
|
|
169
|
+
if (!config)
|
|
170
|
+
return 0;
|
|
171
|
+
await (0, api_client_1.ensureAuthed)();
|
|
172
|
+
const entries = await (0, libraryCache_1.fetchAccountEntries)((p) => (0, api_client_1.listPrompts)(p));
|
|
173
|
+
(0, libraryCache_1.writeCache)(config.user_id, entries);
|
|
174
|
+
return entries.length;
|
|
175
|
+
}
|
|
176
|
+
async function suggestCommand(words, options = {}) {
|
|
177
|
+
if (options.refreshCache) {
|
|
178
|
+
try {
|
|
179
|
+
await refreshLibraryCache();
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
process.exitCode = 1;
|
|
183
|
+
}
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (options.hook) {
|
|
187
|
+
const deadline = setTimeout(() => process.exit(0), exports.HOOK_BUDGET_MS);
|
|
188
|
+
deadline.unref();
|
|
189
|
+
try {
|
|
190
|
+
const out = await runHook(await readStdin(exports.HOOK_BUDGET_MS / 2));
|
|
191
|
+
if (out)
|
|
192
|
+
process.stdout.write(out + '\n');
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
// never surface an error into the user's session
|
|
196
|
+
}
|
|
197
|
+
process.exitCode = 0;
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const text = words.join(' ').trim();
|
|
201
|
+
if (!text)
|
|
202
|
+
throw new Error('Describe the task: ple suggest "review this pull request"');
|
|
203
|
+
const limit = parseLimit(options.limit);
|
|
204
|
+
// Interactive: a missing/stale account cache is refreshed first (network is fine here).
|
|
205
|
+
const config = (0, config_1.readConfig)();
|
|
206
|
+
let entries;
|
|
207
|
+
if (!config) {
|
|
208
|
+
entries = (0, libraryCache_1.entriesFromLocal)(store.list());
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
const cache = (0, libraryCache_1.readCache)(config.user_id);
|
|
212
|
+
if (cache && (0, libraryCache_1.isFresh)(cache)) {
|
|
213
|
+
entries = cache.entries;
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
await refreshLibraryCache();
|
|
217
|
+
entries = (0, libraryCache_1.readCache)(config.user_id)?.entries ?? [];
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const ranked = (0, rank_1.rankLibrary)(entries, text, limit);
|
|
221
|
+
if (options.json) {
|
|
222
|
+
console.log(JSON.stringify(ranked.map(({ item, score }) => ({
|
|
223
|
+
id: item.id,
|
|
224
|
+
name: item.name,
|
|
225
|
+
title: item.title,
|
|
226
|
+
repo: item.repo ?? null,
|
|
227
|
+
uses: item.uses ?? null,
|
|
228
|
+
score,
|
|
229
|
+
})), null, 2));
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (ranked.length === 0) {
|
|
233
|
+
console.log(format_1.c.muted('No saved prompt fits that task.'));
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
for (const { item, score } of ranked) {
|
|
237
|
+
const meta = [item.repo, item.uses ? `used ${item.uses}×` : '', `score ${score}`].filter(Boolean).join(' · ');
|
|
238
|
+
console.log(`${format_1.c.title(item.title)} ${format_1.c.muted(meta)}`);
|
|
239
|
+
if (item.description)
|
|
240
|
+
console.log(format_1.c.muted(` ${item.description}`));
|
|
241
|
+
}
|
|
242
|
+
const first = ranked[0].item.name;
|
|
243
|
+
console.log(format_1.c.muted(`\nUse one: ple get "${first}"`));
|
|
244
|
+
}
|
package/dist/commands/sync.js
CHANGED
|
@@ -49,6 +49,7 @@ exports.syncCommand = syncCommand;
|
|
|
49
49
|
const store = __importStar(require("../lib/localStore"));
|
|
50
50
|
const api_client_1 = require("../lib/api-client");
|
|
51
51
|
const format_1 = require("../lib/format");
|
|
52
|
+
const libraryCache_1 = require("../lib/libraryCache");
|
|
52
53
|
/** The import endpoint caps one request at 50 records. */
|
|
53
54
|
const BATCH = 50;
|
|
54
55
|
async function syncCommand(options = {}) {
|
|
@@ -100,6 +101,9 @@ async function syncCommand(options = {}) {
|
|
|
100
101
|
break;
|
|
101
102
|
}
|
|
102
103
|
}
|
|
104
|
+
// New prompts should be suggestible right away (W1-5 cache) — detached.
|
|
105
|
+
if (imported > 0)
|
|
106
|
+
(0, libraryCache_1.startBackgroundRefresh)({ force: true });
|
|
103
107
|
const tagNote = serverCarriesTags && tagsApplied > 0 ? ` (+${tagsApplied} tag link${tagsApplied === 1 ? '' : 's'})` : '';
|
|
104
108
|
console.log(format_1.c.success(`✓ Uploaded ${imported} prompt${imported === 1 ? '' : 's'}${tagNote}`));
|
|
105
109
|
// Each shortfall gets its own line with its own fix — "12 of 20 synced"
|
package/dist/index.js
CHANGED
|
@@ -23,6 +23,13 @@ const loop_1 = require("./commands/loop");
|
|
|
23
23
|
const save_1 = require("./commands/save");
|
|
24
24
|
const sync_1 = require("./commands/sync");
|
|
25
25
|
const export_1 = require("./commands/export");
|
|
26
|
+
const stats_1 = require("./commands/stats");
|
|
27
|
+
const import_1 = require("./commands/import");
|
|
28
|
+
const log_1 = require("./commands/log");
|
|
29
|
+
const diff_1 = require("./commands/diff");
|
|
30
|
+
const rollback_1 = require("./commands/rollback");
|
|
31
|
+
const suggest_1 = require("./commands/suggest");
|
|
32
|
+
const config_1 = require("./commands/config");
|
|
26
33
|
/** A single global try/catch — consistent error output for every command. */
|
|
27
34
|
function runWithErrorHandler(fn) {
|
|
28
35
|
return async (...args) => {
|
|
@@ -114,4 +121,56 @@ program
|
|
|
114
121
|
.command('search <keyword>')
|
|
115
122
|
.description('Search titles and descriptions (signed out: also local prompt bodies and tags)')
|
|
116
123
|
.action(runWithErrorHandler(search_1.searchCommand));
|
|
124
|
+
program
|
|
125
|
+
.command('stats')
|
|
126
|
+
.description('How your library is used — uses by surface, most used, gathering dust')
|
|
127
|
+
.option('-r, --range <days>', 'Window: 7, 30 or 365 (Free: 7)', '7')
|
|
128
|
+
.option('--json', 'Print the raw summary as JSON')
|
|
129
|
+
.action(runWithErrorHandler(stats_1.statsCommand));
|
|
130
|
+
program
|
|
131
|
+
.command('import')
|
|
132
|
+
.description('Bring in prompts you already have: .claude/commands, SKILL.md, .cursor/commands, ~/.codex/prompts')
|
|
133
|
+
.option('--scan', 'Scan this repo and your home folder for agent prompt files')
|
|
134
|
+
.option('--dry-run', 'Only show what was found, import nothing')
|
|
135
|
+
.option('-a, --all', 'Import everything new without asking')
|
|
136
|
+
.option('--project <repo>', 'Import into this repo (signed in)')
|
|
137
|
+
.action(runWithErrorHandler((opts) => (0, import_1.importCommand)(opts)));
|
|
138
|
+
program
|
|
139
|
+
.command('log <name>')
|
|
140
|
+
.description('Version history of a prompt (* = current)')
|
|
141
|
+
.option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
|
|
142
|
+
.option('-l, --limit <n>', 'Max versions to show (default 20)', '20')
|
|
143
|
+
.option('--json', 'Print as JSON')
|
|
144
|
+
.action(runWithErrorHandler(log_1.logCommand));
|
|
145
|
+
program
|
|
146
|
+
.command('diff <name> [a] [b]')
|
|
147
|
+
.description('Diff two versions (default: previous ↔ current). Refs: 3, v3 or 1.0.2')
|
|
148
|
+
.option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
|
|
149
|
+
.option('--no-color', 'Plain output (automatic when piped)')
|
|
150
|
+
.action(runWithErrorHandler((name, a, b, opts) => (0, diff_1.diffCommand)(name, a, b, opts)));
|
|
151
|
+
program
|
|
152
|
+
.command('suggest [text...]')
|
|
153
|
+
.description('Which saved prompt fits this task? Local match — the text never leaves your machine')
|
|
154
|
+
.option('--json', 'Print matches as JSON')
|
|
155
|
+
.option('-l, --limit <n>', 'Max matches (default 3)', '3')
|
|
156
|
+
.option('--hook', 'Claude Code UserPromptSubmit mode: read hook JSON on stdin, print a short hint or nothing')
|
|
157
|
+
.option('--refresh-cache', 'Refresh the local library cache from your account and exit')
|
|
158
|
+
.action(runWithErrorHandler((text, opts) => (0, suggest_1.suggestCommand)(text ?? [], opts)));
|
|
159
|
+
const configCmd = program
|
|
160
|
+
.command('config')
|
|
161
|
+
.description('CLI preferences (suggest on|off)');
|
|
162
|
+
configCmd
|
|
163
|
+
.command('get [key]')
|
|
164
|
+
.description('Show a setting (or all)')
|
|
165
|
+
.action(runWithErrorHandler(config_1.configGetCommand));
|
|
166
|
+
configCmd
|
|
167
|
+
.command('set <key> <value>')
|
|
168
|
+
.description('Change a setting, e.g. `ple config set suggest off`')
|
|
169
|
+
.action(runWithErrorHandler(config_1.configSetCommand));
|
|
170
|
+
program
|
|
171
|
+
.command('rollback <name> <version>')
|
|
172
|
+
.description('Restore an old version as a new one — nothing is deleted')
|
|
173
|
+
.option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
|
|
174
|
+
.option('-y, --yes', 'Skip the confirmation prompt')
|
|
175
|
+
.action(runWithErrorHandler((name, version, opts) => (0, rollback_1.rollbackCommand)(name, version, opts)));
|
|
117
176
|
program.parseAsync(process.argv);
|
package/dist/lib/api-client.js
CHANGED
|
@@ -14,13 +14,20 @@
|
|
|
14
14
|
* - map 429 / error bodies to clean, user-facing Error messages
|
|
15
15
|
*/
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.USE_SURFACES = void 0;
|
|
17
18
|
exports.login = login;
|
|
18
19
|
exports.ensureAuthed = ensureAuthed;
|
|
19
20
|
exports.listPrompts = listPrompts;
|
|
20
21
|
exports.importPrompts = importPrompts;
|
|
22
|
+
exports.getImportedHashes = getImportedHashes;
|
|
23
|
+
exports.getAccountHeadroom = getAccountHeadroom;
|
|
21
24
|
exports.listProjects = listProjects;
|
|
22
25
|
exports.getPromptById = getPromptById;
|
|
26
|
+
exports.getPromptHistory = getPromptHistory;
|
|
27
|
+
exports.rollbackPrompt = rollbackPrompt;
|
|
28
|
+
exports.buildUseEventBody = buildUseEventBody;
|
|
23
29
|
exports.recordPromptUse = recordPromptUse;
|
|
30
|
+
exports.getUsageInsights = getUsageInsights;
|
|
24
31
|
const constants_1 = require("./constants");
|
|
25
32
|
const config_1 = require("./config");
|
|
26
33
|
const NOT_LOGGED_IN = 'Not logged in. Run `ple login` first.';
|
|
@@ -195,19 +202,47 @@ async function listPrompts(params = {}) {
|
|
|
195
202
|
* the caller batches and reports whatever came back rather than assuming
|
|
196
203
|
* everything landed.
|
|
197
204
|
*/
|
|
198
|
-
async function importPrompts(prompts) {
|
|
205
|
+
async function importPrompts(prompts, options = {}) {
|
|
199
206
|
const res = await apiFetch('/api/prompts/import', {
|
|
200
207
|
method: 'POST',
|
|
201
|
-
body: { prompts },
|
|
208
|
+
body: { prompts, ...options },
|
|
202
209
|
});
|
|
203
210
|
return {
|
|
204
211
|
imported: res.imported ?? 0,
|
|
205
212
|
failed: res.failed ?? 0,
|
|
206
213
|
skippedInvalid: res.skippedInvalid ?? 0,
|
|
207
214
|
truncatedByQuota: res.truncatedByQuota ?? 0,
|
|
215
|
+
skippedDuplicate: res.skippedDuplicate ?? 0,
|
|
216
|
+
projectId: res.projectId,
|
|
208
217
|
tagsApplied: res.tagsApplied,
|
|
209
218
|
};
|
|
210
219
|
}
|
|
220
|
+
/**
|
|
221
|
+
* GET /api/prompts/import — sha256 of everything already brought in with
|
|
222
|
+
* `ple import --scan`. Older servers (no GET handler) → empty set, so the
|
|
223
|
+
* preview just cannot mark "already imported"; the POST still dedupes.
|
|
224
|
+
*/
|
|
225
|
+
async function getImportedHashes() {
|
|
226
|
+
try {
|
|
227
|
+
const res = await apiFetch('/api/prompts/import');
|
|
228
|
+
return new Set(res.knownHashes ?? []);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
return new Set();
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async function getAccountHeadroom() {
|
|
235
|
+
try {
|
|
236
|
+
const res = await apiFetch('/api/account/limits');
|
|
237
|
+
return {
|
|
238
|
+
promptsRemaining: res.usage?.promptsRemaining ?? null,
|
|
239
|
+
isPro: res.plan?.isPro === true,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
return { promptsRemaining: null, isPro: false };
|
|
244
|
+
}
|
|
245
|
+
}
|
|
211
246
|
/** GET /api/projects — list the user's accessible repos (for --project resolution). */
|
|
212
247
|
async function listProjects() {
|
|
213
248
|
const res = await apiFetch('/api/projects', {
|
|
@@ -227,14 +262,62 @@ async function getPromptById(id) {
|
|
|
227
262
|
throw err;
|
|
228
263
|
}
|
|
229
264
|
}
|
|
265
|
+
/** GET /api/prompts/{id} → history for `ple log/diff/rollback`. */
|
|
266
|
+
async function getPromptHistory(id) {
|
|
267
|
+
const res = await apiFetch(`/api/prompts/${id}`);
|
|
268
|
+
if (!res.prompt)
|
|
269
|
+
throw new Error('Prompt not found.');
|
|
270
|
+
return {
|
|
271
|
+
id: res.prompt.id,
|
|
272
|
+
title: res.prompt.title,
|
|
273
|
+
current_version_id: res.prompt.current_version_id ?? null,
|
|
274
|
+
versions: Array.isArray(res.prompt.versions) ? res.prompt.versions : [],
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* POST /api/prompts/{id}/rollback — restores a version as a NEW version
|
|
279
|
+
* (nothing is deleted; the history keeps growing).
|
|
280
|
+
*/
|
|
281
|
+
async function rollbackPrompt(id, versionId) {
|
|
282
|
+
return apiFetch(`/api/prompts/${id}/rollback`, {
|
|
283
|
+
method: 'POST',
|
|
284
|
+
body: { versionId },
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
/** Kullanım yüzeyleri — sunucudaki `USE_SURFACES` ile aynı küme (W1-1). */
|
|
288
|
+
exports.USE_SURFACES = [
|
|
289
|
+
'web', 'cli', 'mcp_tool', 'mcp_prompt', 'mcp_resource', 'extension', 'hook', 'repo', 'api', 'unknown',
|
|
290
|
+
];
|
|
291
|
+
/**
|
|
292
|
+
* Build the use-event body. `PLE_SURFACE` / `PLE_VIA` let a wrapper (e.g. an
|
|
293
|
+
* agent hook calling `ple get`) attribute the use correctly; unknown values
|
|
294
|
+
* fall back to the CLI defaults rather than failing the command.
|
|
295
|
+
*/
|
|
296
|
+
function buildUseEventBody(opts = {}, env = process.env) {
|
|
297
|
+
const envSurface = env.PLE_SURFACE?.trim().toLowerCase();
|
|
298
|
+
const surface = exports.USE_SURFACES.includes(envSurface ?? '')
|
|
299
|
+
? envSurface
|
|
300
|
+
: 'cli';
|
|
301
|
+
const via = env.PLE_VIA?.trim().toLowerCase() === 'suggestion' ? 'suggestion' : 'direct';
|
|
302
|
+
const body = { surface, client: `ple-cli/${constants_1.CLI_VERSION}`, via };
|
|
303
|
+
if (typeof opts.version === 'number' && Number.isInteger(opts.version) && opts.version > 0) {
|
|
304
|
+
body.version = opts.version;
|
|
305
|
+
}
|
|
306
|
+
return body;
|
|
307
|
+
}
|
|
230
308
|
/**
|
|
231
|
-
* Kullanım kaydı (REV-6) — `ple copy/get/show` sonrası fire-and-forget.
|
|
232
|
-
*
|
|
233
|
-
*
|
|
234
|
-
*
|
|
309
|
+
* Kullanım kaydı (REV-6 → W1-1) — `ple copy/get/show` sonrası fire-and-forget.
|
|
310
|
+
* Gövde yüzeyi (`surface: 'cli'`) ve istemciyi taşır; sunucu olay defterine
|
|
311
|
+
* yazar (defter yoksa eski sayaca düşer). Hata YUTULUR: telemetri asıl
|
|
312
|
+
* komutu asla kırmaz.
|
|
235
313
|
*/
|
|
236
|
-
function recordPromptUse(promptId) {
|
|
237
|
-
apiFetch(`/api/prompts/${promptId}/use`, { method: 'POST' }).catch(() => {
|
|
314
|
+
function recordPromptUse(promptId, opts = {}) {
|
|
315
|
+
apiFetch(`/api/prompts/${promptId}/use`, { method: 'POST', body: buildUseEventBody(opts) }).catch(() => {
|
|
238
316
|
/* sessiz — telemetri */
|
|
239
317
|
});
|
|
240
318
|
}
|
|
319
|
+
/** GET /api/insights?range= — usage summary for `ple stats`. */
|
|
320
|
+
async function getUsageInsights(range) {
|
|
321
|
+
const res = await apiFetch('/api/insights', { query: { range } });
|
|
322
|
+
return res.insights ?? null;
|
|
323
|
+
}
|