promptlike 0.10.1 → 0.12.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.
@@ -0,0 +1,351 @@
1
+ "use strict";
2
+ /**
3
+ * `ple feedback` — tell the maker what is missing, broken or confusing, from the terminal or from an agent.
4
+ *
5
+ * ple feedback [--type bug|missing|idea|prompt] [--prompt <title|id>] [--email <e>] [--agent <name>] [--json] "<message>"
6
+ * ple feedback list [--status new|triaged|done|wontfix] [--limit <n>] [--json] (owner)
7
+ * ple feedback close <id> --commit <sha> [--status done|wontfix] [--json] (owner)
8
+ *
9
+ * Built for scripts and agents: it never asks a question, never waits for input, and ends with a
10
+ * documented exit code. Exit codes (also in `--help` and the README):
11
+ * 0 sent (or, for list / close, done)
12
+ * 1 something unexpected (also: not signed in / not allowed, for the owner commands)
13
+ * 2 usage or validation error: nothing was sent
14
+ * 3 rate limited: try again after the printed delay
15
+ * 4 server or network problem: the report was saved to the local queue and is sent by a later `ple` command
16
+ *
17
+ * What leaves the machine: the type, the message, the prompt TITLE or id if you gave one, the email if you
18
+ * gave one, who wrote it (person or agent), and four short context values (see lib/feedbackInput.ts). Never a
19
+ * prompt body, a file, a path or an argument value. With a session the report is tied to your account; without
20
+ * one it is anonymous.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.FEEDBACK_EXIT_CODES_HELP = exports.EXIT_QUEUED = exports.EXIT_RATE_LIMITED = exports.EXIT_USAGE = exports.EXIT_UNEXPECTED = exports.EXIT_SENT = void 0;
24
+ exports.feedbackCommand = feedbackCommand;
25
+ exports.feedbackListCommand = feedbackListCommand;
26
+ exports.feedbackCloseCommand = feedbackCloseCommand;
27
+ const api_client_1 = require("../lib/api-client");
28
+ const config_1 = require("../lib/config");
29
+ const constants_1 = require("../lib/constants");
30
+ const feedbackApi_1 = require("../lib/feedbackApi");
31
+ const feedbackInput_1 = require("../lib/feedbackInput");
32
+ const feedbackQueue_1 = require("../lib/feedbackQueue");
33
+ const feedbackSource_1 = require("../lib/feedbackSource");
34
+ const format_1 = require("../lib/format");
35
+ exports.EXIT_SENT = 0;
36
+ exports.EXIT_UNEXPECTED = 1;
37
+ exports.EXIT_USAGE = 2;
38
+ exports.EXIT_RATE_LIMITED = 3;
39
+ exports.EXIT_QUEUED = 4;
40
+ /** The documented table; `--help` and the tests print/compare it. */
41
+ exports.FEEDBACK_EXIT_CODES_HELP = [
42
+ '0 sent (list / close: done)',
43
+ '1 unexpected problem (list / close: also not signed in, or not allowed)',
44
+ '2 usage or validation error — nothing was sent',
45
+ '3 rate limited — try again after the delay shown',
46
+ '4 server or network problem — saved to the local queue, sent by a later `ple` command',
47
+ ];
48
+ // ---------------------------------------------------------------------------
49
+ // Output
50
+ // ---------------------------------------------------------------------------
51
+ function setExit(code) {
52
+ process.exitCode = code;
53
+ }
54
+ /** `--json`: one line on stdout, always, for every outcome. */
55
+ function emitJson(obj) {
56
+ console.log(JSON.stringify(obj));
57
+ }
58
+ function fail(json, code, error, extra = {}) {
59
+ setExit(code);
60
+ if (json)
61
+ emitJson({ ok: false, exit_code: code, error, ...extra });
62
+ else
63
+ console.error(format_1.c.error(`✗ ${error}`));
64
+ }
65
+ // ---------------------------------------------------------------------------
66
+ // ple feedback "<message>"
67
+ // ---------------------------------------------------------------------------
68
+ async function defaultToken() {
69
+ if ((0, config_1.configStatus)() !== 'valid')
70
+ return {};
71
+ try {
72
+ await (0, api_client_1.ensureAuthed)();
73
+ return { token: (0, config_1.readConfig)()?.access_token };
74
+ }
75
+ catch (err) {
76
+ // The server could not be reached to refresh the session: it cannot take the report either.
77
+ if (err instanceof api_client_1.NetworkError || err instanceof api_client_1.RequestTimeoutError)
78
+ return { unreachable: err.message };
79
+ return {}; // a dead session must not block a report: it goes out anonymously
80
+ }
81
+ }
82
+ async function feedbackCommand(messageParts, opts = {}, deps = {}) {
83
+ const json = opts.json === true;
84
+ try {
85
+ await submit(Array.isArray(messageParts) ? messageParts.join(' ') : String(messageParts ?? ''), opts, deps, json);
86
+ }
87
+ catch (err) {
88
+ fail(json, exports.EXIT_UNEXPECTED, `Unexpected error: ${(0, format_1.safeText)(err instanceof Error ? err.message : String(err)).slice(0, 200)}`);
89
+ }
90
+ }
91
+ async function submit(message, opts, deps, json) {
92
+ const env = deps.env ?? process.env;
93
+ let agentFlag;
94
+ if (opts.agent !== undefined) {
95
+ agentFlag = opts.agent;
96
+ if (!(0, feedbackInput_1.sanitizeAgentName)(agentFlag)) {
97
+ return fail(json, exports.EXIT_USAGE, '--agent needs a name made of letters, digits, ".", "_" or "-" (max 64).');
98
+ }
99
+ }
100
+ const checked = (0, feedbackInput_1.checkFeedbackFields)({ type: opts.type, message, prompt: opts.prompt, email: opts.email });
101
+ if (!checked.ok)
102
+ return fail(json, exports.EXIT_USAGE, checked.error);
103
+ const who = (0, feedbackSource_1.detectSource)(env, agentFlag);
104
+ const payload = {
105
+ type: checked.value.type,
106
+ message: checked.value.message,
107
+ ...(checked.value.prompt_ref ? { prompt_ref: checked.value.prompt_ref } : {}),
108
+ ...(checked.value.email ? { email: checked.value.email } : {}),
109
+ source: who.source,
110
+ ...(who.agent_name ? { agent_name: who.agent_name } : {}),
111
+ client: 'cli',
112
+ context: (0, feedbackInput_1.buildContext)({ cliVersion: constants_1.CLI_VERSION, commandName: 'feedback', flagNames: deps.flagNames }),
113
+ };
114
+ const auth = await (deps.token ?? defaultToken)();
115
+ const send = deps.send ?? ((p, o) => (0, feedbackApi_1.sendFeedback)(p, o));
116
+ let result;
117
+ let attachedAccount = Boolean(auth.token);
118
+ if (auth.unreachable) {
119
+ result = { kind: 'unavailable', message: auth.unreachable };
120
+ attachedAccount = false;
121
+ }
122
+ else {
123
+ result = await send(payload, { token: auth.token });
124
+ if (result.kind === 'auth' && auth.token) {
125
+ // The server did not accept the session: the report still matters, send it without one.
126
+ attachedAccount = false;
127
+ result = await send(payload, { token: undefined });
128
+ }
129
+ }
130
+ const base = { type: payload.type, source: payload.source, ...(payload.agent_name ? { agent_name: payload.agent_name } : {}) };
131
+ switch (result.kind) {
132
+ case 'sent':
133
+ setExit(exports.EXIT_SENT);
134
+ if (json)
135
+ emitJson({ ok: true, ...(result.id ? { id: result.id } : {}), exit_code: exports.EXIT_SENT, ...base, account: attachedAccount });
136
+ else {
137
+ console.log(format_1.c.success('✓ Feedback sent — thank you.') + (result.id ? format_1.c.muted(` (id ${result.id})`) : ''));
138
+ console.log(format_1.c.muted(attachedAccount ? ' Tied to your account.' : ' Sent anonymously (sign in with `ple login` to attach it to your account).'));
139
+ }
140
+ return;
141
+ case 'invalid':
142
+ return fail(json, exports.EXIT_USAGE, `The server rejected the report: ${result.message}`);
143
+ case 'config':
144
+ return fail(json, exports.EXIT_USAGE, result.message);
145
+ case 'rate_limited': {
146
+ const wait = result.retryAfter;
147
+ return fail(json, exports.EXIT_RATE_LIMITED, `Rate limited. Try again${wait !== undefined ? ` in ${wait}s` : ' in a moment'}.`, { retry_after: wait ?? null });
148
+ }
149
+ case 'unavailable':
150
+ return queueIt(payload, result.message, json, env, deps, base);
151
+ case 'auth':
152
+ return fail(json, exports.EXIT_UNEXPECTED, `The server refused the report (HTTP ${result.status}).`);
153
+ default:
154
+ return fail(json, exports.EXIT_UNEXPECTED, `Unexpected answer from the server (HTTP ${result.status}): ${result.message}`);
155
+ }
156
+ }
157
+ function queueIt(payload, reason, json, env, deps, base) {
158
+ let queued;
159
+ try {
160
+ queued = (deps.queue ?? ((p) => (0, feedbackQueue_1.enqueue)(p)))(payload);
161
+ }
162
+ catch (err) {
163
+ return fail(json, exports.EXIT_UNEXPECTED, `Could not reach the server (${reason}) and could not save the report locally either: ${(0, format_1.safeText)(err instanceof Error ? err.message : String(err)).slice(0, 160)}`);
164
+ }
165
+ const sendsLater = (0, feedbackQueue_1.queueEnabled)(env);
166
+ setExit(exports.EXIT_QUEUED);
167
+ const note = sendsLater
168
+ ? 'It will be sent by a later `ple` command.'
169
+ : 'Sending later is off (PLE_FEEDBACK_QUEUE=off); run `ple feedback` again when you are online.';
170
+ if (json) {
171
+ emitJson({
172
+ ok: false,
173
+ queued: true,
174
+ exit_code: exports.EXIT_QUEUED,
175
+ queue_size: queued.size,
176
+ ...(queued.droppedOldest ? { dropped_oldest: true } : {}),
177
+ send_later: sendsLater,
178
+ error: reason,
179
+ ...base,
180
+ });
181
+ return;
182
+ }
183
+ console.error(format_1.c.warn(`⚠ Could not deliver the report (${reason})`));
184
+ console.error(format_1.c.muted(` Saved to the local queue (${queued.size} waiting${queued.droppedOldest ? ', the oldest one was dropped' : ''}). ${note}`));
185
+ }
186
+ async function ownerAuth() {
187
+ if ((0, config_1.configStatus)() !== 'valid')
188
+ return { error: 'This command needs a session. Sign in first: ple login', code: exports.EXIT_UNEXPECTED };
189
+ try {
190
+ await (0, api_client_1.ensureAuthed)();
191
+ }
192
+ catch (err) {
193
+ const message = (0, format_1.safeText)(err instanceof Error ? err.message : String(err)).slice(0, 300);
194
+ const unreachable = err instanceof api_client_1.NetworkError || err instanceof api_client_1.RequestTimeoutError;
195
+ return { error: message, code: unreachable ? exports.EXIT_QUEUED : exports.EXIT_UNEXPECTED };
196
+ }
197
+ const token = (0, config_1.readConfig)()?.access_token;
198
+ return token ? { token } : { error: 'This command needs a session. Sign in first: ple login', code: exports.EXIT_UNEXPECTED };
199
+ }
200
+ /** The same status → exit code mapping for both owner commands. Returns null when the response is a success (2xx). */
201
+ function ownerFailure(out) {
202
+ if (out.kind === 'config')
203
+ return { code: exports.EXIT_USAGE, error: out.message };
204
+ if (out.kind === 'unreachable')
205
+ return { code: exports.EXIT_QUEUED, error: `${out.message} Nothing was changed.` };
206
+ const { status, body } = out;
207
+ if (status >= 200 && status < 300)
208
+ return null;
209
+ if (status === 401)
210
+ return { code: exports.EXIT_UNEXPECTED, error: 'The server did not accept your session. Sign in again: ple login' };
211
+ if (status === 403)
212
+ return { code: exports.EXIT_UNEXPECTED, error: 'Not allowed: reading and closing feedback is limited to the owner account.' };
213
+ if (status === 429) {
214
+ return {
215
+ code: exports.EXIT_RATE_LIMITED,
216
+ error: `Rate limited. Try again${out.retryAfter !== undefined ? ` in ${out.retryAfter}s` : ' in a moment'}.`,
217
+ extra: { retry_after: out.retryAfter ?? null },
218
+ };
219
+ }
220
+ if (status === 400 || status === 404 || status === 413 || status === 422) {
221
+ const details = (0, feedbackApi_1.serverDetails)(body);
222
+ const fallback = status === 404 ? 'No feedback with that id.' : 'The server rejected the request.';
223
+ return { code: exports.EXIT_USAGE, error: (0, feedbackApi_1.serverMessage)(body, fallback) + (details ? ` (${details})` : '') };
224
+ }
225
+ if (status >= 500 || status === 408)
226
+ return { code: exports.EXIT_QUEUED, error: `The server answered HTTP ${status}. Nothing was changed.` };
227
+ return { code: exports.EXIT_UNEXPECTED, error: (0, feedbackApi_1.serverMessage)(body, `The server answered HTTP ${status}.`) };
228
+ }
229
+ const MAX_LIST_LIMIT = 200;
230
+ async function feedbackListCommand(opts = {}, deps = {}) {
231
+ const json = opts.json === true;
232
+ try {
233
+ const status = opts.status === undefined ? undefined : opts.status.trim().toLowerCase();
234
+ if (status !== undefined && !feedbackApi_1.FEEDBACK_STATUSES.includes(status)) {
235
+ return fail(json, exports.EXIT_USAGE, `--status must be one of: ${feedbackApi_1.FEEDBACK_STATUSES.join(', ')}.`);
236
+ }
237
+ let limit = 50;
238
+ if (opts.limit !== undefined) {
239
+ if (!/^\d{1,4}$/.test(opts.limit.trim()) || Number(opts.limit) < 1 || Number(opts.limit) > MAX_LIST_LIMIT) {
240
+ return fail(json, exports.EXIT_USAGE, `--limit must be a whole number from 1 to ${MAX_LIST_LIMIT}.`);
241
+ }
242
+ limit = Number(opts.limit);
243
+ }
244
+ const auth = await (deps.auth ?? ownerAuth)();
245
+ if ('error' in auth)
246
+ return fail(json, auth.code, auth.error);
247
+ const out = await (0, feedbackApi_1.request)({
248
+ method: 'GET',
249
+ path: '/api/feedback',
250
+ query: { status, limit },
251
+ token: auth.token,
252
+ timeoutMs: feedbackApi_1.OWNER_TIMEOUT_MS,
253
+ fetchImpl: deps.fetchImpl,
254
+ });
255
+ const failure = ownerFailure(out);
256
+ if (failure)
257
+ return fail(json, failure.code, failure.error, failure.extra);
258
+ if (out.kind !== 'response' || !Array.isArray(out.body.items)) {
259
+ return fail(json, exports.EXIT_UNEXPECTED, 'The server sent an unexpected answer (no "items" list). Update the CLI: npm i -g promptlike@latest');
260
+ }
261
+ const items = out.body.items;
262
+ setExit(exports.EXIT_SENT);
263
+ if (json) {
264
+ // As the server sent it: it only ever returns this to the owner.
265
+ emitJson({ ok: true, exit_code: exports.EXIT_SENT, items });
266
+ return;
267
+ }
268
+ printList(items, status);
269
+ }
270
+ catch (err) {
271
+ fail(json, exports.EXIT_UNEXPECTED, `Unexpected error: ${(0, format_1.safeText)(err instanceof Error ? err.message : String(err)).slice(0, 200)}`);
272
+ }
273
+ }
274
+ /** A field from the server, as one safe line (it is other people's text). */
275
+ function field(item, key, max) {
276
+ const v = item[key];
277
+ return typeof v === 'string' || typeof v === 'number' ? (0, format_1.truncate)((0, feedbackInput_1.cleanLine)(String(v)), max) : '';
278
+ }
279
+ function printList(items, status) {
280
+ if (items.length === 0) {
281
+ console.log(format_1.c.muted(`No feedback${status ? ` with status '${status}'` : ''}.`));
282
+ return;
283
+ }
284
+ console.log(format_1.c.label('ID STATUS TYPE FROM AGE MESSAGE'));
285
+ for (const raw of items) {
286
+ if (typeof raw !== 'object' || raw === null)
287
+ continue;
288
+ const it = raw;
289
+ const created = field(it, 'created_at', 40);
290
+ const from = it.source === 'agent' ? field(it, 'agent_name', 8) || 'agent' : 'human';
291
+ const row = [
292
+ (0, format_1.shortId)(field(it, 'id', 64) || '?').padEnd(8),
293
+ field(it, 'status', 8).padEnd(8),
294
+ field(it, 'type', 7).padEnd(7),
295
+ from.padEnd(8),
296
+ (created ? (0, format_1.timeAgo)(created) : '').padEnd(10),
297
+ field(it, 'message', 70),
298
+ ].join(' ');
299
+ console.log(row);
300
+ const extra = [
301
+ field(it, 'prompt_ref', 60) && `prompt: ${field(it, 'prompt_ref', 60)}`,
302
+ field(it, 'email', 60) && `email: ${field(it, 'email', 60)}`,
303
+ field(it, 'resolution_commit', 40) && `commit: ${field(it, 'resolution_commit', 40)}`,
304
+ ].filter(Boolean);
305
+ if (extra.length > 0)
306
+ console.log(format_1.c.muted(` ${extra.join(' · ')}`));
307
+ }
308
+ console.log(format_1.c.muted(`\n${items.length} item${items.length === 1 ? '' : 's'}. Close one: ple feedback close <id> --commit <sha>`));
309
+ }
310
+ const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
311
+ const SHA_RE = /^[0-9a-f]{7,40}$/i;
312
+ async function feedbackCloseCommand(id, opts = {}, deps = {}) {
313
+ const json = opts.json === true;
314
+ try {
315
+ if (!ID_RE.test(id ?? ''))
316
+ return fail(json, exports.EXIT_USAGE, 'The id looks wrong: use the full id from `ple feedback list --json`.');
317
+ const status = (opts.status === undefined ? 'done' : opts.status.trim().toLowerCase());
318
+ if (status !== 'done' && status !== 'wontfix')
319
+ return fail(json, exports.EXIT_USAGE, '--status must be done or wontfix.');
320
+ const commit = opts.commit?.trim();
321
+ if (commit === undefined || commit === '') {
322
+ if (status === 'done')
323
+ return fail(json, exports.EXIT_USAGE, '--commit <sha> is required: name the commit that fixed it.');
324
+ }
325
+ else if (!SHA_RE.test(commit)) {
326
+ return fail(json, exports.EXIT_USAGE, '--commit must be a git commit hash (7 to 40 hex characters).');
327
+ }
328
+ const auth = await (deps.auth ?? ownerAuth)();
329
+ if ('error' in auth)
330
+ return fail(json, auth.code, auth.error);
331
+ const out = await (0, feedbackApi_1.request)({
332
+ method: 'PATCH',
333
+ path: `/api/feedback/${encodeURIComponent(id)}`,
334
+ body: { status, ...(commit ? { resolution_commit: commit.toLowerCase() } : {}) },
335
+ token: auth.token,
336
+ timeoutMs: feedbackApi_1.OWNER_TIMEOUT_MS,
337
+ fetchImpl: deps.fetchImpl,
338
+ });
339
+ const failure = ownerFailure(out);
340
+ if (failure)
341
+ return fail(json, failure.code, failure.error, failure.extra);
342
+ setExit(exports.EXIT_SENT);
343
+ if (json)
344
+ emitJson({ ok: true, exit_code: exports.EXIT_SENT, id, status, ...(commit ? { resolution_commit: commit.toLowerCase() } : {}) });
345
+ else
346
+ console.log(format_1.c.success(`✓ ${(0, format_1.shortId)(id)} → ${status}`) + (commit ? format_1.c.muted(` (commit ${commit.toLowerCase().slice(0, 12)})`) : ''));
347
+ }
348
+ catch (err) {
349
+ fail(json, exports.EXIT_UNEXPECTED, `Unexpected error: ${(0, format_1.safeText)(err instanceof Error ? err.message : String(err)).slice(0, 200)}`);
350
+ }
351
+ }
@@ -4,6 +4,7 @@
4
4
  *
