promptlike 0.4.0 → 0.5.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 CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0 — 2026-09-27
4
+
5
+ - **New: `ple export`.** Turn a prompt, or a whole repo with `--project`, into
6
+ an AGENTS.md section or an Agent Skill (`SKILL.md`, the format Claude Code,
7
+ Claude and other skill-aware agents load). `--zip` writes the archive that
8
+ Claude's skill upload expects. Works signed out, from your local prompts.
9
+ Skill names and descriptions pass Anthropic's skill validator: kebab-case,
10
+ at most 64 characters, no reserved words, no angle brackets.
11
+
12
+ ## 0.4.1 — 2026-08-15
13
+
14
+ Data-integrity fix — **update recommended for every 0.4.0 install.**
15
+
16
+ - **Fixed: empty frontmatter fields swallowed the next line on read.** A prompt
17
+ saved without `-d`/`-t` (the most common form) read back with
18
+ `description: "tags:"` and a phantom tag like `created: <timestamp>`;
19
+ `--force` re-saves made the corruption permanent and `ple sync` could upload
20
+ the phantom tag to your account. Root cause: a `\s*` in the parser crossed
21
+ line endings. Files written by 0.4.0 are re-read correctly after this fix
22
+ unless they were re-saved with `--force` (open the file and delete the stray
23
+ text from `description:`/`tags:` lines if so).
24
+ - `ple sync` now reports partial success when a later batch hits the plan
25
+ limit, instead of dying with a bare error after silently uploading a batch.
26
+ The server also accounts for records dropped mid-loop by the limit trigger,
27
+ so uploaded + failed + skipped + truncated always adds up.
28
+ - Out-of-tokens (402) now says what it means: top up with a $3 MicroBoost or
29
+ wait for the monthly reset — instead of a generic "temporarily unavailable".
30
+ - Duplicate-slug error now shows the existing prompt's actual title (two
31
+ different titles can slugify to the same name).
32
+ - A single `--tag "a,b"` is stored as two tags instead of silently splitting
33
+ on the next read.
34
+ - `ple search --help` now says local mode also searches bodies and tags.
35
+
3
36
  ## 0.4.0 — 2026-08-10
4
37
 
5
38
  The install is no longer a dead end.
package/README.md CHANGED
@@ -247,6 +247,29 @@ Debug Helper · 33cc44dd · 2w ago
247
247
  Walk through systematic debugging steps for runtime errors.
