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,159 @@
1
+ "use strict";
2
+ /**
3
+ * `ple save <title> --project <repo>` — save one prompt INTO THE ACCOUNT, and be safe to run again.
4
+ *
5
+ * `ple sync` uploads whatever text the local files hold, so running it after an edit created a second
6
+ * prompt with the same title. This does the opposite: the title inside the repo is the identity.
7
+ *
8
+ * no prompt with that title in the repo → create it (v1)
9
+ * one, and the text is different → add a NEW version (nothing is overwritten, labels stay put)
10
+ * one, and the text is the same → "unchanged": nothing is sent
11
+ * several, none with this text → stop and list them (never guess which one to change)
12
+ *
13
+ * Only the fields the caller gave are touched. A description that differs is patched on the prompt (no
14
+ * version — the description is not part of a version); tags are only ever ADDED. Titles are compared
15
+ * with {@link normalizeTitle} (case, spacing and Unicode-compatibility insensitive), the same rule the
16
+ * rest of the CLI uses to tell "is this the same prompt".
17
+ *
18
+ * Callers run `ensureAuthed()` first. Server calls: `GET /api/prompts?search=&projectId=`,
19
+ * `POST /api/prompts` (create / new version), `PATCH /api/prompts/{id}`, `POST /api/prompts/{id}/tags`.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.MAX_TAG_LENGTH = void 0;
23
+ exports.cleanTags = cleanTags;
24
+ exports.assertTagLengths = assertTagLengths;
25
+ exports.saveToAccount = saveToAccount;
26
+ exports.candidateLine = candidateLine;
27
+ const api_client_1 = require("./api-client");
28
+ const format_1 = require("./format");
29
+ const loopApi_1 = require("./loopApi");
30
+ const promptSource_1 = require("./promptSource");
31
+ /** Same cap the web API enforces on a tag name. */
32
+ exports.MAX_TAG_LENGTH = 50;
33
+ /** Tag names as typed: comma-separated allowed (like the local store), trimmed, de-duplicated ignoring case. */
34
+ function cleanTags(raw) {
35
+ const out = [];
36
+ for (const t of raw.flatMap((r) => r.split(','))) {
37
+ const tag = t.trim();
38
+ if (tag && !out.some((o) => o.toLowerCase() === tag.toLowerCase()))
39
+ out.push(tag);
40
+ }
41
+ return out;
42
+ }
43
+ /** Throws the message to show when a tag cannot be sent (the server would reject it anyway). */
44
+ function assertTagLengths(tags) {
45
+ const long = tags.find((t) => t.length > exports.MAX_TAG_LENGTH);
46
+ if (long)
47
+ throw new Error(`Tag '${(0, format_1.safeText)(long).slice(0, 20)}…' is too long (max ${exports.MAX_TAG_LENGTH} characters).`);
48
+ }
49
+ /** Text as compared for "did it change": line endings and the ends trimmed, nothing else. */
50
+ function sameText(a, b) {
51
+ const norm = (s) => s.replace(/\r\n?/g, '\n').trim();
52
+ return norm(a) === norm(b);
53
+ }
54
+ function versionOf(p) {
55
+ const n = p.current_version?.version_number;
56
+ return typeof n === 'number' ? n : null;
57
+ }
58
+ /** Tags the prompt does not have yet (names compared ignoring case). */
59
+ function missingTags(wanted, have) {
60
+ const present = new Set((have.tags ?? []).map((t) => t.name.toLowerCase()));
61
+ return wanted.filter((t) => !present.has(t.toLowerCase()));
62
+ }
63
+ async function addTags(promptId, tags) {
64
+ const added = [];
65
+ const failed = [];
66
+ for (const tag of tags) {
67
+ try {
68
+ await (0, loopApi_1.addTagByName)(promptId, tag);
69
+ added.push(tag);
70
+ }
71
+ catch (err) {
72
+ failed.push({ tag, message: err instanceof Error ? err.message : String(err) });
73
+ }
74
+ }
75
+ return { added, failed };
76
+ }
77
+ /** Server cap per page (GET /api/prompts maxLimit) and the walk's upper bound: 20 pages = 2000 prompts of one repo. */
78
+ const PAGE_LIMIT = 100;
79
+ const MAX_PAGES = 20;
80
+ /**
81
+ * Prompts of the repo whose title is this one. The server's search is the cheap first try (same as the
82
+ * MCP `save_prompt`), but it is an ILIKE: it cannot tell "BAŞLANGICI" from "başlangıcı" (dotless ı) or
83
+ * see through a different spacing. Creating is the one step that cannot be undone, so when the search
84
+ * finds nothing the repo is walked page by page and compared with {@link normalizeTitle} before a
85
+ * second prompt is made.
86
+ */
87
+ async function findSameTitle(title, projectId) {
88
+ const key = (0, promptSource_1.normalizeTitle)(title);
89
+ const byTitle = (rows) => rows.filter((p) => (0, promptSource_1.normalizeTitle)(p.title) === key);
90
+ const searched = byTitle(await (0, api_client_1.listPrompts)({ search: title.trim().replace(/\s+/g, ' '), projectId, limit: PAGE_LIMIT }));
91
+ if (searched.length > 0)
92
+ return searched;
93
+ const found = [];
94
+ const seen = new Set();
95
+ for (let page = 1; page <= MAX_PAGES; page++) {
96
+ const rows = await (0, api_client_1.listPrompts)({ projectId, limit: PAGE_LIMIT, page });
97
+ const fresh = rows.filter((p) => !seen.has(p.id));
98
+ if (fresh.length === 0)
99
+ break; // server ignored `page` and sent the same rows again
100
+ for (const p of fresh)
101
+ seen.add(p.id);
102
+ found.push(...byTitle(fresh));
103
+ if (rows.length < PAGE_LIMIT)
104
+ break; // last page
105
+ }
106
+ return found;
107
+ }
108
+ async function saveToAccount(input) {
109
+ const sameTitle = await findSameTitle(input.title, input.projectId);
110
+ if (sameTitle.length === 0) {
111
+ const saved = await (0, loopApi_1.createPrompt)({
112
+ projectId: input.projectId,
113
+ title: input.title,
114
+ description: input.description,
115
+ body: input.body,
116
+ changelog: 'Saved with ple save',
117
+ });
118
+ if (!saved.promptId)
119
+ throw new Error('The server saved the prompt but sent an unexpected response. Run `ple list --project` to check.');
120
+ const tags = await addTags(saved.promptId, input.tags);
121
+ return { status: 'created', id: saved.promptId, version: saved.versionNumber ?? 1, tagsAdded: tags.added, tagsFailed: tags.failed };
122
+ }
123
+ // The one that already holds this text wins; otherwise a single match is the one to version.
124
+ const identical = sameTitle.find((p) => sameText((0, format_1.joinPromptParts)(p.current_version ?? {}), input.body));
125
+ const target = identical ?? (sameTitle.length === 1 ? sameTitle[0] : undefined);
126
+ if (!target)
127
+ return { status: 'ambiguous', candidates: sameTitle };
128
+ // Description: only when given and different. No version — PATCH changes the prompt, not a version.
129
+ let descriptionUpdated = false;
130
+ if (input.description !== undefined && input.description !== (target.description ?? '')) {
131
+ await (0, loopApi_1.patchDescription)(target.id, input.description);
132
+ descriptionUpdated = true;
133
+ }
134
+ const tags = await addTags(target.id, missingTags(input.tags, target));
135
+ if (identical) {
136
+ return {
137
+ status: 'unchanged',
138
+ id: target.id,
139
+ version: versionOf(target),
140
+ descriptionUpdated,
141
+ tagsAdded: tags.added,
142
+ tagsFailed: tags.failed,
143
+ };
144
+ }
145
+ const saved = await (0, loopApi_1.saveVersion)(target.id, { roleText: '', descriptionText: '', contextText: input.body }, 'Updated with ple save', 'cli');
146
+ return {
147
+ status: 'updated',
148
+ id: target.id,
149
+ version: saved.versionNumber ?? null,
150
+ previousVersion: versionOf(target),
151
+ descriptionUpdated,
152
+ tagsAdded: tags.added,
153
+ tagsFailed: tags.failed,
154
+ };
155
+ }
156
+ /** One candidate line for the "several prompts share this title" stop. */
157
+ function candidateLine(p) {
158
+ return `${(0, format_1.shortId)(p.id)} ${(0, format_1.safeText)(p.title)}`;
159
+ }
@@ -26,11 +26,14 @@ exports.listPrompts = listPrompts;
26
26
  exports.importPrompts = importPrompts;