5
5
  * ple import --scan # your agent folders (W1-2 — strategy F15, "activation = investment")
6
6
  * ple import github:owner/repo # a public GitHub repo, per-file license gate (importGithub.ts)
7
+ * ple import ple:user/repo # public prompts of another PromptLikeEngineer user (importPle.ts)
7
8
  * ple import --check [--apply] # follow upstream changes of what came from GitHub (importCheck.ts)
8
9
  *
9
10
  * `--scan`:
@@ -64,6 +65,8 @@ Object.defineProperty(exports, "parseSelection", { enumerable: true, get: functi
64
65
  const local_1 = require("./local");
65
66
  const format_1 = require("../lib/format");
66
67
  const importGithub_1 = require("./importGithub");
68
+ const importPle_1 = require("./importPle");
69
+ const pleSpec_1 = require("../lib/pleSpec");
67
70
  const importCheck_1 = require("./importCheck");
68
71
  function toImportable(cand) {
69
72
  return {
@@ -88,13 +91,15 @@ async function importCommand(options = {}, deps = {}) {
88
91
  if (options.apply && !options.check) {
89
92
  throw new Error('--apply only works together with --check.');
90
93
  }
94
+ if (options.source && (0, pleSpec_1.isPleSource)(options.source))
95
+ return (0, importPle_1.importPleCommand)(options.source, options, deps);
91
96
  if (options.source)
92
97
  return (0, importGithub_1.importGithubCommand)(options.source, options, deps);
93
98
  if (options.check)
94
99
  return (0, importCheck_1.importCheckCommand)({ apply: options.apply, dryRun: options.dryRun });
95
100
  if (!options.scan) {
96
101
  throw new Error('Nothing to import. Use `ple import --scan` to find prompts in your agent folders, ' +
97
- '`ple import github:<owner>/<repo>` to bring in a public GitHub repo, or `ple import --check` to look for upstream changes.');
102
+ '`ple import github:<owner>/<repo>` to bring in a public GitHub repo, `ple import ple:<user>/<repo>` for public prompts on PromptLikeEngineer, or `ple import --check` to look for upstream changes.');
98
103
  }
99
104
  const signedOut = (0, local_1.isSignedOut)();
100
105
  const destination = signedOut ? 'your local store' : 'your account';
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ /**
3
+ * `ple import ple:<user>/<repo>[/<prompt>]` — copy PUBLIC prompts of another PromptLikeEngineer user into your library.
4
+ *
5
+ * ple import ple:zeynepaslierhan/ortak-web --dry-run # what is there, and under which license
6
+ * ple import ple:zeynepaslierhan/ortak-web --all # every prompt of the repo, no questions
7
+ * ple import ple:zeynepaslierhan/ortak-web/Code Review # one prompt (title or id)
8
+ *
9
+ * Works signed out (it reads the public pages' API; no token is read or sent). Signed out → the local store,
10
+ * signed in → the account (`--project <repo>` picks the repo). Each copy keeps its source: user, repo, prompt id,
11
+ * the version it was read at and the repo's license, in the description and (signed in) as provenance, so a re-run
12
+ * skips what is already there. A prompt of a repo without a declared license is copied with a notice, never
13
+ * silently. Updates are not followed yet: a newer version upstream is reported, not applied.
14
+ */
15
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ var desc = Object.getOwnPropertyDescriptor(m, k);
18
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
19
+ desc = { enumerable: true, get: function() { return m[k]; } };
20
+ }
21
+ Object.defineProperty(o, k2, desc);
22
+ }) : (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ o[k2] = m[k];
25
+ }));
26
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
27
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
28
+ }) : function(o, v) {
29
+ o["default"] = v;
30
+ });
31
+ var __importStar = (this && this.__importStar) || (function () {
32
+ var ownKeys = function(o) {
33
+ ownKeys = Object.getOwnPropertyNames || function (o) {
34
+ var ar = [];
35
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
36
+ return ar;
37
+ };
38
+ return ownKeys(o);
39
+ };
40
+ return function (mod) {
41
+ if (mod && mod.__esModule) return mod;
42
+ var result = {};
43
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
44
+ __setModuleDefault(result, mod);
45
+ return result;
46
+ };
47
+ })();
48
+ Object.defineProperty(exports, "__esModule", { value: true });
49
+ exports.pickByRef = pickByRef;
50
+ exports.attributionLine = attributionLine;
51
+ exports.importPleCommand = importPleCommand;
52
+ const history = __importStar(require("../lib/localHistory"));
53
+ const store = __importStar(require("../lib/localStore"));
54
+ const api_client_1 = require("../lib/api-client");
55
+ const constants_1 = require("../lib/constants");
56
+ const format_1 = require("../lib/format");
57
+ const githubImport_1 = require("../lib/githubImport");
58
+ const importOrigins_1 = require("../lib/importOrigins");
59
+ const importShared_1 = require("../lib/importShared");
60
+ const pleSpec_1 = require("../lib/pleSpec");
61
+ const promptResolver_1 = require("../lib/promptResolver");
62
+ const publicApi_1 = require("../lib/publicApi");
63
+ const scanners_1 = require("../lib/scanners");
64
+ const secretGuard_1 = require("../lib/secretGuard");
65
+ const titleMatch_1 = require("../lib/titleMatch");
66
+ const local_1 = require("./local");
67
+ const LICENSE_NAMES = {
68
+ 'CC-BY-4.0': 'CC BY 4.0',
69
+ 'CC-BY-SA-4.0': 'CC BY-SA 4.0',
70
+ 'CC0-1.0': 'CC0 1.0',
71
+ MIT: 'MIT',
72
+ 'Apache-2.0': 'Apache 2.0',
73
+ };
74
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
75
+ const SHORT_ID_RE = /^[0-9a-f]{8,}$/i;
76
+ /** The prompts a `<prompt>` argument names: an id (full or 8+ hex prefix), else exact title, else part of a title. */
77
+ function pickByRef(cards, ref) {
78
+ const r = ref.trim();
79
+ if (UUID_RE.test(r))
80
+ return cards.filter((k) => k.id.toLowerCase() === r.toLowerCase());
81
+ if (SHORT_ID_RE.test(r)) {
82
+ const byId = cards.filter((k) => k.id.toLowerCase().startsWith(r.toLowerCase()));
83
+ if (byId.length > 0)
84
+ return byId;
85
+ }
86
+ const exact = cards.filter((k) => (0, titleMatch_1.foldedEquals)(k.title, r));
87
+ return exact.length > 0 ? exact : cards.filter((k) => (0, titleMatch_1.foldedIncludes)(k.title, r));
88
+ }
89
+ /** `Source: ple:user/repo/ab12cd34 · v3 · CC BY 4.0 · promptlikeengineer.com/user/repo` */
90
+ function attributionLine(owner, d) {
91
+ const license = d.license ? LICENSE_NAMES[d.license] ?? d.license : 'no license declared';
92
+ const v = d.version ? ` · v${d.version}` : '';
93
+ return `Source: ple:${owner}/${d.repoSlug}/${d.id.slice(0, 8)}${v} · ${license} · promptlikeengineer.com/${owner}/${d.repoSlug}`;
94
+ }
95
+ async function importPleCommand(source, options = {}, deps = {}) {
96
+ const spec = (0, pleSpec_1.parsePleSpec)(source);
97
+ const signedOut = (0, local_1.isSignedOut)();
98
+ if (!signedOut)
99
+ await (0, api_client_1.ensureAuthed)();
100
+ const destination = signedOut ? 'your local store' : 'your account';
101
+ const where = `ple:${spec.owner}/${spec.repo}`;
102
+ const cards = await (0, publicApi_1.listPublicRepoPrompts)(spec.owner, spec.repo);
103
+ if (cards.length === 0) {
104
+ console.log(format_1.c.muted(`No public prompts found in ${where}. The repo and its prompts must both be public.`));
105
+ process.exitCode = 1;
106
+ return;
107
+ }
108
+ let rows = cards;
109
+ if (spec.prompt) {
110
+ rows = pickByRef(cards, spec.prompt);
111
+ if (rows.length === 0) {
112
+ console.error(format_1.c.error(`No prompt matched '${(0, format_1.safeText)(spec.prompt)}' in ${where}.`));
113
+ for (const k of cards.slice(0, 10))
114
+ console.error(format_1.c.muted(` ${k.id.slice(0, 8)} ${(0, format_1.truncate)(k.title, 60)}`));
115
+ process.exitCode = 1;
116
+ return;
117
+ }
118
+ if (rows.length > 1) {
119
+ console.error(format_1.c.error(`'${(0, format_1.safeText)(spec.prompt)}' matched ${rows.length} prompts in ${where}. Use the id:`));
120
+ for (const k of rows)
121
+ console.error(format_1.c.muted(` ${k.id.slice(0, 8)} ${(0, format_1.truncate)(k.title, 60)}`));
122
+ process.exitCode = 1;
123
+ return;
124
+ }
125
+ }
126
+ // What is already there: body hashes, and (signed in) which public prompt came in at which version.
127
+ let hashes = new Set();
128
+ const cameIn = new Map();
129
+ if (signedOut) {
130
+ hashes = new Set(store.list().map((p) => (0, scanners_1.hashBody)(p.body)));
131
+ }
132
+ else {
133
+ try {
134
+ const state = await (0, importOrigins_1.fetchImportOrigins)();
135
+ hashes = state.knownHashes;
136
+ for (const o of state.origins ?? []) {
137
+ if (o.meta?.source === 'ple' && o.meta.prompt_id)
138
+ cameIn.set(o.meta.prompt_id, Number(o.meta.version) || 0);
139
+ }
140
+ }
141
+ catch {
142
+ /* best effort: the server drops a duplicate hash itself */
143
+ }
144
+ }
145
+ const license = rows[0].license;
146
+ console.log(format_1.c.title(`Found ${rows.length} public prompt${rows.length === 1 ? '' : 's'} in ${where}`) +
147
+ format_1.c.muted(` → ${destination}`) +
148
+ format_1.c.muted(` · license: ${license ? LICENSE_NAMES[license] ?? license : 'none declared'}`));
149
+ if (!license) {
150
+ console.log(format_1.c.warn(' ⚠ This repo declares no license: the author has not said how its prompts may be reused. Ask before sharing them further.'));
151
+ }
152
+ rows.forEach((k, i) => console.log(` ${format_1.c.accent(String(i + 1).padStart(3))} ${(0, format_1.truncate)(k.title, 50).padEnd(50)} ${format_1.c.muted(k.id.slice(0, 8))}`));
153
+ if (options.dryRun) {
154
+ console.log(format_1.c.muted(`\nDry run — nothing imported. Run \`ple import ${(0, format_1.safeText)(source)}\` to pick, or add --all.`));
155
+ return;
156
+ }
157
+ // One named prompt is an explicit choice; a whole repo needs --all or a pick.
158
+ const selected = spec.prompt ? rows : await (0, importShared_1.chooseRows)(rows, options.all, deps);
159
+ if (!selected)
160
+ return;
161
+ const details = [];
162
+ let skipped = 0;
163
+ for (const k of selected) {
164
+ const d = await (0, publicApi_1.getPublicPrompt)(spec.owner, k);
165
+ const body = (0, format_1.joinPromptParts)(d);
166
+ if (!body) {
167
+ console.log(format_1.c.warn(` ⚠ ${(0, format_1.truncate)(d.title, 50)}: no text in its current version — skipped`));
168
+ skipped++;
169
+ continue;
170
+ }
171
+ const secret = (0, secretGuard_1.findSecret)(body);
172
+ if (secret) {
173
+ console.log(format_1.c.warn(` ⚠ ${(0, format_1.truncate)(d.title, 50)}: looks like it contains a ${secret} — not imported`));
174
+ skipped++;
175
+ continue;
176
+ }
177
+ const have = cameIn.get(d.id);
178
+ if (have !== undefined && d.version !== null && d.version > have && !hashes.has((0, scanners_1.hashBody)(body))) {
179
+ console.log(format_1.c.muted(` … ${(0, format_1.truncate)(d.title, 50)}: you have v${have}, upstream is v${d.version} — updates are not followed yet; skipped`));
180
+ skipped++;
181
+ continue;
182
+ }
183
+ if (hashes.has((0, scanners_1.hashBody)(body))) {
184
+ console.log(format_1.c.muted(` … ${(0, format_1.truncate)(d.title, 50)}: already in ${destination} — skipped`));
185
+ skipped++;
186
+ continue;
187
+ }
188
+ details.push(d);
189
+ }
190
+ if (details.length === 0) {
191
+ console.log(format_1.c.success(skipped > 0 ? '\nNothing new to import.' : '\nNothing to import.'));
192
+ return;
193
+ }
194
+ if (signedOut) {
195
+ for (const d of details) {
196
+ const body = (0, format_1.joinPromptParts)(d);
197
+ const slug = (0, importShared_1.freeSlug)(d.title);
198
+ const attribution = attributionLine(spec.owner, d);
199
+ const saved = store.save({
200
+ slug,
201
+ title: d.title,
202
+ description: (0, githubImport_1.buildDescription)(d.description ?? '', attribution),
203
+ tags: [],
204
+ body,
205
+ });
206
+ history.recordIfChanged(slug, { title: saved.title, description: saved.description, tags: saved.tags, body: saved.body }, { note: `Imported from ple:${spec.owner}/${d.repoSlug}/${d.id.slice(0, 8)}${d.version ? ` v${d.version}` : ''}` });
207
+ }
208
+ console.log(format_1.c.success(`✓ Imported ${details.length} prompt${details.length === 1 ? '' : 's'} into ${store.promptsDir()}`));
209
+ console.log(format_1.c.muted('Sign in and run `ple sync` to carry them to your account (history, web, agents).'));
210
+ return;
211
+ }
212
+ const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
213
+ const payload = details.map((d) => {
214
+ const body = (0, format_1.joinPromptParts)(d);
215
+ return {
216
+ title: d.title,
217
+ description: (0, githubImport_1.buildDescription)(d.description ?? '', attributionLine(spec.owner, d)),
218
+ content: body,
219
+ origin: {
220
+ tool: 'other',
221
+ kind: 'prompt',
222
+ path: `ple:${spec.owner}/${d.repoSlug}/${d.id}`,
223
+ sha256: (0, scanners_1.hashBody)(body),
224
+ meta: {
225
+ source: 'ple',
226
+ owner: spec.owner,
227
+ repo: d.repoSlug,
228
+ prompt_id: d.id,
229
+ ...(d.version ? { version: String(d.version) } : {}),
230
+ ...(d.license ? { license: d.license } : {}),
231
+ url: `${constants_1.WEB_APP_URL}/${spec.owner}/${d.repoSlug}`,
232
+ },
233
+ },
234
+ };
235
+ });
236
+ await (0, importShared_1.uploadPrompts)(payload, { projectId, retryCommand: `ple import ${(0, format_1.safeText)(source)}` });
237
+ }
@@ -212,11 +212,12 @@ async function copyLocalPrompt(p, values = {}) {
212
212
  process.exitCode = 1;
213
213
  }