248
248
  ```
249
249
 
250
+ ### `ple export [name] --format agents-md|skill`
251
+
252
+ Export a prompt for coding agents — or a whole repo with `--project <repo>`
253
+ and no name. Signed out, it exports from the local store.
254
+
255
+ | Format | One prompt | Whole repo |
256
+ |---|---|---|
257
+ | `agents-md` | a `## Title` section on stdout (append it to your AGENTS.md) | a full AGENTS.md, one section per prompt |
258
+ | `skill` | `<name>/SKILL.md` ([Agent Skills](https://agentskills.io/specification) format) | one skill: `SKILL.md` index + `references/<prompt>.md` |
259
+
260
+ ```bash
261
+ ple export "code review" --format agents-md >> AGENTS.md
262
+ ple export "code review" --format skill --out ~/.claude/skills # Claude Code picks it up
263
+ ple export --project backend --format skill --zip # upload the zip in Claude
264
+ ple export --project backend --format agents-md --out AGENTS.md
265
+ ```
266
+
267
+ Skill names follow the spec: lowercase, digits and single hyphens, at most 64
268
+ characters. The words "claude" and "anthropic" are removed because Anthropic
269
+ rejects them in skill names. `{{variables}}` are listed under an **Inputs**
270
+ heading so the agent knows what to ask for. Existing files are never
271
+ overwritten without `--force`.
272
+
250
273
  ### `ple --help` / `ple <cmd> --help`
251
274
 
252
275
  Standard `commander` help output for either the root command or any
@@ -359,7 +382,13 @@ cli/
359
382
  │ │ ├── list.ts # list with --tag / --limit
360
383
  │ │ ├── copy.ts # resolve + fetch + clipboard
361
384
  │ │ ├── show.ts # resolve + 3-part colored render
362
- │ │ └── search.ts # title + description search
385
+ │ │ ├── search.ts # title + description search
386
+ │ │ ├── save.ts # write to local store, no account needed
387
+ │ │ ├── get.ts # resolve + fill {{vars}} + print/copy
388
+ │ │ ├── sync.ts # one-way upload: local store → account
389
+ │ │ ├── improve.ts # one-shot variants, pick a winner
390
+ │ │ ├── loop.ts # multi-round improve judged by --exec
391
+ │ │ └── local.ts # logged-out routing + local-store implementations
363
392
  │ └── lib/
364
393
  │ ├── constants.ts # API_BASE_URL + WEB_APP_URL
365
394
  │ ├── config.ts # read/write ~/.config/promptlike/config.json
@@ -367,7 +396,9 @@ cli/
367
396
  │ ├── clipboard.ts # spawn(pbcopy/xclip/clip) + Wayland fallback
368
397
  │ ├── format.ts # chalk palette, timeAgo, truncate, joinPromptParts
369
398
  │ ├── promptResolver.ts # name → prompt (id prefix or title search)
370
- │ └── promptVariables.ts # {{variable}} extract + fill
399
+ │ ├── promptVariables.ts # {{variable}} extract + fill
400
+ │ ├── localStore.ts # ~/.promptlike/prompts/ Markdown read/write
401
+ │ └── loopApi.ts / loopUx.ts # loop + improve variant generation & prompts
371
402
  └── dist/ # tsc output, what gets published
372
403
  ```
373
404
 
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.exportCommand = exportCommand;
37
+ const fs = __importStar(require("fs"));
38
+ const path = __importStar(require("path"));
39
+ const api_client_1 = require("../lib/api-client");
40
+ const local_1 = require("./local");
41
+ const store = __importStar(require("../lib/localStore"));
42
+ const promptResolver_1 = require("../lib/promptResolver");
43
+ const format_1 = require("../lib/format");
44
+ const agentExport_1 = require("../lib/agentExport");
45
+ /** Hard cap for a repo export — 10 pages × 100. */
46
+ const MAX_PAGES = 10;
47
+ const PAGE_SIZE = 100;
48
+ function parseFormat(value) {
49
+ const v = (value ?? '').trim().toLowerCase();
50
+ if (agentExport_1.AGENT_EXPORT_FORMATS.includes(v))
51
+ return v;
52
+ throw new Error(`--format must be one of: ${agentExport_1.AGENT_EXPORT_FORMATS.join(', ')}.`);
53
+ }
54
+ function fromRemote(p) {
55
+ const v = (0, promptResolver_1.fetchPromptContent)(p);
56
+ const body = v
57
+ ? (0, agentExport_1.composePromptMarkdown)({ role: v.role_text, context: v.context_text, description: v.description_text, content: v.content })
58
+ : '';
59
+ if (!body.trim())
60
+ return null;
61
+ return { title: p.title, description: p.description ?? null, body, projectName: p.project_name ?? null };
62
+ }
63
+ function fromLocal(p) {
64
+ if (!p.body.trim())
65
+ return null;
66
+ return { title: p.title, description: p.description || null, body: p.body.trim() };
67
+ }
68
+ async function collectRemoteRepo(projectId) {
69
+ const out = [];
70
+ for (let page = 1; page <= MAX_PAGES; page++) {
71
+ const rows = await (0, api_client_1.listPrompts)({ projectId, limit: PAGE_SIZE, page });
72
+ for (const r of rows) {
73
+ const e = fromRemote(r);
74
+ if (e)
75
+ out.push(e);
76
+ }
77
+ if (rows.length < PAGE_SIZE)
78
+ break;
79
+ }
80
+ return out;
81
+ }
82
+ function ensureWritable(target, force) {
83
+ if (fs.existsSync(target) && !force) {
84
+ throw new Error(`${target} already exists. Re-run with --force to overwrite.`);
85
+ }
86
+ }
87
+ function writeSkill(skill, options) {
88
+ const parent = path.resolve(options.out ?? '.');
89
+ fs.mkdirSync(parent, { recursive: true });
90
+ if (options.zip) {
91
+ const target = path.join(parent, `${skill.name}.zip`);
92
+ ensureWritable(target, options.force);
93
+ fs.writeFileSync(target, (0, agentExport_1.createZip)(skill.files));
94
+ return target;
95
+ }
96
+ const folder = path.join(parent, skill.name);
97
+ ensureWritable(folder, options.force);
98
+ for (const f of skill.files) {
99
+ const target = path.join(parent, ...f.path.split('/'));
100
+ fs.mkdirSync(path.dirname(target), { recursive: true });
101
+ fs.writeFileSync(target, f.content, 'utf-8');
102
+ }
103
+ return folder;
104
+ }
105
+ function writeAgentsMd(text, options) {
106
+ if (!options.out) {
107
+ process.stdout.write(text);
108
+ return null;
109
+ }
110
+ const target = path.resolve(options.out);
111
+ ensureWritable(target, options.force);
112
+ fs.mkdirSync(path.dirname(target), { recursive: true });
113
+ fs.writeFileSync(target, text, 'utf-8');
114
+ return target;
115
+ }
116
+ /**
117
+ * `ple export [name] --format agents-md|skill` — one prompt, or a whole repo
118
+ * with `--project` and no name.
119
+ *
120
+ * ple export "code review" --format agents-md >> AGENTS.md
121
+ * ple export "code review" --format skill --out ~/.claude/skills
122
+ * ple export --project ai-os --format skill --zip # upload in Claude
123
+ *
124
+ * Signed out, it exports from the local store (no name → every local prompt).
125
+ */
126
+ async function exportCommand(name, options = {}) {
127
+ const format = parseFormat(options.format);
128
+ if (options.zip && format !== 'skill')
129
+ throw new Error('--zip only applies to --format skill.');
130
+ const exportedAt = new Date().toISOString();
131
+ let single = null;
132
+ let repo = null;
133
+ if ((0, local_1.isSignedOut)()) {
134
+ if (options.project) {
135
+ console.error(format_1.c.muted(`(--project '${options.project}' is ignored while signed out — local prompts have no projects)`));
136
+ }
137
+ if (name) {
138
+ const hit = store.resolve(name);
139
+ if (hit === null || 'candidates' in hit) {
140
+ throw new Error(hit === null
141
+ ? `No local prompt matched '${name}'.`
142
+ : `'${name}' matches ${hit.candidates.length} local prompts: ${hit.candidates.map((p) => p.slug).join(', ')}.`);
143
+ }
144
+ single = fromLocal(hit.prompt);
145
+ if (!single)
146
+ throw new Error(`'${hit.prompt.title}' has empty content.`);
147
+ }
148
+ else {
149
+ const prompts = store.list().map(fromLocal).filter((p) => p !== null);
150
+ repo = { name: 'prompts', prompts };
151
+ }
152
+ }
153
+ else {
154
+ await (0, api_client_1.ensureAuthed)();
155
+ const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
156
+ if (name) {
157
+ const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
158
+ if (!prompt) {
159
+ process.exitCode = 1;
160
+ return;
161
+ }
162
+ single = fromRemote(prompt);
163
+ if (!single)
164
+ throw new Error(`'${prompt.title}' has empty content.`);
165
+ }
166
+ else if (projectId) {
167
+ const prompts = await collectRemoteRepo(projectId);
168
+ repo = { name: prompts[0]?.projectName ?? options.project ?? 'prompts', prompts };
169
+ }
170
+ else {
171
+ throw new Error('Give a prompt name, or --project <repo> to export a whole repo.');
172
+ }
173
+ }
174
+ let text = null;
175
+ let skill = null;
176
+ let count = 1;
177
+ if (single) {
178
+ if (format === 'agents-md')
179
+ text = (0, agentExport_1.buildAgentsMdSection)(single, exportedAt);
180
+ else
181
+ skill = (0, agentExport_1.buildPromptSkill)(single, exportedAt);
182
+ }
183
+ else if (repo) {
184
+ if (repo.prompts.length === 0)
185
+ throw new Error('Nothing to export — no prompts with content.');
186
+ count = repo.prompts.length;
187
+ if (format === 'agents-md')
188
+ text = (0, agentExport_1.buildAgentsMdDocument)(repo.name, null, repo.prompts, exportedAt);
189
+ else
190
+ skill = (0, agentExport_1.buildProjectSkill)(repo.name, null, repo.prompts, exportedAt);
191
+ }
192
+ const written = skill ? writeSkill(skill, options) : writeAgentsMd(text ?? '', options);
193
+ if (written) {
194
+ console.error(format_1.c.success(`✓ Exported ${count} prompt${count === 1 ? '' : 's'} → ${written}`));
195
+ }
196
+ }
@@ -118,10 +118,13 @@ async function saveCommand(title, options = {}) {
118
118
  return;
119
119
  }
120
120
  const slug = store.slugify(cleanTitle);
121
+ const previous = store.read(slug);
121
122
  // Overwriting someone's prompt silently is the one unrecoverable thing this
122
- // command could do — the local store keeps no versions.
123
- if (store.exists(slug) && !options.force) {
124
- console.error(format_1.c.error(`'${slug}' already exists.`));
123
+ // command could do — the local store keeps no versions. Farklı başlıklar
124
+ // aynı slug'a inebilir ("a/b" ve "a:b" → "ab"); mesaj bu yüzden mevcut
125
+ // kaydın GERÇEK başlığını söyler, kullanıcının hiç yazmadığı slug'ı değil.
126
+ if (previous && !options.force) {
127
+ console.error(format_1.c.error(`'${slug}' already exists (saved as "${previous.title}").`));
125
128
  console.error(format_1.c.muted('Overwrite it with --force, or pick a different title.'));
126
129
  process.exitCode = 1;
127
130
  return;
@@ -129,7 +132,6 @@ async function saveCommand(title, options = {}) {
129
132
  // On --force, fields the user did not re-specify are CARRIED OVER.
130
133
  // Overwriting the body must not silently wipe tags and the description —
131
134
  // the local store keeps no versions, so that loss is unrecoverable.
132
- const previous = store.read(slug);
133
135
  const tags = options.tag && options.tag.length > 0 ? options.tag : (previous?.tags ?? []);
134
136
  const description = options.description?.trim() ?? previous?.description ?? '';
135
137
  const saved = store.save({ slug, title: cleanTitle, description, tags, body });
@@ -78,21 +78,35 @@ async function syncCommand(options = {}) {
78
78
  let truncatedByQuota = 0;
79
79
  let tagsApplied = 0;
80
80
  let serverCarriesTags = true;
81
+ // Batch hatası (ör. 2. batch'te plan limiti → HTTP 429) yükseltilirse bile
82
+ // 1. batch'in SONUCU raporlanmak zorunda: "✗ limit" tek satırıyla susmak,
83
+ // yüklenmiş 50 prompt'u yok saymaktı (denetim bulgusu 2a).
84
+ let abortMessage = null;
81
85
  for (let i = 0; i < payload.length; i += BATCH) {
82
- const res = await (0, api_client_1.importPrompts)(payload.slice(i, i + BATCH));
83
- imported += res.imported;
84
- failed += res.failed;
85
- skippedInvalid += res.skippedInvalid;
86
- truncatedByQuota += res.truncatedByQuota;
87
- if (res.tagsApplied === undefined)
88
- serverCarriesTags = false;
89
- else
90
- tagsApplied += res.tagsApplied;
86
+ try {
87
+ const res = await (0, api_client_1.importPrompts)(payload.slice(i, i + BATCH));
88
+ imported += res.imported;
89
+ failed += res.failed;
90
+ skippedInvalid += res.skippedInvalid;
91
+ truncatedByQuota += res.truncatedByQuota;
92
+ if (res.tagsApplied === undefined)
93
+ serverCarriesTags = false;
94
+ else
95
+ tagsApplied += res.tagsApplied;
96
+ }
97
+ catch (err) {
98
+ abortMessage = err instanceof Error ? err.message : String(err);
99
+ truncatedByQuota += payload.length - i; // bu ve sonraki batch'ler gitmedi
100
+ break;
101
+ }
91
102
  }
92
103
  const tagNote = serverCarriesTags && tagsApplied > 0 ? ` (+${tagsApplied} tag link${tagsApplied === 1 ? '' : 's'})` : '';
93
104
  console.log(format_1.c.success(`✓ Uploaded ${imported} prompt${imported === 1 ? '' : 's'}${tagNote}`));
94
105
  // Each shortfall gets its own line with its own fix — "12 of 20 synced"
95
106
  // with no reason is the kind of message that sends people to support.
107
+ if (abortMessage) {
108
+ console.log(format_1.c.warn(`⚠ Stopped early: ${abortMessage}`));
109
+ }
96
110
  if (truncatedByQuota > 0) {
97
111
  console.log(format_1.c.warn(`⚠ ${truncatedByQuota} not uploaded — plan prompt limit reached.`));
98
112
  console.log(format_1.c.muted(' Upgrade for unlimited prompts, then run `ple sync` again.'));
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ const improve_1 = require("./commands/improve");
22
22
  const loop_1 = require("./commands/loop");
23
23
  const save_1 = require("./commands/save");
24
24
  const sync_1 = require("./commands/sync");
25
+ const export_1 = require("./commands/export");
25
26
  /** A single global try/catch — consistent error output for every command. */
26
27
  function runWithErrorHandler(fn) {
27
28
  return async (...args) => {
@@ -100,8 +101,17 @@ program
100
101
  .option('-p, --pick <n>', 'Non-interactive: auto-pick variant N each round + auto-continue — for scripts/agents')
101
102
  .option('--project <repo>', 'Scope to one repo (name, slug, or id) when titles collide')
102
103
  .action(runWithErrorHandler(loop_1.loopCommand));
104
+ program
105
+ .command('export [name]')
106
+ .description('Export a prompt (or a whole repo with --project) as an AGENTS.md section or an Agent Skill (SKILL.md)')
107
+ .requiredOption('--format <format>', 'agents-md | skill')
108
+ .option('--project <repo>', 'Repo to export (no name) or to scope the name to')
109
+ .option('-o, --out <path>', 'agents-md: file to write (default stdout) · skill: parent folder (default .)')
110
+ .option('--zip', 'skill: write <name>.zip (upload in Claude) instead of a folder')
111
+ .option('-f, --force', 'Overwrite an existing file or folder')
112
+ .action(runWithErrorHandler(export_1.exportCommand));
103
113
  program
104
114
  .command('search <keyword>')
105
- .description('Search within title and description')
115
+ .description('Search titles and descriptions (signed out: also local prompt bodies and tags)')
106
116
  .action(runWithErrorHandler(search_1.searchCommand));
107
117
  program.parseAsync(process.argv);
@@ -0,0 +1,378 @@
1
+ "use strict";
2
+ /**
3
+ * Agent formatlarına dışa aktarma — AGENTS.md bölümü + Agent Skills (SKILL.md) + zip.
4
+ *
5
+ * ⚠️ İKİ KOPYA, BİREBİR AYNI: web `src/lib/export/agent-export.ts` ve CLI
6
+ * `cli/src/lib/agentExport.ts`. CLI ayrı npm paketi, web'den import edemez
7
+ * (emsal: promptVariables). `agent-export.sync.test.ts` iki dosyanın byte-byte
8
+ * aynı olduğunu doğrular — birini değiştirince diğerine kopyala.
9
+ * Bu yüzden dosya HİÇBİR ŞEY import etmez ve DOM/Node API'sine dayanmaz.
10
+ *
11
+ * Format kaynakları (2026-09-27 doğrulandı):
12
+ * - Agent Skills spec (agentskills.io/specification) + Anthropic docs
13
+ * (platform.claude.com/docs/en/agents-and-tools/agent-skills/overview):
14
+ * `name` 1-64, [a-z0-9-], baş/son tire yok, `--` yok, klasör adıyla aynı,
15
+ * "anthropic"/"claude" içeremez, XML etiketi yok. `description` 1-1024,
16
+ * ne yaptığını + NE ZAMAN kullanılacağını söyler, `<`/`>` yok (Anthropic
17
+ * skill-creator quick_validate.py). İzinli frontmatter: name, description,
18
+ * license, compatibility, metadata (string→string), allowed-tools.
19
+ * - claude.ai yükleme: zip'in kökünde skill KLASÖRÜ olmalı
20
+ * (`my-skill.zip └── my-skill/SKILL.md`), dosyalar doğrudan kökte değil.
21
+ * - AGENTS.md (agents.md): serbest Markdown, zorunlu alan yok → prompt başına
22
+ * bir `##` bölümü; gövdedeki başlıklar bir seviye aşağı itilir.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.AGENT_EXPORT_FORMATS = void 0;
26
+ exports.toSkillName = toSkillName;
27
+ exports.listVariables = listVariables;
28
+ exports.demoteHeadings = demoteHeadings;
29
+ exports.composePromptMarkdown = composePromptMarkdown;
30
+ exports.buildAgentsMdSection = buildAgentsMdSection;
31
+ exports.buildAgentsMdDocument = buildAgentsMdDocument;
32
+ exports.buildSkillDescription = buildSkillDescription;
33
+ exports.buildPromptSkill = buildPromptSkill;
34
+ exports.buildProjectSkill = buildProjectSkill;
35
+ exports.createZip = createZip;
36
+ exports.AGENT_EXPORT_FORMATS = ['agents-md', 'skill'];
37
+ const SKILL_NAME_MAX = 64;
38
+ const SKILL_DESCRIPTION_MAX = 1024;
39
+ const RESERVED_WORDS = ['anthropic', 'claude'];
40
+ const SOURCE = 'promptlikeengineer.com';
41
+ const TURKISH_MAP = {
42
+ ı: 'i', İ: 'i', ş: 's', Ş: 's', ğ: 'g', Ğ: 'g', ü: 'u', Ü: 'u', ö: 'o', Ö: 'o', ç: 'c', Ç: 'c',
43
+ };
44
+ // ---------------------------------------------------------------------------
45
+ // Metin yardımcıları
46
+ // ---------------------------------------------------------------------------
47
+ function toAsciiSlug(input) {
48
+ return input
49
+ .replace(/[ıİşŞğĞüÜöÖçÇ]/g, (ch) => TURKISH_MAP[ch] ?? ch)
50
+ .normalize('NFKD')
51
+ .replace(/[̀-ͯ]/g, '')
52
+ .toLowerCase()
53
+ .replace(/[^a-z0-9]+/g, '-')
54
+ .replace(/^-+|-+$/g, '');
55
+ }
56
+ /**
57
+ * Başlığı spec-uyumlu skill adına çevirir. Rezerve kelimeler ("claude",
58
+ * "anthropic") çıkarılır — Anthropic yüklemesi bunları reddeder.
59
+ */
60
+ function toSkillName(title, fallback = 'prompt') {
61
+ let slug = toAsciiSlug(title);
62
+ for (const word of RESERVED_WORDS)
63
+ slug = slug.split(word).join('-');
64
+ slug = slug.replace(/-{2,}/g, '-').replace(/^-+|-+$/g, '');
65
+ if (slug.length > SKILL_NAME_MAX)
66
+ slug = slug.slice(0, SKILL_NAME_MAX).replace(/-+$/g, '');
67
+ return slug || fallback;
68
+ }
69
+ /** `<`/`>` ve satır sonlarını temizler (frontmatter tek satır kalsın). */
70
+ function sanitizeInline(text) {
71
+ return text.replace(/[<>]/g, '').replace(/\s+/g, ' ').trim();
72
+ }
73
+ function truncate(text, max) {
74
+ if (text.length <= max)
75
+ return text;
76
+ return `${text.slice(0, max - 1).trimEnd()}…`;
77
+ }
78
+ /** YAML çift tırnaklı skaler — ters bölü ve tırnak kaçışlı. */
79
+ function yamlString(value) {
80
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
81
+ }
82
+ /** Metindeki benzersiz {{değişken}} adları (promptVariables ile aynı desen). */
83
+ function listVariables(text) {
84
+ const seen = new Set();
85
+ for (const m of text.matchAll(/\{\{\s*([\p{L}\p{N}_.-]+)\s*\}\}/gu))
86
+ seen.add(m[1]);
87
+ return [...seen];
88
+ }
89
+ /**
90
+ * Markdown başlıklarını `levels` kadar aşağı iter (fenced code içini atlar,
91
+ * en fazla h6). AGENTS.md'de prompt başlığı `##` olduğu için gövde `###`'ten başlar.
92
+ */
93
+ function demoteHeadings(markdown, levels) {
94
+ let inFence = false;
95
+ return markdown
96
+ .split('\n')
97
+ .map((line) => {
98
+ if (/^\s*(```|~~~)/.test(line)) {
99
+ inFence = !inFence;
100
+ return line;
101
+ }
102
+ if (inFence)
103
+ return line;
104
+ const m = /^(#{1,6})(\s.*)$/.exec(line);
105
+ if (!m)
106
+ return line;
107
+ return `${'#'.repeat(Math.min(6, m[1].length + levels))}${m[2]}`;
108
+ })
109
+ .join('\n');
110
+ }
111
+ /**
112
+ * Yapısal parçalardan Markdown gövde — web `composeMarkdown` ile aynı düzen
113
+ * (## Role / ## Context / ## Instructions). Parçalar boşsa legacy `content`.
114
+ */
115
+ function composePromptMarkdown(parts) {
116
+ const blocks = [];
117
+ if (parts.role?.trim())
118
+ blocks.push(`## Role\n\n${parts.role.trim()}`);
119
+ if (parts.context?.trim())
120
+ blocks.push(`## Context\n\n${parts.context.trim()}`);
121
+ const desc = parts.description?.trim();
122
+ if (desc)
123
+ blocks.push(desc.startsWith('#') ? desc : `## Instructions\n\n${desc}`);
124
+ if (blocks.length > 0)
125
+ return blocks.join('\n\n');
126
+ return parts.content?.trim() ?? '';
127
+ }
128
+ // ---------------------------------------------------------------------------
129
+ // AGENTS.md
130
+ // ---------------------------------------------------------------------------
131
+ function provenance(p, exportedAt) {
132
+ const parts = [SOURCE];
133
+ if (p.projectName)
134
+ parts.push(`repo: ${p.projectName}`);
135
+ if (p.version != null)
136
+ parts.push(`v${p.version}`);
137
+ parts.push(`exported ${exportedAt.slice(0, 10)}`);
138
+ return `<!-- ${parts.join(' · ').replace(/--/g, '-')} -->`;
139
+ }
140
+ /** Tek prompt → mevcut bir AGENTS.md'ye yapıştırılacak `##` bölümü. */
141
+ function buildAgentsMdSection(p, exportedAt) {
142
+ const lines = [`## ${sanitizeInline(p.title) || 'Untitled prompt'}`, '', provenance(p, exportedAt), ''];
143
+ const desc = sanitizeInline(p.description ?? '');
144
+ if (desc)
145
+ lines.push(`> ${desc}`, '');
146
+ const vars = listVariables(p.body);
147
+ if (vars.length > 0) {
148
+ lines.push(`Placeholders to fill before use: ${vars.map((v) => `\`{{${v}}}\``).join(', ')}.`, '');
149
+ }
150
+ lines.push(demoteHeadings(p.body.trim(), 1));
151
+ return `${lines.join('\n').trimEnd()}\n`;
152
+ }
153
+ /** Bir repo → tam AGENTS.md belgesi (repo başlığı + prompt başına bölüm). */
154
+ function buildAgentsMdDocument(projectName, projectDescription, prompts, exportedAt) {
155
+ const head = [`# ${sanitizeInline(projectName) || 'Prompts'}`, ''];
156
+ const desc = sanitizeInline(projectDescription ?? '');
157
+ if (desc)
158
+ head.push(desc, '');
159
+ head.push(`Reusable prompts exported from ${SOURCE} on ${exportedAt.slice(0, 10)}. ` +
160
+ 'Each section is one prompt; follow it when the task matches its title.', '');
161
+ const sections = prompts.map((p) => buildAgentsMdSection(p, exportedAt).trimEnd());
162
+ return `${[head.join('\n').trimEnd(), ...sections].join('\n\n')}\n`;
163
+ }
164
+ // ---------------------------------------------------------------------------
165
+ // Agent Skills (SKILL.md)
166
+ // ---------------------------------------------------------------------------
167
+ /** "Ne yapar + ne zaman kullanılır" — spec'in iki şartı; 1024 sınırı, `<>` yok. */
168
+ function buildSkillDescription(p) {
169
+ const title = sanitizeInline(p.title) || 'this prompt';
170
+ const what = sanitizeInline(p.description ?? '').replace(/[.\s]+$/, '');
171
+ const whatPart = what ? `${what}.` : `Applies the saved prompt "${title}".`;
172
+ const when = ` Use when the user asks for "${title}" or a task that matches it.`;
173
+ return truncate(`${whatPart}${when}`, SKILL_DESCRIPTION_MAX);
174
+ }
175
+ function frontmatter(name, description, meta) {
176
+ const lines = ['---', `name: ${name}`, `description: ${yamlString(description)}`, 'metadata:'];
177
+ for (const [k, v] of Object.entries(meta))
178
+ lines.push(` ${k}: ${yamlString(v)}`);
179
+ lines.push('---');
180
+ return lines.join('\n');
181
+ }
182
+ function inputsSection(vars) {
183
+ if (vars.length === 0)
184
+ return '';
185
+ return [
186
+ '## Inputs',
187
+ '',
188
+ 'This prompt has placeholders. Take each value from the conversation, or ask the user once for the missing ones, then substitute them before following the instructions:',
189
+ '',
190
+ ...vars.map((v) => `- \`{{${v}}}\``),
191
+ '',
192
+ ].join('\n');
193
+ }
194
+ /** Tek prompt → `<name>/SKILL.md`. */
195
+ function buildPromptSkill(p, exportedAt) {
196
+ const name = toSkillName(p.title);
197
+ const meta = { source: SOURCE, exported: exportedAt.slice(0, 10) };
198
+ if (p.projectName)
199
+ meta.repo = sanitizeInline(p.projectName);
200
+ if (p.version != null)
201
+ meta.version = String(p.version);
202
+ const body = [
203
+ frontmatter(name, buildSkillDescription(p), meta),
204
+ '',
205
+ `# ${sanitizeInline(p.title) || name}`,
206
+ '',
207
+ inputsSection(listVariables(p.body)),
208
+ p.body.trim(),
209
+ ]
210
+ .filter((s, i, arr) => !(s === '' && arr[i - 1] === ''))
211
+ .join('\n');
212
+ return { name, files: [{ path: `${name}/SKILL.md`, content: `${body.trimEnd()}\n` }] };
213
+ }
214
+ /**
215
+ * Bir repo → TEK skill: SKILL.md bir dizin (progressive disclosure), her prompt
216
+ * `references/<ad>.md`. Claude yalnız eşleşen referansı okur → bağlam şişmez.
217
+ */
218
+ function buildProjectSkill(projectName, projectDescription, prompts, exportedAt) {
219
+ const name = toSkillName(projectName, 'prompt-library');
220
+ const used = new Set();
221
+ const refs = prompts.map((p) => {
222
+ let file = toSkillName(p.title);
223
+ let n = 2;
224
+ while (used.has(file))
225
+ file = `${toSkillName(p.title)}-${n++}`;
226
+ used.add(file);
227
+ return { p, file };
228
+ });
229
+ const desc = sanitizeInline(projectDescription ?? '').replace(/[.\s]+$/, '');
230
+ // Benzersiz başlıklar (aynı adlı prompt'lar açıklamada tekrar etmesin), ilk 8.
231
+ const uniqueTitles = [...new Set(prompts.map((p) => sanitizeInline(p.title)).filter(Boolean))];
232
+ const titles = uniqueTitles.slice(0, 8);
233
+ const description = truncate(`${desc ? `${desc}. ` : ''}Library of ${prompts.length} saved prompt${prompts.length === 1 ? '' : 's'} from the "${sanitizeInline(projectName)}" repo` +
234
+ `${titles.length ? ` (${titles.join(', ')}${uniqueTitles.length > titles.length ? ', …' : ''})` : ''}. ` +
235
+ 'Use when the user asks for one of these tasks or refers to a prompt from this repo by name.', SKILL_DESCRIPTION_MAX);
236
+ const index = refs.map(({ p, file }) => {
237
+ const d = sanitizeInline(p.description ?? '');
238
+ return `- **${sanitizeInline(p.title) || file}** → [references/${file}.md](references/${file}.md)${d ? `: ${d}` : ''}`;
239
+ });
240
+ const skillMd = [
241
+ frontmatter(name, description, { source: SOURCE, repo: sanitizeInline(projectName), exported: exportedAt.slice(0, 10) }),
242
+ '',
243
+ `# ${sanitizeInline(projectName) || name}`,
244
+ '',
245
+ 'Pick the prompt that matches the task, read only that reference file, fill its `{{placeholders}}` from the conversation (ask once for missing ones), then follow it.',
246
+ '',
247
+ '## Prompts',
248
+ '',
249
+ ...index,
250
+ '',
251
+ ].join('\n');
252
+ const files = [{ path: `${name}/SKILL.md`, content: skillMd }];
253
+ for (const { p, file } of refs) {
254
+ const header = [`# ${sanitizeInline(p.title) || file}`, ''];
255
+ const d = sanitizeInline(p.description ?? '');
256
+ if (d)
257
+ header.push(`> ${d}`, '');
258
+ files.push({
259
+ path: `${name}/references/${file}.md`,
260
+ content: `${header.join('\n')}${demoteHeadings(p.body.trim(), 1)}\n`,
261
+ });
262
+ }
263
+ return { name, files };
264
+ }
265
+ // ---------------------------------------------------------------------------
266
+ // Zip (STORE, sıkıştırmasız) — bağımlılıksız; web + CLI aynı byte'ları üretir.
267
+ // ---------------------------------------------------------------------------
268
+ function utf8(text) {
269
+ const out = [];
270
+ for (const ch of text) {
271
+ let cp = ch.codePointAt(0) ?? 0;
272
+ if (cp < 0x80)
273
+ out.push(cp);
274
+ else if (cp < 0x800)
275
+ out.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
276
+ else if (cp < 0x10000) {
277
+ if (cp >= 0xd800 && cp <= 0xdfff)
278
+ cp = 0xfffd; // yalnız surrogate → U+FFFD
279
+ out.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
280
+ }
281
+ else {
282
+ out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
283
+ }
284
+ }
285
+ return Uint8Array.from(out);
286
+ }
287
+ let crcTable = null;
288
+ function crc32(data) {
289
+ if (!crcTable) {
290
+ crcTable = new Uint32Array(256);
291
+ for (let n = 0; n < 256; n++) {
292
+ let c = n;
293
+ for (let k = 0; k < 8; k++)
294
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
295
+ crcTable[n] = c >>> 0;
296
+ }
297
+ }
298
+ let crc = 0xffffffff;
299
+ for (let i = 0; i < data.length; i++)
300
+ crc = crcTable[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
301
+ return (crc ^ 0xffffffff) >>> 0;
302
+ }
303
+ /**
304
+ * Dosyaları zip'e koyar. Ara klasörler için dizin girdisi de yazılır (bazı
305
+ * yükleyiciler kökteki klasörü girdiden tanır). Adlar UTF-8 (bit 11).
306
+ */
307
+ function createZip(files, date = new Date()) {
308
+ const dosTime = (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2);
309
+ const dosDate = ((Math.max(1980, date.getFullYear()) - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
310
+ const entries = [];
311
+ const dirs = new Set();
312
+ for (const f of files) {
313
+ const segs = f.path.split('/');
314
+ for (let i = 1; i < segs.length; i++) {
315
+ const dir = `${segs.slice(0, i).join('/')}/`;
316
+ if (!dirs.has(dir)) {
317
+ dirs.add(dir);
318
+ entries.push({ name: utf8(dir), data: new Uint8Array(0), dir: true });
319
+ }
320
+ }
321
+ entries.push({ name: utf8(f.path), data: utf8(f.content), dir: false });
322
+ }
323
+ const chunks = [];
324
+ const central = [];
325
+ let offset = 0;
326
+ for (const e of entries) {
327
+ const crc = crc32(e.data);
328
+ const local = new Uint8Array(30 + e.name.length);
329
+ const lv = new DataView(local.buffer);
330
+ lv.setUint32(0, 0x04034b50, true);
331
+ lv.setUint16(4, 20, true);
332
+ lv.setUint16(6, 0x0800, true);
333
+ lv.setUint16(8, 0, true);
334
+ lv.setUint16(10, dosTime, true);
335
+ lv.setUint16(12, dosDate, true);
336
+ lv.setUint32(14, crc, true);
337
+ lv.setUint32(18, e.data.length, true);
338
+ lv.setUint32(22, e.data.length, true);
339
+ lv.setUint16(26, e.name.length, true);
340
+ lv.setUint16(28, 0, true);
341
+ local.set(e.name, 30);
342
+ const cd = new Uint8Array(46 + e.name.length);
343
+ const cv = new DataView(cd.buffer);
344
+ cv.setUint32(0, 0x02014b50, true);
345
+ cv.setUint16(4, 20, true);
346
+ cv.setUint16(6, 20, true);
347
+ cv.setUint16(8, 0x0800, true);
348
+ cv.setUint16(10, 0, true);
349
+ cv.setUint16(12, dosTime, true);
350
+ cv.setUint16(14, dosDate, true);
351
+ cv.setUint32(16, crc, true);
352
+ cv.setUint32(20, e.data.length, true);
353
+ cv.setUint32(24, e.data.length, true);
354
+ cv.setUint16(28, e.name.length, true);
355
+ cv.setUint32(38, e.dir ? 0x10 : 0, true);
356
+ cv.setUint32(42, offset, true);
357
+ cd.set(e.name, 46);
358
+ chunks.push(local, e.data);
359
+ central.push(cd);
360
+ offset += local.length + e.data.length;
361
+ }
362
+ const cdSize = central.reduce((n, c) => n + c.length, 0);
363
+ const end = new Uint8Array(22);
364
+ const ev = new DataView(end.buffer);
365
+ ev.setUint32(0, 0x06054b50, true);
366
+ ev.setUint16(8, entries.length, true);
367
+ ev.setUint16(10, entries.length, true);
368
+ ev.setUint32(12, cdSize, true);
369
+ ev.setUint32(16, offset, true);
370
+ const all = [...chunks, ...central, end];
371
+ const out = new Uint8Array(all.reduce((n, c) => n + c.length, 0));
372
+ let pos = 0;
373
+ for (const c of all) {
374
+ out.set(c, pos);
375
+ pos += c.length;
376
+ }
377
+ return out;
378
+ }
@@ -34,7 +34,6 @@ exports.CLI_NAME = 'ple';
34
34
  function readVersion() {
35
35
  try {
36
36
  const pkgPath = '../../package.json';
37
- // eslint-disable-next-line @typescript-eslint/no-var-requires
38
37
  const pkg = require(pkgPath);
39
38
  return pkg.version ?? '0.0.0';
40
39
  }
@@ -145,7 +145,12 @@ function parse(slug, raw) {
145
145
  const header = raw.slice(3, end);
146
146
  const body = raw.slice(end + 4).replace(/^\r?\n/, '');
147
147
  const field = (name) => {
148
- const m = header.match(new RegExp(`^${name}:\\s*(.*)$`, 'm'));
148
+ // [ \t]* — ASLA \s* değil: \s satır sonunu da eşler; alan boşken
149
+ // (`description:`) bir SONRAKİ frontmatter satırını yutuyordu. 0.4.0'da
150
+ // yayınlanan veri-bozma hatası buydu: bayraksız `ple save` sonrası
151
+ // description "tags:" oluyor, tags ["created: <ts>"] oluyor; --force
152
+ // taşıması çöpü dosyaya kalıcı yazıyor, sync hesaba sızdırıyordu.
153
+ const m = header.match(new RegExp(`^${name}:[ \\t]*(.*)$`, 'm'));
149
154
  return m ? m[1].trim() : '';
150
155
  };
151
156
  const tags = field('tags')
@@ -177,8 +182,16 @@ function save(p) {
177
182
  ensureDir();
178
183
  const now = new Date().toISOString();
179
184
  const previous = exists(p.slug) ? read(p.slug) : null;
185
+ // Etiketler virgülde bölünür: serialize ', ' ile birleştirip parse virgülden
186
+ // böldüğü için virgül içeren tek etiket zaten round-trip edemez — sessiz
187
+ // bölünme yerine kayıtta normalize edilir.
188
+ const tags = p.tags
189
+ .flatMap((t) => t.split(','))
190
+ .map((t) => t.trim())
191
+ .filter(Boolean);
180
192
  const record = {
181
193
  ...p,
194
+ tags,
182
195
  // Overwriting keeps the original creation time — the file has a history
183
196
  // even though this store does not keep versions.
184
197
  created: p.created || previous?.created || now,
@@ -56,8 +56,9 @@ async function bearerPost(path, body) {
56
56
  if (res.status === 403)
57
57
  throw new Error(proMessage(parsed.error));
58
58
  if (res.status === 402) {
59
- const base = parsed.error?.trim() || 'You are out of AI tokens';
60
- throw new Error(`${base} — top up or wait for your monthly reset: ${constants_1.API_BASE_URL}/settings`);
59
+ // Satış anı, hata anı değil: MicroBoost adıyla ve fiyatıyla anılır.
60
+ const base = parsed.error?.trim() || "You've used this month's AI tokens";
61
+ throw new Error(`${base}\n Top up: $3 MicroBoost (600K tokens) → ${constants_1.API_BASE_URL}/dashboard/settings`);
61
62
  }
62
63
  if (res.status === 429) {
63
64
  const retryAfter = res.headers.get('retry-after');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promptlike",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Terminal access to your PromptLikeEngineer prompt library - search, read, and copy your saved prompts without leaving the shell.",
5
5
  "bin": {
6
6
  "ple": "dist/index.js"