27
27
  exports.getImportedHashes = getImportedHashes;
28
28
  exports.getAccountHeadroom = getAccountHeadroom;
29
+ exports.getAccountLimits = getAccountLimits;
29
30
  exports.listProjects = listProjects;
30
31
  exports.toRepoDetail = toRepoDetail;
31
32
  exports.listProjectsDetailed = listProjectsDetailed;
32
33
  exports.createProject = createProject;
33
34
  exports.setProjectVisibility = setProjectVisibility;
35
+ exports.setProjectLicense = setProjectLicense;
36
+ exports.setPromptVisibility = setPromptVisibility;
34
37
  exports.getPromptById = getPromptById;
35
38
  exports.getPromptHistory = getPromptHistory;
36
39
  exports.rollbackPrompt = rollbackPrompt;
@@ -442,6 +445,33 @@ async function getAccountHeadroom() {
442
445
  return { promptsRemaining: null, isPro: false };
443
446
  }
444
447
  }
448
+ /** A count or a limit: a finite number ≥ 0, anything else (missing, null, text) is "not reported". */
449
+ function countOrNull(v) {
450
+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null;
451
+ }
452
+ /**
453
+ * GET /api/account/limits for `ple whoami`. Unlike {@link getAccountHeadroom} this does NOT swallow errors
454
+ * (the caller must tell "signed out / offline" from "free plan"), and it checks the shape: the plan name is
455
+ * server text and goes through {@link safeText}.
456
+ */
457
+ async function getAccountLimits() {
458
+ const res = await apiFetch('/api/account/limits');
459
+ const plan = res.plan ?? {};
460
+ const usage = res.usage ?? {};
461
+ const trial = typeof plan.trialEndsAt === 'string' && !Number.isNaN(Date.parse(plan.trialEndsAt)) ? plan.trialEndsAt : null;
462
+ return {
463
+ plan: {
464
+ id: typeof plan.id === 'string' ? plan.id : null,
465
+ name: typeof plan.name === 'string' && plan.name.trim() ? (0, format_1.safeText)(plan.name) : plan.isPro === true ? 'Pro' : 'Free',
466
+ isPro: plan.isPro === true,
467
+ promptLimit: countOrNull(plan.promptLimit),
468
+ versionLimitPerPrompt: countOrNull(plan.versionLimitPerPrompt),
469
+ projectLimit: countOrNull(plan.projectLimit),
470
+ trialEndsAt: trial,
471
+ },
472
+ usage: { promptCount: countOrNull(usage.promptCount), projectCount: countOrNull(usage.projectCount) },
473
+ };
474
+ }
445
475
  /** GET /api/projects — list the user's accessible repos (for --project resolution). */