214
214
  }
215
+ /** Prints the matches; returns false when there were none (the caller adds the feedback pointer). */
215
216
  function localSearch(keyword) {
216
217
  const rows = store.search(keyword);
217
218
  if (rows.length === 0) {
218
219
  console.log(format_1.c.muted(`No local prompts matched '${keyword}'.`));
219
- return;
220
+ return false;
220
221
  }
221
222
  console.log(format_1.c.label(`${rows.length} result${rows.length === 1 ? '' : 's'}:`));
222
223
  console.log();
@@ -225,4 +226,5 @@ function localSearch(keyword) {
225
226
  if (p.description)
226
227
  console.log(format_1.c.muted(` ${(0, format_1.truncate)(p.description, 80)}`));
227
228
  }
229
+ return true;
228
230
  }
@@ -54,7 +54,7 @@ function versionNotFound(ref, versions) {
54
54
  function noteUnrecorded(p, latest) {
55
55
  if (latest && latest.body.trim() !== p.body.trim()) {
56
56
  console.error(format_1.c.muted(`(The file on disk differs from v${latest.version} — it was edited outside ple. ` +
57
- `Run \`ple save "${p.slug}" --force\` or a rollback to record it.)`));
57
+ `\`ple rollback "${p.slug}" v${latest.version}\` saves the edit as its own version first, then restores v${latest.version}.)`));
58
58
  }
59
59
  }
60
60
  function localLog(name, options) {