446
476
  async function listProjects() {
447
477
  const res = await apiFetch('/api/projects', {
@@ -468,6 +498,7 @@ function toRepoDetail(raw) {
468
498
  slug: typeof r.slug === 'string' ? (0, format_1.safeText)(r.slug) : null,
469
499
  description: typeof r.description === 'string' ? (0, format_1.safeText)(r.description) : null,
470
500
  visibility: r.visibility === 'public' ? 'public' : 'private',
501
+ license: typeof r.license === 'string' ? (0, format_1.safeText)(r.license) : null,
471
502
  role,
472
503
  prompt_count: typeof r.prompt_count === 'number' ? r.prompt_count : 0,
473
504
  member_count: typeof r.member_count === 'number' ? r.member_count : 0,
@@ -504,6 +535,20 @@ async function setProjectVisibility(id, visibility) {
504
535
  body: { visibility },
505
536
  });
506
537
  }
538
+ /** PATCH /api/projects/{id} — declare (or clear, with null) the repo's license; the server allows the owner only. */
539
+ async function setProjectLicense(id, license) {
540
+ await apiFetch(`/api/projects/${encodeURIComponent(id)}`, {
541
+ method: 'PATCH',
542
+ body: { license },
543
+ });
544
+ }
545
+ /** PATCH /api/prompts/{id} — change one prompt's visibility (the server allows the owner only). */
546
+ async function setPromptVisibility(id, visibility) {
547
+ await apiFetch(`/api/prompts/${encodeURIComponent(id)}`, {
548
+ method: 'PATCH',
549
+ body: { visibility },
550
+ });
551
+ }
507
552
  /** GET /api/prompts/{id} — full detail; returns null when not found (404). */
508
553
  async function getPromptById(id) {
509
554
  try {
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ /**
3
+ * HTTP for `ple feedback`: POST /api/feedback (the session is optional) and the owner's
4
+ * GET /api/feedback · PATCH /api/feedback/{id}.
5
+ *
6
+ * Kept out of `api-client.ts` on purpose: a report must go out WITHOUT a session, a failed send is
7
+ * queued instead of thrown, and the status codes map to the feedback exit codes rather than to the
8
+ * generic 1/2. It reuses the same rules as the rest of the CLI: the base URL is validated before any
9
+ * request is built, every request has a timeout, redirects are never followed (a 3xx would replay the
10
+ * body, and the bearer token, at an address the server picked), and a token is only ever sent to the
11
+ * configured API origin. Nothing here throws; every outcome is a value.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.FEEDBACK_STATUSES = exports.OWNER_TIMEOUT_MS = exports.SUBMIT_TIMEOUT_MS = void 0;
15
+ exports.request = request;
16
+ exports.serverMessage = serverMessage;
17
+ exports.serverDetails = serverDetails;
18
+ exports.toSendResult = toSendResult;
19
+ exports.sendFeedback = sendFeedback;
20
+ const constants_1 = require("./constants");
21
+ const format_1 = require("./format");
22
+ exports.SUBMIT_TIMEOUT_MS = 15000;
23
+ exports.OWNER_TIMEOUT_MS = 15000;
24
+ exports.FEEDBACK_STATUSES = ['new', 'triaged', 'done', 'wontfix'];
25
+ const MAX_RETRY_AFTER_S = 86400;
26
+ function clampRetryAfter(value) {
27
+ const n = typeof value === 'number' ? value : typeof value === 'string' && /^\d{1,6}$/.test(value.trim()) ? Number(value) : NaN;
28
+ return Number.isFinite(n) && n >= 0 ? Math.min(Math.floor(n), MAX_RETRY_AFTER_S) : undefined;
29
+ }
30
+ function isTimeout(err, signal) {
31
+ if (signal.aborted)
32
+ return true;
33
+ const name = err?.name;
34
+ return name === 'TimeoutError' || name === 'AbortError';
35
+ }
36
+ async function request(input) {
37
+ if (constants_1.API_BASE_URL_ERROR)
38
+ return { kind: 'config', message: (0, format_1.safeText)(constants_1.API_BASE_URL_ERROR) };
39
+ const url = new URL(constants_1.API_BASE_URL + input.path);
40
+ for (const [k, v] of Object.entries(input.query ?? {})) {
41
+ if (v !== undefined && v !== '')
42
+ url.searchParams.set(k, String(v));
43
+ }
44
+ const headers = { Accept: 'application/json', 'X-CLI-Version': constants_1.CLI_VERSION };
45
+ if (input.body !== undefined)
46
+ headers['Content-Type'] = 'application/json';
47
+ if (input.token)
48
+ headers.Authorization = `Bearer ${input.token}`;
49
+ const signal = AbortSignal.timeout(Math.max(1, Math.floor(input.timeoutMs)));
50
+ let res;
51
+ try {
52
+ res = await (input.fetchImpl ?? fetch)(url.toString(), {
53
+ method: input.method,
54
+ headers,
55
+ body: input.body === undefined ? undefined : JSON.stringify(input.body),
56
+ signal,
57
+ redirect: 'manual',
58
+ });
59
+ }
60
+ catch (err) {
61
+ if (isTimeout(err, signal)) {
62
+ return { kind: 'unreachable', message: `No response from ${constants_1.API_BASE_URL} within ${Math.round(input.timeoutMs / 1000)}s.` };
63
+ }
64
+ return { kind: 'unreachable', message: (0, format_1.safeText)(`Cannot reach ${constants_1.API_BASE_URL}. ${err instanceof Error ? err.message : String(err)}`).slice(0, 300) };
65
+ }
66
+ if (res.status >= 300 && res.status < 400) {
67
+ return { kind: 'unreachable', message: `The server answered with a redirect (HTTP ${res.status}); the CLI does not follow redirects. Check PROMPTLIKE_API_URL (currently ${constants_1.API_BASE_URL}).` };
68
+ }
69
+ let body = {};
70
+ try {
71
+ const parsed = await res.json();
72
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed))
73
+ body = parsed;
74
+ }
75
+ catch {
76
+ // Not JSON, or cut off mid-body: the status alone decides.
77
+ }
78
+ const retryAfter = clampRetryAfter(body.retry_after) ?? clampRetryAfter(res.headers.get('retry-after') ?? undefined);
79
+ return { kind: 'response', status: res.status, body, retryAfter };
80
+ }
81
+ /** The server's `error` text, made terminal-safe and short; `fallback` when there is none. */
82
+ function serverMessage(body, fallback) {
83
+ const e = body.error;
84
+ return typeof e === 'string' && e.trim() ? (0, format_1.safeText)(e).trim().slice(0, 300) : fallback;
85
+ }
86
+ /** `details` of a 400, flattened to one safe line (it may be an array, an object or a string). */
87
+ function serverDetails(body) {
88
+ const d = body.details;
89
+ if (d === undefined || d === null)
90
+ return '';
91
+ let text;
92
+ try {
93
+ text = typeof d === 'string' ? d : JSON.stringify(d);
94
+ }
95
+ catch {
96
+ return '';
97
+ }
98
+ return (0, format_1.safeText)(text).slice(0, 300);
99
+ }
100
+ function toSendResult(out) {
101
+ if (out.kind === 'config')
102
+ return { kind: 'config', message: out.message };
103
+ if (out.kind === 'unreachable')
104
+ return { kind: 'unavailable', message: out.message };
105
+ const { status, body } = out;
106
+ if (status === 201 || status === 200) {
107
+ const id = typeof body.id === 'string' || typeof body.id === 'number' ? (0, format_1.safeText)(String(body.id)).slice(0, 64) : undefined;
108
+ return { kind: 'sent', id: id || undefined };
109
+ }
110
+ if (status === 400 || status === 413 || status === 422) {
111
+ const fallback = status === 413 ? 'The report is too large.' : 'The server rejected the report.';
112
+ const details = serverDetails(body);
113
+ return { kind: 'invalid', status, message: serverMessage(body, fallback) + (details ? ` (${details})` : '') };
114
+ }
115
+ if (status === 429)
116
+ return { kind: 'rate_limited', retryAfter: out.retryAfter };
117
+ if (status === 401 || status === 403)
118
+ return { kind: 'auth', status };
119
+ if (status >= 500 || status === 404 || status === 408) {
120
+ return { kind: 'unavailable', message: `The server answered HTTP ${status}.` };
121
+ }
122
+ return { kind: 'unexpected', status, message: serverMessage(body, `The server answered HTTP ${status}.`) };
123
+ }
124
+ /** POST one report. With a `token` the report is tied to the account; a 401/403 is returned for the caller to retry anonymously. */
125
+ async function sendFeedback(payload, opts = {}) {
126
+ return toSendResult(await request({
127
+ method: 'POST',
128
+ path: '/api/feedback',
129
+ body: payload,
130
+ token: opts.token,
131
+ timeoutMs: opts.timeoutMs ?? exports.SUBMIT_TIMEOUT_MS,
132
+ fetchImpl: opts.fetchImpl,
133
+ }));
134
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ /**
3
+ * The one-line pointer to `ple feedback`, shown when `ple search` or `ple get` comes up empty or fails.
4
+ *
5
+ * Always stderr (stdout stays the prompt text / the result list for pipes and agents), never part of a
6
+ * `--json` answer, and never repeated: one line per command run.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.FEEDBACK_HINT = void 0;
10
+ exports.printFeedbackHint = printFeedbackHint;
11
+ const format_1 = require("./format");
12
+ exports.FEEDBACK_HINT = 'Missing something? ple feedback --type missing "..."';
13
+ function printFeedbackHint() {
14
+ console.error(format_1.c.muted(exports.FEEDBACK_HINT));
15
+ }
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ /**
3
+ * Input rules for `ple feedback` — pure, no network, no disk.
4
+ *
5
+ * A report is a short note about the tool, never a vehicle for data. What is checked here:
6
+ * - sizes (they mirror the server: message 1..2000, prompt reference ≤200, agent name ≤64);
7
+ * - the message is one piece of plain text: terminal escapes and control characters are removed;
8
+ * - `--prompt` is a TITLE or an id. Anything that looks like prompt text (a line break, more than
9
+ * 200 characters) is refused, so a prompt body cannot ride along by accident;
10
+ * - the same secret patterns `ple import --scan` uses (see secretGuard.ts) REFUSE the report and
11
+ * name the kind, never the value. Refusing beats masking: a half-hidden key is still a leaked key.
12
+ *
13
+ * The context block is built from constants (version, platform, Node version, the command's NAME and
14
+ * the NAMES of the flags that were used). No argument value, no message, no path ever goes into it.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.MAX_CONTEXT_VALUE = exports.MAX_EMAIL = exports.MAX_AGENT_NAME = exports.MAX_PROMPT_REF = exports.MAX_MESSAGE = exports.DEFAULT_FEEDBACK_TYPE = exports.FEEDBACK_TYPES = void 0;
18
+ exports.scanForSecret = scanForSecret;
19
+ exports.cleanMessage = cleanMessage;
20
+ exports.cleanLine = cleanLine;
21
+ exports.isFeedbackType = isFeedbackType;
22
+ exports.sanitizeAgentName = sanitizeAgentName;
23
+ exports.isPlausibleEmail = isPlausibleEmail;
24
+ exports.osLabel = osLabel;
25
+ exports.buildContext = buildContext;
26
+ exports.checkFeedbackFields = checkFeedbackFields;
27
+ exports.parseStoredPayload = parseStoredPayload;
28
+ const format_1 = require("./format");
29
+ const secretGuard_1 = require("./secretGuard");
30
+ exports.FEEDBACK_TYPES = ['bug', 'missing', 'idea', 'prompt'];
31
+ exports.DEFAULT_FEEDBACK_TYPE = 'idea';
32
+ exports.MAX_MESSAGE = 2000;
33
+ exports.MAX_PROMPT_REF = 200;
34
+ exports.MAX_AGENT_NAME = 64;
35
+ exports.MAX_EMAIL = 254;
36
+ /** Every context value is a short string. */
37
+ exports.MAX_CONTEXT_VALUE = 64;
38
+ // Zero-width / formatting characters never change what a key looks like to a reader, but one in the middle
39
+ // of a token defeats a regex. Removed for MATCHING only (the text that is sent is not touched by this).
40
+ const INVISIBLE = /[\p{Cf}\u2028\u2029\u034F\u115F\u1160\u17B4\u17B5\u180B-\u180F\u3164\uFE00-\uFE0F\uFFA0]/gu;
41
+ /** Kind of secret found in `text` (never the value), or null. NFKC + invisible characters removed first. */
42
+ function scanForSecret(text) {
43
+ const scanned = text.normalize('NFKC').replace(INVISIBLE, '');
44
+ return (0, secretGuard_1.findSecret)(scanned) ?? (0, secretGuard_1.findSecret)(text);
45
+ }
46
+ /** Plain multi-line text: escapes and control characters out, line endings unified, ends trimmed. */
47
+ function cleanMessage(raw) {
48
+ return (0, format_1.safeText)(raw.replace(/\r\n?/g, '\n').replace(/[\u2028\u2029]/g, '\n'), true).trim();
49
+ }
50
+ /** One line: every run of whitespace/control characters becomes a single space. */
51
+ function cleanLine(raw) {
52
+ return (0, format_1.safeText)(raw.replace(/[\r\n\t\u2028\u2029]+/g, ' ')).replace(/\s{2,}/g, ' ').trim();
53
+ }
54
+ function isFeedbackType(value) {
55
+ return exports.FEEDBACK_TYPES.includes(value);
56
+ }
57
+ /**
58
+ * Agent names are labels: lowercase `a-z 0-9 . _ -`, at most 64. Returns '' when nothing is left, so the caller
59
+ * can tell "no name" from a name.
60
+ */
61
+ function sanitizeAgentName(raw) {
62
+ return raw
63
+ .normalize('NFKC')
64
+ .toLowerCase()
65
+ .replace(INVISIBLE, '')
66
+ .replace(/[^a-z0-9._-]+/g, '-')
67
+ .replace(/-{2,}/g, '-')
68
+ .replace(/^[-._]+|[-._]+$/g, '')
69
+ .slice(0, exports.MAX_AGENT_NAME);
70
+ }
71
+ const EMAIL_RE = /^[^\s@<>()[\],;:"\\]{1,64}@[^\s@<>()[\],;:"\\]+\.[^\s@<>()[\],;:"\\]{2,}$/;
72
+ function isPlausibleEmail(value) {
73
+ return value.length <= exports.MAX_EMAIL && EMAIL_RE.test(value);
74
+ }
75
+ /** `os` for the context: platform and CPU architecture only (`darwin-arm64`). */
76
+ function osLabel(platform = process.platform, arch = process.arch) {
77
+ return `${platform}-${arch}`.slice(0, exports.MAX_CONTEXT_VALUE);
78
+ }
79
+ /**
80
+ * The context block. `flagNames` are long option names that were passed (`--type`, `--prompt`); values and the
81
+ * message are never part of it. Names outside `--[a-z-]` are dropped, so nothing else can slip in through here.
82
+ */
83
+ function buildContext(opts) {
84
+ const flags = (opts.flagNames ?? []).filter((f) => /^--[a-z][a-z-]{0,30}$/.test(f));
85
+ const command = [opts.commandName, ...flags].join(' ').slice(0, exports.MAX_CONTEXT_VALUE);
86
+ return {
87
+ cli_version: opts.cliVersion.slice(0, exports.MAX_CONTEXT_VALUE),
88
+ os: osLabel(opts.platform, opts.arch),
89
+ node: (opts.nodeVersion ?? process.versions.node).slice(0, exports.MAX_CONTEXT_VALUE),
90
+ command,
91
+ };
92
+ }
93
+ /** Validate and normalise what the user typed. The error text says what to change and never echoes a secret. */
94
+ function checkFeedbackFields(input) {
95
+ const typeRaw = input.type === undefined ? exports.DEFAULT_FEEDBACK_TYPE : input.type.trim().toLowerCase();
96
+ if (!isFeedbackType(typeRaw)) {
97
+ return { ok: false, error: `--type must be one of: ${exports.FEEDBACK_TYPES.join(', ')} (got '${cleanLine(input.type ?? '').slice(0, 20)}').` };
98
+ }
99
+ const message = cleanMessage(input.message);
100
+ if (!message)
101
+ return { ok: false, error: 'The message is empty. Usage: ple feedback [--type bug|missing|idea|prompt] "<message>"' };
102
+ if (message.length > exports.MAX_MESSAGE) {
103
+ return { ok: false, error: `The message is too long (${message.length} characters, max ${exports.MAX_MESSAGE}). One short, factual sentence is enough.` };
104
+ }
105
+ const messageSecret = scanForSecret(input.message);
106
+ if (messageSecret) {
107
+ return {
108
+ ok: false,
109
+ error: `The message contains something that looks like a secret (${messageSecret}). Nothing was sent. Remove it and try again — feedback never needs secrets.`,
110
+ };
111
+ }
112
+ const value = { type: typeRaw, message };
113
+ if (input.prompt !== undefined) {
114
+ if (/[\r\n\u2028\u2029]/.test(input.prompt)) {
115
+ return { ok: false, error: '--prompt takes a prompt title or id on one line, not prompt text. The body of a prompt is never sent.' };
116
+ }
117
+ const ref = cleanLine(input.prompt);
118
+ if (ref.length > exports.MAX_PROMPT_REF) {
119
+ return { ok: false, error: `--prompt is too long (max ${exports.MAX_PROMPT_REF} characters). Give the prompt's title or id, never its text.` };
120
+ }
121
+ const refSecret = scanForSecret(input.prompt);
122
+ if (refSecret)
123
+ return { ok: false, error: `--prompt contains something that looks like a secret (${refSecret}). Nothing was sent.` };
124
+ if (ref)
125
+ value.prompt_ref = ref;
126
+ }
127
+ if (input.email !== undefined) {
128
+ const email = input.email.trim();
129
+ if (!isPlausibleEmail(email))
130
+ return { ok: false, error: '--email is not a valid email address.' };
131
+ value.email = email;
132
+ }
133
+ return { ok: true, value };
134
+ }
135
+ /**
136
+ * Re-validate a payload read back from disk (the queue file). Anything off — wrong shape, over a limit,
137
+ * a secret that was added by hand — returns null and the entry is dropped.
138
+ */
139
+ function parseStoredPayload(raw) {
140
+ if (typeof raw !== 'object' || raw === null)
141
+ return null;
142
+ const o = raw;
143
+ if (typeof o.type !== 'string' || !isFeedbackType(o.type))
144
+ return null;
145
+ if (typeof o.message !== 'string' || o.message.length < 1 || o.message.length > exports.MAX_MESSAGE)
146
+ return null;
147
+ if (scanForSecret(o.message))
148
+ return null;
149
+ if (o.source !== 'human' && o.source !== 'agent')
150
+ return null;
151
+ if (o.client !== 'cli')
152
+ return null;
153
+ const ctx = o.context;
154
+ if (typeof ctx !== 'object' || ctx === null)
155
+ return null;
156
+ const short = (v) => typeof v === 'string' && v.length <= exports.MAX_CONTEXT_VALUE;
157
+ if (!short(ctx.cli_version) || !short(ctx.os) || !short(ctx.node) || !short(ctx.command))
158
+ return null;
159
+ const out = {
160
+ type: o.type,
161
+ message: o.message,
162
+ source: o.source,
163
+ client: 'cli',
164
+ context: { cli_version: ctx.cli_version, os: ctx.os, node: ctx.node, command: ctx.command },
165
+ };
166
+ if (o.prompt_ref !== undefined) {
167
+ if (typeof o.prompt_ref !== 'string' || o.prompt_ref.length > exports.MAX_PROMPT_REF || /[\r\n]/.test(o.prompt_ref))
168
+ return null;
169
+ out.prompt_ref = o.prompt_ref;
170
+ }
171
+ if (o.email !== undefined) {
172
+ if (typeof o.email !== 'string' || !isPlausibleEmail(o.email))
173
+ return null;
174
+ out.email = o.email;
175
+ }
176
+ if (o.agent_name !== undefined) {
177
+ if (typeof o.agent_name !== 'string' || o.agent_name.length > exports.MAX_AGENT_NAME)
178
+ return null;
179
+ out.agent_name = o.agent_name;
180
+ }
181
+ return out;
182
+ }