skilld 2.3.0 → 3.0.0-beta.2

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.
Files changed (146) hide show
  1. package/README.md +142 -353
  2. package/bin/skilld.mjs +56 -0
  3. package/loader/resolve-artifact.mjs +37 -0
  4. package/package.json +28 -55
  5. package/dist/_chunks/add.mjs +0 -95
  6. package/dist/_chunks/add.mjs.map +0 -1
  7. package/dist/_chunks/agent-prompt.mjs +0 -90
  8. package/dist/_chunks/agent-prompt.mjs.map +0 -1
  9. package/dist/_chunks/agent.mjs +0 -1817
  10. package/dist/_chunks/agent.mjs.map +0 -1
  11. package/dist/_chunks/args.mjs +0 -49
  12. package/dist/_chunks/args.mjs.map +0 -1
  13. package/dist/_chunks/assemble.mjs +0 -126
  14. package/dist/_chunks/assemble.mjs.map +0 -1
  15. package/dist/_chunks/author.mjs +0 -432
  16. package/dist/_chunks/author.mjs.map +0 -1
  17. package/dist/_chunks/cache.mjs +0 -367
  18. package/dist/_chunks/cache.mjs.map +0 -1
  19. package/dist/_chunks/cache2.mjs +0 -151
  20. package/dist/_chunks/cache2.mjs.map +0 -1
  21. package/dist/_chunks/changes-digest.mjs +0 -49
  22. package/dist/_chunks/changes-digest.mjs.map +0 -1
  23. package/dist/_chunks/changes.mjs +0 -23
  24. package/dist/_chunks/changes.mjs.map +0 -1
  25. package/dist/_chunks/client.mjs +0 -182
  26. package/dist/_chunks/client.mjs.map +0 -1
  27. package/dist/_chunks/core.mjs +0 -13
  28. package/dist/_chunks/detect.mjs +0 -614
  29. package/dist/_chunks/detect.mjs.map +0 -1
  30. package/dist/_chunks/detect2.mjs +0 -2
  31. package/dist/_chunks/eject.mjs +0 -69
  32. package/dist/_chunks/eject.mjs.map +0 -1
  33. package/dist/_chunks/embedding-cache.mjs +0 -2
  34. package/dist/_chunks/embedding-cache2.mjs +0 -61
  35. package/dist/_chunks/embedding-cache2.mjs.map +0 -1
  36. package/dist/_chunks/env.mjs +0 -19
  37. package/dist/_chunks/env.mjs.map +0 -1
  38. package/dist/_chunks/index-identity.mjs +0 -365
  39. package/dist/_chunks/index-identity.mjs.map +0 -1
  40. package/dist/_chunks/index-identity2.mjs +0 -2
  41. package/dist/_chunks/install-many.mjs +0 -542
  42. package/dist/_chunks/install-many.mjs.map +0 -1
  43. package/dist/_chunks/install.mjs +0 -259
  44. package/dist/_chunks/install.mjs.map +0 -1
  45. package/dist/_chunks/intro.mjs +0 -63
  46. package/dist/_chunks/intro.mjs.map +0 -1
  47. package/dist/_chunks/list.mjs +0 -102
  48. package/dist/_chunks/list.mjs.map +0 -1
  49. package/dist/_chunks/lockfile.mjs +0 -174
  50. package/dist/_chunks/lockfile.mjs.map +0 -1
  51. package/dist/_chunks/login.mjs +0 -247
  52. package/dist/_chunks/login.mjs.map +0 -1
  53. package/dist/_chunks/logout.mjs +0 -27
  54. package/dist/_chunks/logout.mjs.map +0 -1
  55. package/dist/_chunks/map.mjs +0 -11
  56. package/dist/_chunks/map.mjs.map +0 -1
  57. package/dist/_chunks/markdown.mjs +0 -101
  58. package/dist/_chunks/markdown.mjs.map +0 -1
  59. package/dist/_chunks/menu.mjs +0 -33
  60. package/dist/_chunks/menu.mjs.map +0 -1
  61. package/dist/_chunks/model-picker.mjs +0 -61
  62. package/dist/_chunks/model-picker.mjs.map +0 -1
  63. package/dist/_chunks/monorepo.mjs +0 -74
  64. package/dist/_chunks/monorepo.mjs.map +0 -1
  65. package/dist/_chunks/package-json.mjs +0 -84
  66. package/dist/_chunks/package-json.mjs.map +0 -1
  67. package/dist/_chunks/paths.mjs +0 -47
  68. package/dist/_chunks/paths.mjs.map +0 -1
  69. package/dist/_chunks/pipeline.mjs +0 -993
  70. package/dist/_chunks/pipeline.mjs.map +0 -1
  71. package/dist/_chunks/pool.mjs +0 -2
  72. package/dist/_chunks/pool2.mjs +0 -121
  73. package/dist/_chunks/pool2.mjs.map +0 -1
  74. package/dist/_chunks/portable.mjs +0 -152
  75. package/dist/_chunks/portable.mjs.map +0 -1
  76. package/dist/_chunks/prepare-hook.mjs +0 -2
  77. package/dist/_chunks/prepare-hook2.mjs +0 -61
  78. package/dist/_chunks/prepare-hook2.mjs.map +0 -1
  79. package/dist/_chunks/prepare.mjs +0 -113
  80. package/dist/_chunks/prepare.mjs.map +0 -1
  81. package/dist/_chunks/prepare2.mjs +0 -80
  82. package/dist/_chunks/prepare2.mjs.map +0 -1
  83. package/dist/_chunks/prompts.mjs +0 -1252
  84. package/dist/_chunks/prompts.mjs.map +0 -1
  85. package/dist/_chunks/pull.mjs +0 -190
  86. package/dist/_chunks/pull.mjs.map +0 -1
  87. package/dist/_chunks/regex.mjs +0 -19
  88. package/dist/_chunks/regex.mjs.map +0 -1
  89. package/dist/_chunks/retriv.mjs +0 -2
  90. package/dist/_chunks/retriv2.mjs +0 -177
  91. package/dist/_chunks/retriv2.mjs.map +0 -1
  92. package/dist/_chunks/sanitize.mjs +0 -260
  93. package/dist/_chunks/sanitize.mjs.map +0 -1
  94. package/dist/_chunks/search-helpers.mjs +0 -88
  95. package/dist/_chunks/search-helpers.mjs.map +0 -1
  96. package/dist/_chunks/search-interactive.mjs +0 -249
  97. package/dist/_chunks/search-interactive.mjs.map +0 -1
  98. package/dist/_chunks/search.mjs +0 -247
  99. package/dist/_chunks/search.mjs.map +0 -1
  100. package/dist/_chunks/semver.mjs +0 -2831
  101. package/dist/_chunks/semver.mjs.map +0 -1
  102. package/dist/_chunks/skill-installer.mjs +0 -2
  103. package/dist/_chunks/skill-installer2.mjs +0 -163
  104. package/dist/_chunks/skill-installer2.mjs.map +0 -1
  105. package/dist/_chunks/skills.mjs +0 -187
  106. package/dist/_chunks/skills.mjs.map +0 -1
  107. package/dist/_chunks/store.mjs +0 -107
  108. package/dist/_chunks/store.mjs.map +0 -1
  109. package/dist/_chunks/sync.mjs +0 -1009
  110. package/dist/_chunks/sync.mjs.map +0 -1
  111. package/dist/_chunks/sync2.mjs +0 -2
  112. package/dist/_chunks/telemetry.mjs +0 -26
  113. package/dist/_chunks/telemetry.mjs.map +0 -1
  114. package/dist/_chunks/uninstall.mjs +0 -214
  115. package/dist/_chunks/uninstall.mjs.map +0 -1
  116. package/dist/_chunks/update.mjs +0 -133
  117. package/dist/_chunks/update.mjs.map +0 -1
  118. package/dist/_chunks/upload.mjs +0 -155
  119. package/dist/_chunks/upload.mjs.map +0 -1
  120. package/dist/_chunks/validate.mjs +0 -60
  121. package/dist/_chunks/validate.mjs.map +0 -1
  122. package/dist/_chunks/version.mjs +0 -19
  123. package/dist/_chunks/version.mjs.map +0 -1
  124. package/dist/_chunks/watch.mjs +0 -2
  125. package/dist/_chunks/watch2.mjs +0 -118
  126. package/dist/_chunks/watch2.mjs.map +0 -1
  127. package/dist/_chunks/whoami.mjs +0 -21
  128. package/dist/_chunks/whoami.mjs.map +0 -1
  129. package/dist/_chunks/wizard.mjs +0 -2
  130. package/dist/_chunks/wizard2.mjs +0 -200
  131. package/dist/_chunks/wizard2.mjs.map +0 -1
  132. package/dist/_chunks/yaml.mjs +0 -33
  133. package/dist/_chunks/yaml.mjs.map +0 -1
  134. package/dist/cli-entry.d.mts +0 -1
  135. package/dist/cli-entry.mjs +0 -5
  136. package/dist/cli-entry.mjs.map +0 -1
  137. package/dist/cli.d.mts +0 -1
  138. package/dist/cli.mjs +0 -1330
  139. package/dist/cli.mjs.map +0 -1
  140. package/dist/prepare.d.mts +0 -1
  141. package/dist/prepare.mjs +0 -84
  142. package/dist/prepare.mjs.map +0 -1
  143. package/dist/retriv/worker.d.mts +0 -37
  144. package/dist/retriv/worker.d.mts.map +0 -1
  145. package/dist/retriv/worker.mjs +0 -46
  146. package/dist/retriv/worker.mjs.map +0 -1
@@ -1,1817 +0,0 @@
1
- import { detectInstalledAgents, targets } from "./detect.mjs";
2
- import { SECTION_MERGE_ORDER, SECTION_OUTPUT_FILES, buildAllSectionPrompts, getSectionValidator, resolveSkilldCommand, wrapSection } from "./prompts.mjs";
3
- import { ollamaHost } from "./index-identity.mjs";
4
- import { CACHE_DIR, LLM_CACHE_DIR, PI_AI_AUTH_PATH, skillInternalDir, skillLogDir } from "./paths.mjs";
5
- import { API_CHANGE_BULLET_RE, SECTION_HEADING_RE, SOURCE_LINK_RE, TRAILING_SLASH_RE } from "./regex.mjs";
6
- import { sanitizeMarkdown } from "./sanitize.mjs";
7
- import { createReferenceCache, getSkillReferenceDirs } from "./cache.mjs";
8
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
9
- import { promisify, styleText } from "node:util";
10
- import { join } from "pathe";
11
- import { exec, execFileSync, spawn } from "node:child_process";
12
- import { isWindows } from "std-env";
13
- import { homedir } from "node:os";
14
- import { builtinModels, builtinProviders, getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
15
- import { resolve as resolve$1 } from "node:path";
16
- import { Type } from "typebox";
17
- import { glob, readFile } from "node:fs/promises";
18
- import { parseSync } from "oxc-parser";
19
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
20
- import { createHash } from "node:crypto";
21
- const STATIC_REGEX_1$6 = /-\d{8}$/;
22
- const STATIC_REGEX_2$5 = /-\d{4}-\d{2}-\d{2}$/;
23
- const STATIC_REGEX_3$3 = /-preview/;
24
- function isStableId(id) {
25
- if (STATIC_REGEX_1$6.test(id)) return false;
26
- if (STATIC_REGEX_2$5.test(id)) return false;
27
- if (STATIC_REGEX_3$3.test(id)) return false;
28
- return true;
29
- }
30
- function compareVersions(a, b) {
31
- const versionOf = (id) => {
32
- return (id.match(/\d+(?:\.\d+)?/g) ?? []).flatMap((n) => n.split(".").map(Number));
33
- };
34
- const av = versionOf(a);
35
- const bv = versionOf(b);
36
- for (let i = 0; i < Math.max(av.length, bv.length); i++) {
37
- const x = av[i] ?? 0;
38
- const y = bv[i] ?? 0;
39
- if (x !== y) return y - x;
40
- }
41
- return 0;
42
- }
43
- function resolve$2(opts) {
44
- const { provider, prefix, contains, exclude } = opts;
45
- return getBuiltinModels(provider).filter((m) => isStableId(m.id)).filter((m) => m.id.startsWith(prefix)).filter((m) => !contains || m.id.includes(contains)).filter((m) => !exclude?.some((e) => m.id.includes(e))).sort((a, b) => compareVersions(a.id, b.id))[0];
46
- }
47
- function buildModelEntry(opts) {
48
- const found = resolve$2(opts);
49
- const piName = found?.name;
50
- const transformed = piName && opts.nameTransform ? opts.nameTransform(piName) : piName;
51
- const name = opts.name ?? transformed ?? opts.model ?? opts.prefix;
52
- return {
53
- model: opts.model ?? found?.id ?? opts.prefix,
54
- name,
55
- hint: opts.hint,
56
- recommended: opts.recommended
57
- };
58
- }
59
- function buildModels(entries) {
60
- return Object.fromEntries(entries.map((e) => {
61
- const entry = buildModelEntry(e);
62
- return [entry.model, entry];
63
- }));
64
- }
65
- const TOOL_NAMES = {
66
- Read: {
67
- canonical: "read",
68
- verb: "Reading"
69
- },
70
- Glob: {
71
- canonical: "search",
72
- verb: "Searching"
73
- },
74
- Grep: {
75
- canonical: "search",
76
- verb: "Searching"
77
- },
78
- Write: {
79
- canonical: "write",
80
- verb: "Writing"
81
- },
82
- Bash: {
83
- canonical: "shell",
84
- verb: "Running"
85
- },
86
- read_file: {
87
- canonical: "read",
88
- verb: "Reading"
89
- },
90
- glob_tool: {
91
- canonical: "search",
92
- verb: "Searching"
93
- },
94
- write_file: {
95
- canonical: "write",
96
- verb: "Writing"
97
- },
98
- list_directory: {
99
- canonical: "list",
100
- verb: "Listing"
101
- },
102
- search_file_content: {
103
- canonical: "search",
104
- verb: "Searching"
105
- },
106
- run_shell_command: {
107
- canonical: "shell",
108
- verb: "Running"
109
- }
110
- };
111
- function extractToolHint(input) {
112
- if (!input) return void 0;
113
- for (const k of [
114
- "file_path",
115
- "path",
116
- "dir_path",
117
- "pattern",
118
- "query",
119
- "command"
120
- ]) {
121
- const v = input[k];
122
- if (typeof v === "string" && v) return v;
123
- }
124
- }
125
- const STATIC_REGEX_1$5 = /^Claude\s+/;
126
- const STATIC_REGEX_2$4 = /\s*\(latest\)\s*$/i;
127
- const stripClaude = (n) => n.replace(STATIC_REGEX_1$5, "").replace(STATIC_REGEX_2$4, "");
128
- function buildArgs$2(model, skillDir, symlinkDirs) {
129
- return [
130
- "-p",
131
- "--model",
132
- model,
133
- "--output-format",
134
- "stream-json",
135
- "--verbose",
136
- "--include-partial-messages",
137
- "--allowedTools",
138
- [
139
- "Read",
140
- "Glob",
141
- "Grep",
142
- "Bash(*skilld search*)",
143
- "Bash(*skilld validate*)"
144
- ].join(" "),
145
- "--disallowedTools",
146
- "WebSearch WebFetch Task",
147
- "--add-dir",
148
- skillDir,
149
- ...symlinkDirs.flatMap((d) => ["--add-dir", d]),
150
- "--no-session-persistence"
151
- ];
152
- }
153
- function parseEvent$2(line) {
154
- try {
155
- const obj = JSON.parse(line);
156
- if (obj.type === "stream_event") {
157
- const evt = obj.event;
158
- if (evt?.type === "content_block_delta" && evt.delta?.type === "text_delta") return {
159
- kind: "text",
160
- delta: evt.delta.text
161
- };
162
- return { kind: "noop" };
163
- }
164
- if (obj.type === "assistant" && obj.message?.content) {
165
- const content = obj.message.content;
166
- const tools = content.filter((c) => c.type === "tool_use");
167
- if (tools.length) return {
168
- kind: "tool-call",
169
- tool: tools.map((t) => t.name).join(", "),
170
- hint: tools.map((t) => extractToolHint(t.input) ?? "").filter(Boolean).join(", ") || void 0,
171
- writeContent: tools.find((t) => t.name === "Write" && t.input?.content)?.input?.content
172
- };
173
- const text = content.filter((c) => c.type === "text").map((c) => c.text).join("");
174
- if (text) return {
175
- kind: "text",
176
- full: text
177
- };
178
- }
179
- if (obj.type === "result") {
180
- const u = obj.usage;
181
- return {
182
- kind: "done",
183
- usage: u ? {
184
- input: u.input_tokens ?? u.inputTokens ?? 0,
185
- output: u.output_tokens ?? u.outputTokens ?? 0
186
- } : void 0,
187
- cost: obj.total_cost_usd,
188
- turns: obj.num_turns
189
- };
190
- }
191
- } catch {}
192
- return { kind: "noop" };
193
- }
194
- const adapter$2 = {
195
- cli: "claude",
196
- agentId: "claude-code",
197
- providerName: "Anthropic",
198
- models: buildModels([
199
- {
200
- model: "opus",
201
- provider: "anthropic",
202
- prefix: "claude-opus-",
203
- nameTransform: stripClaude,
204
- hint: "Most capable for complex work"
205
- },
206
- {
207
- model: "sonnet",
208
- provider: "anthropic",
209
- prefix: "claude-sonnet-",
210
- nameTransform: stripClaude,
211
- hint: "Best for everyday tasks"
212
- },
213
- {
214
- model: "haiku",
215
- provider: "anthropic",
216
- prefix: "claude-haiku-",
217
- nameTransform: stripClaude,
218
- hint: "Fastest for quick answers",
219
- recommended: true
220
- }
221
- ]),
222
- buildArgs: buildArgs$2,
223
- parseEvent: parseEvent$2
224
- };
225
- const STATIC_REGEX_1$4 = /^cat\s*>|>/;
226
- function buildArgs$1(model, _skillDir, _symlinkDirs) {
227
- return [
228
- "exec",
229
- "--json",
230
- "--ephemeral",
231
- "--model",
232
- model,
233
- "--full-auto",
234
- "-"
235
- ];
236
- }
237
- function parseEvent$1(line) {
238
- try {
239
- const obj = JSON.parse(line);
240
- if (obj.type === "item.completed" && obj.item) {
241
- const item = obj.item;
242
- if (item.type === "agent_message" && item.text) return {
243
- kind: "text",
244
- full: item.text
245
- };
246
- if (item.type === "command_execution" && item.aggregated_output) {
247
- const cmd = item.command || "";
248
- const writeContent = STATIC_REGEX_1$4.test(cmd) ? item.aggregated_output : void 0;
249
- return {
250
- kind: "tool-call",
251
- tool: "Bash",
252
- hint: `(${item.aggregated_output.length} chars output)`,
253
- writeContent
254
- };
255
- }
256
- if (item.type === "file_change" && item.changes?.length) return {
257
- kind: "tool-call",
258
- tool: "Write",
259
- hint: item.changes.map((c) => c.path).join(", ")
260
- };
261
- }
262
- if (obj.type === "item.started" && obj.item?.type === "command_execution") return {
263
- kind: "tool-call",
264
- tool: "Bash",
265
- hint: obj.item.command
266
- };
267
- if (obj.type === "turn.completed" && obj.usage) return {
268
- kind: "done",
269
- usage: {
270
- input: obj.usage.input_tokens ?? 0,
271
- output: obj.usage.output_tokens ?? 0
272
- }
273
- };
274
- if (obj.type === "turn.failed" || obj.type === "error") return {
275
- kind: "error",
276
- message: obj.message
277
- };
278
- } catch {}
279
- return { kind: "noop" };
280
- }
281
- const adapter$1 = {
282
- cli: "codex",
283
- agentId: "codex",
284
- providerName: "OpenAI",
285
- models: buildModels([
286
- {
287
- provider: "openai",
288
- prefix: "gpt-",
289
- contains: "codex",
290
- exclude: [
291
- "spark",
292
- "mini",
293
- "max"
294
- ],
295
- hint: "Latest frontier Codex model"
296
- },
297
- {
298
- provider: "openai",
299
- prefix: "gpt-",
300
- contains: "codex-spark",
301
- hint: "Faster Codex variant",
302
- recommended: true
303
- },
304
- {
305
- provider: "openai",
306
- prefix: "gpt-",
307
- contains: "codex-mini",
308
- hint: "Cheapest Codex variant"
309
- }
310
- ]),
311
- buildArgs: buildArgs$1,
312
- parseEvent: parseEvent$1
313
- };
314
- function buildArgs(model, skillDir, symlinkDirs) {
315
- return [
316
- "-o",
317
- "stream-json",
318
- "-m",
319
- model,
320
- "--allowed-tools",
321
- `read_file,write_file,glob_tool,list_directory,search_file_content,run_shell_command(${resolveSkilldCommand()}),run_shell_command(grep),run_shell_command(head)`,
322
- "--include-directories",
323
- skillDir,
324
- ...symlinkDirs.flatMap((d) => ["--include-directories", d])
325
- ];
326
- }
327
- function parseEvent(line) {
328
- try {
329
- const obj = JSON.parse(line);
330
- if (obj.type === "message" && obj.role === "assistant" && obj.content) return obj.delta ? {
331
- kind: "text",
332
- delta: obj.content
333
- } : {
334
- kind: "text",
335
- full: obj.content
336
- };
337
- if (obj.type === "tool_use" || obj.type === "tool_call") {
338
- const tool = obj.tool_name || obj.name || obj.tool || "tool";
339
- const params = obj.parameters || obj.args || obj.input || {};
340
- return {
341
- kind: "tool-call",
342
- tool,
343
- hint: extractToolHint(params),
344
- writeContent: tool === "write_file" && typeof params.content === "string" ? params.content : void 0
345
- };
346
- }
347
- if (obj.type === "result") {
348
- const s = obj.stats;
349
- return {
350
- kind: "done",
351
- usage: s ? {
352
- input: s.input_tokens ?? s.input ?? 0,
353
- output: s.output_tokens ?? s.output ?? 0
354
- } : void 0,
355
- turns: s?.tool_calls
356
- };
357
- }
358
- } catch {}
359
- return { kind: "noop" };
360
- }
361
- const adapter = {
362
- cli: "gemini",
363
- agentId: "gemini-cli",
364
- providerName: "Google",
365
- models: buildModels([{
366
- provider: "google",
367
- prefix: "gemini-",
368
- contains: "pro",
369
- exclude: [
370
- "flash",
371
- "live",
372
- "gemma"
373
- ],
374
- hint: "Most capable"
375
- }, {
376
- provider: "google",
377
- prefix: "gemini-",
378
- contains: "flash",
379
- exclude: [
380
- "lite",
381
- "live",
382
- "preview"
383
- ],
384
- hint: "Balanced",
385
- recommended: true
386
- }]),
387
- buildArgs,
388
- parseEvent
389
- };
390
- const OLLAMA_PREFIX = "ollama:";
391
- function isOllamaModel(model) {
392
- return model.startsWith(OLLAMA_PREFIX);
393
- }
394
- function parseOllamaModelId(model) {
395
- return isOllamaModel(model) ? model.slice(7) : null;
396
- }
397
- async function isCompletionModel(name) {
398
- const res = await fetch(`${ollamaHost()}/api/show`, {
399
- method: "POST",
400
- headers: { "content-type": "application/json" },
401
- body: JSON.stringify({ model: name }),
402
- signal: AbortSignal.timeout(1500)
403
- }).catch(() => null);
404
- if (!res?.ok) return true;
405
- const caps = (await res.json().catch(() => null))?.capabilities;
406
- return !caps?.length || caps.includes("completion") || caps.includes("insert");
407
- }
408
- async function getAvailableOllamaModels() {
409
- const res = await fetch(`${ollamaHost()}/api/tags`, { signal: AbortSignal.timeout(1500) }).catch(() => null);
410
- if (!res?.ok) return [];
411
- const data = await res.json().catch(() => null);
412
- if (!data?.models?.length) return [];
413
- return (await Promise.all(data.models.map(async (m) => {
414
- if (!await isCompletionModel(m.name)) return null;
415
- const params = m.details?.parameter_size;
416
- const quant = m.details?.quantization_level;
417
- const sizeGb = m.size ? `${(m.size / 1e9).toFixed(1)}GB` : void 0;
418
- const detail = params ? `${params}${quant ? ` ${quant}` : ""}` : sizeGb;
419
- return {
420
- id: `ollama:${m.name}`,
421
- name: m.name,
422
- hint: detail ? `local · ${detail}` : "local"
423
- };
424
- }))).filter((m) => m !== null);
425
- }
426
- function ollamaExecutor(model) {
427
- const modelId = parseOllamaModelId(model);
428
- if (!modelId) return { error: `Not an Ollama model: ${model}` };
429
- return {
430
- cliCleanup: false,
431
- run: async ({ section, prompt, timeout, onProgress }) => {
432
- const ac = new AbortController();
433
- const timer = setTimeout(() => ac.abort(), timeout);
434
- onProgress?.({
435
- chunk: "[ollama]",
436
- type: "reasoning",
437
- text: "",
438
- reasoning: "Generating locally…",
439
- section
440
- });
441
- const res = await fetch(`${ollamaHost()}/api/chat`, {
442
- method: "POST",
443
- headers: { "content-type": "application/json" },
444
- body: JSON.stringify({
445
- model: modelId,
446
- messages: [{
447
- role: "user",
448
- content: prompt
449
- }],
450
- stream: true,
451
- options: {
452
- temperature: .2,
453
- num_ctx: Number(process.env.OLLAMA_NUM_CTX) || 32768
454
- }
455
- }),
456
- signal: ac.signal
457
- }).catch((err) => ({
458
- ok: false,
459
- statusText: err.message,
460
- body: null
461
- }));
462
- if (!res.ok || !res.body) {
463
- clearTimeout(timer);
464
- return {
465
- text: "",
466
- stderr: `Ollama request failed: ${res.statusText}. Is \`ollama serve\` running at ${ollamaHost()}?`,
467
- exitCode: 1
468
- };
469
- }
470
- let text = "";
471
- let usage;
472
- const drain = async () => {
473
- const reader = res.body.getReader();
474
- const decoder = new TextDecoder();
475
- let buffer = "";
476
- for (;;) {
477
- const { done, value } = await reader.read();
478
- if (done) break;
479
- buffer += decoder.decode(value, { stream: true });
480
- const lines = buffer.split("\n");
481
- buffer = lines.pop() || "";
482
- for (const line of lines) {
483
- if (!line.trim()) continue;
484
- const chunk = JSON.parse(line);
485
- if (chunk.error) throw new Error(chunk.error);
486
- const delta = chunk.message?.content;
487
- if (delta) {
488
- text += delta;
489
- onProgress?.({
490
- chunk: delta,
491
- type: "text",
492
- text,
493
- reasoning: "",
494
- section
495
- });
496
- }
497
- if (chunk.done) usage = {
498
- input: chunk.prompt_eval_count ?? 0,
499
- output: chunk.eval_count ?? 0
500
- };
501
- }
502
- }
503
- };
504
- const streamError = await drain().then(() => void 0).catch((err) => err.message);
505
- clearTimeout(timer);
506
- if (streamError) return {
507
- text: "",
508
- stderr: `Ollama stream error: ${streamError}`,
509
- exitCode: 1
510
- };
511
- if (!text.trim()) return {
512
- text: "",
513
- stderr: "Ollama returned no content",
514
- exitCode: 1
515
- };
516
- return {
517
- text: text.trim(),
518
- usage,
519
- cost: 0
520
- };
521
- }
522
- };
523
- }
524
- const BLOCKED_OAUTH_PROVIDERS = /* @__PURE__ */ new Set([
525
- "github-copilot",
526
- "anthropic",
527
- "openai-codex"
528
- ]);
529
- const PI_AGENT_AUTH_PATH = join(process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"), "auth.json");
530
- const SKILLD_AUTH_PATH = PI_AI_AUTH_PATH;
531
- function isObjectRecord(value) {
532
- return typeof value === "object" && value !== null && !Array.isArray(value);
533
- }
534
- function isStringRecord(value) {
535
- return isObjectRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
536
- }
537
- function isCredential(value) {
538
- if (!isObjectRecord(value) || !("type" in value)) return false;
539
- if (value.type === "oauth") return "refresh" in value && typeof value.refresh === "string" && "access" in value && typeof value.access === "string" && "expires" in value && typeof value.expires === "number";
540
- if (value.type !== "api_key") return false;
541
- return (!("key" in value) || value.key === void 0 || typeof value.key === "string") && (!("env" in value) || value.env === void 0 || isStringRecord(value.env));
542
- }
543
- function readAuthFile(path) {
544
- if (!existsSync(path)) return {};
545
- try {
546
- const parsed = JSON.parse(readFileSync(path, "utf-8"));
547
- if (!isObjectRecord(parsed)) return {};
548
- return Object.fromEntries(Object.entries(parsed).filter((entry) => isCredential(entry[1])));
549
- } catch {
550
- return {};
551
- }
552
- }
553
- function loadAuth() {
554
- const piAuth = readAuthFile(PI_AGENT_AUTH_PATH);
555
- const skilldAuth = readAuthFile(SKILLD_AUTH_PATH);
556
- return {
557
- ...piAuth,
558
- ...skilldAuth
559
- };
560
- }
561
- function saveAuth(auth) {
562
- mkdirSync(CACHE_DIR, {
563
- recursive: true,
564
- mode: 448
565
- });
566
- writeFileSync(SKILLD_AUTH_PATH, JSON.stringify(auth, null, 2), { mode: 384 });
567
- }
568
- function createCredentialStore() {
569
- const chains = /* @__PURE__ */ new Map();
570
- return {
571
- async read(providerId) {
572
- return loadAuth()[providerId];
573
- },
574
- async list() {
575
- return Object.entries(loadAuth()).map(([providerId, credential]) => ({
576
- providerId,
577
- type: credential.type
578
- }));
579
- },
580
- async modify(providerId, update) {
581
- let result;
582
- const operation = (chains.get(providerId) ?? Promise.resolve()).then(async () => {
583
- const current = loadAuth()[providerId];
584
- const next = await update(current);
585
- result = next ?? current;
586
- if (next) {
587
- const localAuth = readAuthFile(SKILLD_AUTH_PATH);
588
- localAuth[providerId] = next;
589
- saveAuth(localAuth);
590
- }
591
- });
592
- chains.set(providerId, operation.then(() => void 0, () => void 0));
593
- await operation;
594
- return result;
595
- },
596
- async delete(providerId) {
597
- const localAuth = readAuthFile(SKILLD_AUTH_PATH);
598
- delete localAuth[providerId];
599
- saveAuth(localAuth);
600
- }
601
- };
602
- }
603
- function createPiAiModels() {
604
- return builtinModels({ credentials: createCredentialStore() });
605
- }
606
- function getOAuthProviderList() {
607
- const auth = loadAuth();
608
- return builtinProviders().filter((provider) => provider.auth.oauth && !BLOCKED_OAUTH_PROVIDERS.has(provider.id)).map((provider) => ({
609
- id: provider.id,
610
- name: provider.auth.oauth?.name ?? provider.name,
611
- loggedIn: auth[provider.id]?.type === "oauth"
612
- }));
613
- }
614
- async function loginOAuthProvider(providerId, callbacks) {
615
- const models = createPiAiModels();
616
- if (!models.getProvider(providerId)?.auth.oauth || BLOCKED_OAUTH_PROVIDERS.has(providerId)) return false;
617
- const notify = (event) => {
618
- if (event.type === "auth_url") callbacks.onAuth(event.url, event.instructions);
619
- else if (event.type === "device_code") {
620
- if (callbacks.onDeviceCode) callbacks.onDeviceCode(event.userCode, event.verificationUri);
621
- else callbacks.onAuth(event.verificationUri, `Enter code ${event.userCode}`);
622
- } else callbacks.onProgress?.(event.message);
623
- };
624
- const prompt = async (input) => {
625
- if (input.type !== "select") return callbacks.onPrompt(input.message, input.placeholder);
626
- const options = input.options.map((option) => ({
627
- id: option.id,
628
- label: option.label
629
- }));
630
- return await callbacks.onSelect?.(input.message, options) ?? options[0]?.id ?? "";
631
- };
632
- const interaction = {
633
- notify,
634
- prompt
635
- };
636
- await models.login(providerId, "oauth", interaction);
637
- return true;
638
- }
639
- async function logoutOAuthProvider(providerId) {
640
- await createPiAiModels().logout(providerId);
641
- }
642
- function isPiAiModel(model) {
643
- return model.startsWith("pi:");
644
- }
645
- function parsePiAiModelId(model) {
646
- if (!model.startsWith("pi:")) return null;
647
- const rest = model.slice(3);
648
- const slashIdx = rest.indexOf("/");
649
- if (slashIdx === -1) return null;
650
- return {
651
- provider: rest.slice(0, slashIdx),
652
- modelId: rest.slice(slashIdx + 1)
653
- };
654
- }
655
- const MIN_CONTEXT_WINDOW = 32e3;
656
- const LEGACY_MODEL_PATTERNS = [
657
- /^claude-3-/,
658
- /^claude-3\.5-/,
659
- /^claude-3\.7-/,
660
- /^gpt-4(?!\.\d)/,
661
- /^o1/,
662
- /^o3-mini/,
663
- /^gemini-1\./,
664
- /^gemini-2\.0/,
665
- /^gemini-live-/,
666
- /-preview-\d{2}-\d{2,4}$/,
667
- /-\d{8}$/
668
- ];
669
- function isLegacyModel(modelId) {
670
- return LEGACY_MODEL_PATTERNS.some((p) => p.test(modelId));
671
- }
672
- const RECOMMENDED_MODELS = {
673
- anthropic: /haiku/,
674
- google: /flash/,
675
- openai: /gpt-4\.1-mini/
676
- };
677
- async function getAvailablePiAiModels(models = createPiAiModels()) {
678
- const modelsByProvider = Map.groupBy(await models.getAvailable(), (model) => model.provider);
679
- const available = [];
680
- for (const [provider, providerModels] of modelsByProvider) {
681
- const auth = await models.checkAuth(provider);
682
- if (!auth) continue;
683
- const authSource = auth.type === "oauth" ? "oauth" : "api-key";
684
- const recPattern = RECOMMENDED_MODELS[provider];
685
- const recModelId = recPattern ? providerModels.find((model) => !isLegacyModel(model.id) && recPattern.test(model.id))?.id : void 0;
686
- for (const model of providerModels) {
687
- if (model.contextWindow && model.contextWindow < MIN_CONTEXT_WINDOW) continue;
688
- if (isLegacyModel(model.id)) continue;
689
- const id = `pi:${provider}/${model.id}`;
690
- const ctx = model.contextWindow ? ` · ${Math.round(model.contextWindow / 1e3)}k ctx` : "";
691
- const cost = model.cost?.input ? ` · $${model.cost.input}/Mtok` : "";
692
- available.push({
693
- id,
694
- name: model.name || model.id,
695
- hint: `${authSource === "oauth" ? "OAuth" : "API key"}${ctx}${cost}`,
696
- authSource,
697
- recommended: model.id === recModelId
698
- });
699
- }
700
- }
701
- return available;
702
- }
703
- const STATIC_REGEX_1$3 = /^\.\/\.skilld\//;
704
- const STATIC_REGEX_2$3 = /^\.skilld\//;
705
- const STATIC_REGEX_3$2 = /^\.\//;
706
- const STATIC_REGEX_5$2 = /\s+/;
707
- const TOOLS = [
708
- {
709
- name: "Read",
710
- description: "Read a file. Path is relative to the working directory (e.g. \"./.skilld/docs/api.md\").",
711
- parameters: Type.Object({ path: Type.String({ description: "File path to read" }) })
712
- },
713
- {
714
- name: "Glob",
715
- description: "List files matching a glob pattern (e.g. \"./.skilld/docs/*.md\"). Returns newline-separated paths.",
716
- parameters: Type.Object({
717
- pattern: Type.String({ description: "Glob pattern" }),
718
- no_ignore: Type.Optional(Type.Boolean({ description: "Include gitignored files" }))
719
- })
720
- },
721
- {
722
- name: "Write",
723
- description: "Write content to a file.",
724
- parameters: Type.Object({
725
- path: Type.String({ description: "File path to write" }),
726
- content: Type.String({ description: "File content" })
727
- })
728
- },
729
- {
730
- name: "Bash",
731
- description: "Run a shell command. Use for `skilld search`, `skilld validate`, etc.",
732
- parameters: Type.Object({ command: Type.String({ description: "Shell command to run" }) })
733
- }
734
- ];
735
- const SAFE_COMMANDS = /* @__PURE__ */ new Set([
736
- "skilld",
737
- "ls",
738
- "cat",
739
- "find"
740
- ]);
741
- const SHELL_META_RE = /[;&|`$()<>]/;
742
- function resolveSandboxedPath(p, skilldDir) {
743
- const cleaned = String(p).replace(STATIC_REGEX_1$3, "./").replace(STATIC_REGEX_2$3, "./").replace(STATIC_REGEX_3$2, "");
744
- const resolved = resolve$1(skilldDir, cleaned);
745
- if (!resolved.startsWith(`${skilldDir}/`) && resolved !== skilldDir) throw new Error(`Path traversal blocked: ${p}`);
746
- return resolved;
747
- }
748
- function globMatch(filePath, pattern) {
749
- const segments = pattern.split("**");
750
- if (segments.length === 1) {
751
- const parts = pattern.split("*");
752
- if (parts.length === 1) return filePath === pattern;
753
- let pos = 0;
754
- for (let i = 0; i < parts.length; i++) {
755
- const part = parts[i];
756
- if (!part) continue;
757
- const idx = filePath.indexOf(part, pos);
758
- if (idx === -1) return false;
759
- if (i === 0 && idx !== 0) return false;
760
- pos = idx + part.length;
761
- }
762
- if (parts.at(-1) !== "") return pos === filePath.length;
763
- return true;
764
- }
765
- let remaining = filePath;
766
- for (let i = 0; i < segments.length; i++) {
767
- const seg = segments[i];
768
- if (!seg) continue;
769
- const segParts = seg.split("*");
770
- let pos = 0;
771
- let matched = false;
772
- for (let attempt = remaining.indexOf(segParts[0], 0); attempt !== -1; attempt = remaining.indexOf(segParts[0], attempt + 1)) {
773
- pos = attempt;
774
- matched = true;
775
- for (const sp of segParts) {
776
- if (!sp) continue;
777
- const idx = remaining.indexOf(sp, pos);
778
- if (idx === -1) {
779
- matched = false;
780
- break;
781
- }
782
- pos = idx + sp.length;
783
- }
784
- if (matched) break;
785
- }
786
- if (!matched) return false;
787
- remaining = remaining.slice(pos);
788
- }
789
- return true;
790
- }
791
- function executeTool(toolCall, skilldDir) {
792
- const args = toolCall.arguments;
793
- switch (toolCall.name) {
794
- case "Read": {
795
- const filePath = resolveSandboxedPath(args.path, skilldDir);
796
- if (!existsSync(filePath)) return `Error: file not found: ${args.path}`;
797
- return sanitizeMarkdown(readFileSync(filePath, "utf-8"));
798
- }
799
- case "Glob": {
800
- const pattern = String(args.pattern).replace(STATIC_REGEX_1$3, "./").replace(STATIC_REGEX_2$3, "./").replace(STATIC_REGEX_3$2, "");
801
- const results = [];
802
- const walkDir = (dir, prefix) => {
803
- if (!existsSync(dir)) return;
804
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
805
- const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
806
- if (entry.isDirectory()) walkDir(join(dir, entry.name), relPath);
807
- else results.push(`./.skilld/${relPath}`);
808
- }
809
- };
810
- const baseDir = pattern.split("*")[0]?.replace(TRAILING_SLASH_RE, "") ?? "";
811
- walkDir(join(skilldDir, baseDir), baseDir);
812
- const matched = results.filter((r) => globMatch(r.replace(STATIC_REGEX_1$3, ""), pattern));
813
- return matched.length > 0 ? matched.join("\n") : `No files matching: ${args.pattern}`;
814
- }
815
- case "Write": {
816
- const filePath = resolveSandboxedPath(args.path, skilldDir);
817
- writeFileSync(filePath, sanitizeMarkdown(String(args.content)));
818
- return "File written successfully.";
819
- }
820
- case "Bash": {
821
- const cmd = String(args.command).trim();
822
- const parts = cmd.split(STATIC_REGEX_5$2);
823
- const bin = parts[0] ?? "";
824
- if (!SAFE_COMMANDS.has(bin) || SHELL_META_RE.test(cmd)) return `Error: command not allowed. Only skilld, ls, cat, find commands are permitted.`;
825
- try {
826
- return execFileSync(bin, parts.slice(1), {
827
- cwd: skilldDir,
828
- timeout: 15e3,
829
- encoding: "utf-8",
830
- maxBuffer: 524288
831
- }).trim();
832
- } catch (err) {
833
- return `Error: ${err.message}`;
834
- }
835
- }
836
- default: return `Unknown tool: ${toolCall.name}`;
837
- }
838
- }
839
- const SYSTEM_PROMPT = "You are a technical documentation expert generating SKILL.md sections for AI agent skills. Follow the format instructions exactly. Use the provided tools to explore reference files in ./.skilld/ before writing your output.";
840
- async function optimizeSectionPiAi(opts) {
841
- const parsed = parsePiAiModelId(opts.model);
842
- if (!parsed) throw new Error(`Invalid pi-ai model ID: ${opts.model}. Expected format: pi:provider/model-id`);
843
- const models = opts.models ?? createPiAiModels();
844
- const model = models.getModel(parsed.provider, parsed.modelId);
845
- if (!model) throw new Error(`Unknown pi-ai model: ${parsed.provider}/${parsed.modelId}`);
846
- const skilldDir = skillInternalDir(opts.skillDir);
847
- const fullPrompt = opts.prompt;
848
- opts.onProgress?.({
849
- chunk: "[starting...]",
850
- type: "reasoning",
851
- text: "",
852
- reasoning: "",
853
- section: opts.section
854
- });
855
- const messages = [{
856
- role: "user",
857
- content: [{
858
- type: "text",
859
- text: fullPrompt
860
- }],
861
- timestamp: Date.now()
862
- }];
863
- let text = "";
864
- let completed = false;
865
- let totalUsage;
866
- let totalCost;
867
- let lastWriteContent = "";
868
- for (let turn = 0; turn < 30; turn++) {
869
- if (opts.signal?.aborted) throw new Error("pi-ai request timed out");
870
- const eventStream = models.streamSimple(model, {
871
- systemPrompt: SYSTEM_PROMPT,
872
- messages,
873
- tools: TOOLS
874
- }, {
875
- reasoning: turn === 0 ? "medium" : void 0,
876
- maxTokens: 16384,
877
- signal: opts.signal
878
- });
879
- let assistantMessage;
880
- let turnText = "";
881
- for await (const event of eventStream) {
882
- if (opts.signal?.aborted) throw new Error("pi-ai request timed out");
883
- switch (event.type) {
884
- case "text_delta":
885
- turnText += event.delta;
886
- opts.onProgress?.({
887
- chunk: event.delta,
888
- type: "text",
889
- text: turnText,
890
- reasoning: "",
891
- section: opts.section
892
- });
893
- break;
894
- case "toolcall_end": {
895
- const tc = event.toolCall;
896
- const hint = tc.name === "Read" || tc.name === "Write" ? `[${tc.name}: ${tc.arguments.path}]` : tc.name === "Bash" ? `[${tc.name}: ${tc.arguments.command}]` : `[${tc.name}: ${tc.arguments.pattern}]`;
897
- opts.onProgress?.({
898
- chunk: hint,
899
- type: "reasoning",
900
- text: "",
901
- reasoning: hint,
902
- section: opts.section
903
- });
904
- break;
905
- }
906
- case "done":
907
- assistantMessage = event.message;
908
- break;
909
- case "error": throw new Error(event.error?.errorMessage ?? "pi-ai stream error");
910
- }
911
- }
912
- if (!assistantMessage) throw new Error("pi-ai stream ended without a message");
913
- if (assistantMessage.usage) {
914
- if (totalUsage) {
915
- totalUsage.input += assistantMessage.usage.input;
916
- totalUsage.output += assistantMessage.usage.output;
917
- } else totalUsage = {
918
- input: assistantMessage.usage.input,
919
- output: assistantMessage.usage.output
920
- };
921
- totalCost = (totalCost ?? 0) + (assistantMessage.usage.cost?.total ?? 0);
922
- }
923
- messages.push(assistantMessage);
924
- const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall");
925
- if (toolCalls.length === 0) {
926
- text = turnText;
927
- completed = true;
928
- break;
929
- }
930
- for (const tc of toolCalls) {
931
- const result = executeTool(tc, skilldDir);
932
- if (tc.name === "Write") lastWriteContent = String(tc.arguments.content);
933
- messages.push({
934
- role: "toolResult",
935
- toolCallId: tc.id,
936
- toolName: tc.name,
937
- content: [{
938
- type: "text",
939
- text: result
940
- }],
941
- isError: result.startsWith("Error:"),
942
- timestamp: Date.now()
943
- });
944
- }
945
- }
946
- if (!completed) throw new Error(`pi-ai exceeded 30 tool turns without completing`);
947
- return {
948
- text: text || lastWriteContent,
949
- fullPrompt,
950
- usage: totalUsage,
951
- cost: totalCost
952
- };
953
- }
954
- const STATIC_REGEX_1$2 = /^```(?:markdown|md)?[^\S\n]*\n([\s\S]+)\n```[^\S\n]*$/;
955
- const STATIC_REGEX_2$2 = /^```(?:markdown|md)/;
956
- const STATIC_REGEX_5$1 = /^-{3,}\n/;
957
- const STATIC_REGEX_6 = /\n-{3,}/;
958
- const STATIC_REGEX_7 = /^(##\s|- (?:BREAKING|DEPRECATED|NEW): )/m;
959
- const STATIC_REGEX_8 = /^(## .+)\n/;
960
- const STATIC_REGEX_9 = /^\.\/(?:\.skilld\/|references\/)/;
961
- function cleanSectionOutput(content) {
962
- let cleaned = content.trim();
963
- const wrapMatch = cleaned.match(STATIC_REGEX_1$2);
964
- if (wrapMatch) {
965
- const inner = wrapMatch[1].trim();
966
- if (STATIC_REGEX_2$2.test(cleaned) || SECTION_HEADING_RE.test(inner) || API_CHANGE_BULLET_RE.test(inner)) cleaned = inner;
967
- }
968
- cleaned = cleaned.replace(/^# (?!#)/gm, "## ");
969
- const fmMatch = cleaned.match(STATIC_REGEX_5$1);
970
- if (fmMatch) {
971
- const afterOpen = fmMatch[0].length;
972
- const closeMatch = cleaned.slice(afterOpen).match(STATIC_REGEX_6);
973
- if (closeMatch) cleaned = cleaned.slice(afterOpen + closeMatch.index + closeMatch[0].length).trim();
974
- else cleaned = cleaned.slice(afterOpen).trim();
975
- }
976
- const firstMarker = cleaned.match(STATIC_REGEX_7);
977
- if (firstMarker?.index && firstMarker.index > 0) cleaned = cleaned.slice(firstMarker.index).trim();
978
- const headingMatch = cleaned.match(STATIC_REGEX_8);
979
- if (headingMatch) {
980
- const heading = headingMatch[1];
981
- const afterFirst = headingMatch[0].length;
982
- const secondIdx = cleaned.indexOf(heading, afterFirst);
983
- if (secondIdx !== -1) {
984
- if (secondIdx - afterFirst < 200) cleaned = cleaned.slice(secondIdx).trim();
985
- }
986
- }
987
- cleaned = cleaned.replace(/\(?\[`?\.\/(?:\.skilld\/|references\/)[^)\]]*\]\(([^)]+)\)\)?/g, (match, url) => {
988
- if (STATIC_REGEX_9.test(url)) return `[source](${url})`;
989
- return match;
990
- });
991
- cleaned = cleaned.replace(/\[source\]\(\.\/((docs|issues|discussions|releases|pkg|guide)\/)/g, "[source](./.skilld/$1");
992
- cleaned = sanitizeMarkdown(cleaned);
993
- if (!SECTION_HEADING_RE.test(cleaned) && !API_CHANGE_BULLET_RE.test(cleaned) && !SOURCE_LINK_RE.test(cleaned)) return "";
994
- return cleaned;
995
- }
996
- const STATIC_REGEX_1$1 = /^\[(?:starting|retrying|cached)/;
997
- const STATIC_REGEX_2$1 = /^\[([^:[\]]+)(?::\s(.+))?\]$/;
998
- const STATIC_REGEX_3$1 = /skilld search\s+"([^"]+)"/;
999
- function createToolProgress(log) {
1000
- let lastMsg = "";
1001
- let repeatCount = 0;
1002
- const lastTextEmit = /* @__PURE__ */ new Map();
1003
- const TEXT_THROTTLE_MS = 2e3;
1004
- function emit(msg) {
1005
- if (msg === lastMsg) {
1006
- repeatCount++;
1007
- log.message(`${msg} ${styleText("gray", `(+${repeatCount})`)}`);
1008
- } else {
1009
- lastMsg = msg;
1010
- repeatCount = 0;
1011
- log.message(msg);
1012
- }
1013
- }
1014
- return ({ type, chunk, text, section }) => {
1015
- if (type === "text") {
1016
- const key = section ?? "";
1017
- const now = Date.now();
1018
- if (now - (lastTextEmit.get(key) ?? 0) < TEXT_THROTTLE_MS) return;
1019
- lastTextEmit.set(key, now);
1020
- const prefix = section ? `${styleText("gray", `[${section}]`)} ` : "";
1021
- const items = text ? text.match(/^- (?:BREAKING|DEPRECATED|NEW|CHANGED|REMOVED|Use |Do |Set |Add |Avoid |Always |Never |Prefer |Check |Ensure )/gm)?.length ?? 0 : 0;
1022
- emit(items > 0 ? `${prefix}Writing... ${styleText("gray", `(${items} items)`)}` : `${prefix}Writing...`);
1023
- return;
1024
- }
1025
- if (type !== "reasoning" || !chunk.startsWith("[")) return;
1026
- if (STATIC_REGEX_1$1.test(chunk)) {
1027
- emit(`${section ? `${styleText("gray", `[${section}]`)} ` : ""}${chunk.slice(1, -1)}`);
1028
- return;
1029
- }
1030
- const match = chunk.match(STATIC_REGEX_2$1);
1031
- if (!match) return;
1032
- const names = match[1].split(",").map((n) => n.trim());
1033
- const hints = match[2]?.split(",").map((h) => h.trim()) ?? [];
1034
- for (let i = 0; i < names.length; i++) {
1035
- const rawName = names[i];
1036
- const hint = hints[i] ?? hints[0] ?? "";
1037
- const verb = TOOL_NAMES[rawName]?.verb ?? rawName;
1038
- const prefix = section ? `${styleText("gray", `[${section}]`)} ` : "";
1039
- if ((rawName === "Bash" || rawName === "run_shell_command") && hint) {
1040
- const searchMatch = hint.match(STATIC_REGEX_3$1);
1041
- if (searchMatch) emit(`${prefix}Searching ${styleText("cyan", `"${searchMatch[1]}"`)}`);
1042
- else if (hint.includes("skilld validate")) emit(`${prefix}Validating...`);
1043
- else {
1044
- const shortened = shortenCommand(hint);
1045
- emit(`${prefix}Running ${shortened.length > 50 ? `${shortened.slice(0, 47)}...` : shortened}`);
1046
- }
1047
- } else {
1048
- const path = shortenPath(hint || "...");
1049
- emit(`${prefix}${verb} ${styleText("gray", path)}`);
1050
- }
1051
- }
1052
- };
1053
- }
1054
- function shortenPath(p) {
1055
- const refIdx = p.indexOf(".skilld/");
1056
- if (refIdx !== -1) return p.slice(refIdx + 8);
1057
- const parts = p.split("/");
1058
- return parts.length > 2 ? `.../${parts.slice(-2).join("/")}` : p;
1059
- }
1060
- function shortenCommand(cmd) {
1061
- return cmd.replace(/\/[^\s"']+/g, (match) => {
1062
- if (match.includes(".claude/") || match.includes(".skilld/") || match.includes("node_modules/")) return `.../${match.split("/").slice(-2).join("/")}`;
1063
- return match;
1064
- });
1065
- }
1066
- const CLI_ADAPTERS = {
1067
- claude: adapter$2,
1068
- gemini: adapter,
1069
- codex: adapter$1
1070
- };
1071
- const CLI_PROVIDER_NAMES = Object.fromEntries(Object.values(CLI_ADAPTERS).map((a) => [a.agentId, a.providerName]));
1072
- const PI_PROVIDER_NAMES = {
1073
- "anthropic": "Anthropic",
1074
- "google": "Google",
1075
- "google-antigravity": "Antigravity",
1076
- "google-gemini-cli": "Google Gemini",
1077
- "google-vertex": "Google Vertex",
1078
- "openai": "OpenAI",
1079
- "openai-codex": "OpenAI Codex",
1080
- "github-copilot": "GitHub Copilot",
1081
- "groq": "Groq",
1082
- "mistral": "Mistral",
1083
- "xai": "xAI"
1084
- };
1085
- const CLI_MODELS = Object.fromEntries(Object.values(CLI_ADAPTERS).flatMap((adapter) => Object.entries(adapter.models).map(([id, entry]) => [id, {
1086
- ...entry,
1087
- cli: adapter.cli,
1088
- agentId: adapter.agentId
1089
- }])));
1090
- function getModelName(id) {
1091
- if (isOllamaModel(id)) return parseOllamaModelId(id) ?? id;
1092
- if (isPiAiModel(id)) return parsePiAiModelId(id)?.modelId ?? id;
1093
- return CLI_MODELS[id]?.name ?? id;
1094
- }
1095
- function getModelLabel(id) {
1096
- if (isOllamaModel(id)) return `Ollama · ${parseOllamaModelId(id) ?? id}`;
1097
- if (isPiAiModel(id)) {
1098
- const parsed = parsePiAiModelId(id);
1099
- return parsed ? `${PI_PROVIDER_NAMES[parsed.provider] ?? parsed.provider} · ${parsed.modelId}` : id;
1100
- }
1101
- const config = CLI_MODELS[id];
1102
- if (!config) return id;
1103
- return `${CLI_PROVIDER_NAMES[config.agentId] ?? config.cli} · ${config.name}`;
1104
- }
1105
- async function getAvailableModels() {
1106
- const execAsync = promisify(exec);
1107
- const lookupCmd = isWindows ? "where" : "which";
1108
- const ollamaModelsPromise = getAvailableOllamaModels();
1109
- const agentsWithCli = detectInstalledAgents().filter((id) => targets[id].cli);
1110
- const cliChecks = await Promise.all(agentsWithCli.map(async (agentId) => {
1111
- const cli = targets[agentId].cli;
1112
- try {
1113
- await execAsync(`${lookupCmd} ${cli}`);
1114
- return agentId;
1115
- } catch {
1116
- return null;
1117
- }
1118
- }));
1119
- const availableAgentIds = new Set(cliChecks.filter((id) => id != null));
1120
- const cliModels = Object.entries(CLI_MODELS).filter(([_, config]) => availableAgentIds.has(config.agentId)).map(([id, config]) => {
1121
- const providerName = CLI_PROVIDER_NAMES[config.agentId] ?? targets[config.agentId]?.displayName ?? config.agentId;
1122
- return {
1123
- id,
1124
- name: config.name,
1125
- hint: config.hint,
1126
- recommended: config.recommended,
1127
- agentId: config.agentId,
1128
- agentName: providerName,
1129
- provider: config.agentId,
1130
- providerName: `${providerName} (via ${config.cli} CLI)`,
1131
- vendorGroup: providerName
1132
- };
1133
- });
1134
- const piAiEntries = (await getAvailablePiAiModels()).map((m) => {
1135
- const piProvider = parsePiAiModelId(m.id)?.provider ?? "pi-ai";
1136
- const displayName = PI_PROVIDER_NAMES[piProvider] ?? piProvider;
1137
- const authLabel = m.authSource === "api-key" ? "API key" : "OAuth";
1138
- return {
1139
- id: m.id,
1140
- name: m.name,
1141
- hint: m.hint,
1142
- recommended: m.recommended,
1143
- agentId: "pi-ai",
1144
- agentName: `pi-ai (${m.authSource})`,
1145
- provider: `pi:${piProvider}:${m.authSource}`,
1146
- providerName: `${displayName} (${authLabel})`,
1147
- vendorGroup: displayName
1148
- };
1149
- });
1150
- const ollamaEntries = (await ollamaModelsPromise).map((m) => ({
1151
- id: m.id,
1152
- name: m.name,
1153
- hint: m.hint,
1154
- agentId: "ollama",
1155
- agentName: "Ollama (local)",
1156
- provider: "ollama",
1157
- providerName: "Ollama (local)",
1158
- vendorGroup: "Ollama"
1159
- }));
1160
- return [
1161
- ...cliModels,
1162
- ...piAiEntries,
1163
- ...ollamaEntries
1164
- ];
1165
- }
1166
- const NUXT_CONFIG_FILES = [
1167
- "nuxt.config.ts",
1168
- "nuxt.config.js",
1169
- "nuxt.config.mjs"
1170
- ];
1171
- const NUXT_ECOSYSTEM = [
1172
- "vue",
1173
- "nitro",
1174
- "h3"
1175
- ];
1176
- async function findNuxtConfig(cwd) {
1177
- for (const name of NUXT_CONFIG_FILES) {
1178
- const path = join(cwd, name);
1179
- const content = await readFile(path, "utf8").catch(() => null);
1180
- if (content) return {
1181
- path,
1182
- content
1183
- };
1184
- }
1185
- return null;
1186
- }
1187
- function extractModuleStrings(node) {
1188
- if (!node || typeof node !== "object") return [];
1189
- if (node.type === "Property" && !node.computed && node.key?.type === "Identifier" && node.key.name === "modules" && node.value?.type === "ArrayExpression") return node.value.elements.filter((el) => el?.type === "Literal" && typeof el.value === "string").map((el) => el.value);
1190
- const results = [];
1191
- if (Array.isArray(node)) for (const child of node) results.push(...extractModuleStrings(child));
1192
- else for (const key of Object.keys(node)) {
1193
- if (key === "start" || key === "end" || key === "type") continue;
1194
- const val = node[key];
1195
- if (val && typeof val === "object") results.push(...extractModuleStrings(val));
1196
- }
1197
- return results;
1198
- }
1199
- async function detectNuxtModules(cwd) {
1200
- const config = await findNuxtConfig(cwd);
1201
- if (!config) return [];
1202
- const modules = extractModuleStrings(parseSync(config.path, config.content).program);
1203
- const seen = /* @__PURE__ */ new Set();
1204
- const packages = [];
1205
- for (const mod of modules) if (!seen.has(mod)) {
1206
- seen.add(mod);
1207
- packages.push({
1208
- name: mod,
1209
- count: 0,
1210
- source: "preset"
1211
- });
1212
- }
1213
- for (const pkg of NUXT_ECOSYSTEM) if (!seen.has(pkg)) {
1214
- seen.add(pkg);
1215
- packages.push({
1216
- name: pkg,
1217
- count: 0,
1218
- source: "preset"
1219
- });
1220
- }
1221
- return packages;
1222
- }
1223
- async function detectPresetPackages(cwd) {
1224
- return detectNuxtModules(cwd);
1225
- }
1226
- const FROM_STATIC_IMPORT_RE = /\bfrom\s*['"]([^'"\n]+)['"]/g;
1227
- const SIDE_EFFECT_IMPORT_RE = /\bimport\s*['"]([^'"\n]+)['"]/g;
1228
- const DYNAMIC_IMPORT_RE = /\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)/g;
1229
- const PATTERNS = ["**/*.{ts,js,vue,mjs,cjs,tsx,jsx,mts,cts}"];
1230
- const IGNORE_DIRS = [
1231
- "node_modules",
1232
- "dist",
1233
- ".nuxt",
1234
- ".output",
1235
- "coverage"
1236
- ];
1237
- function addPackage(counts, specifier) {
1238
- if (!specifier || specifier.startsWith(".") || specifier.startsWith("/")) return;
1239
- const name = specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0];
1240
- if (!isNodeBuiltin(name)) counts.set(name, (counts.get(name) || 0) + 1);
1241
- }
1242
- async function detectImportedPackages(cwd = process.cwd()) {
1243
- try {
1244
- const counts = /* @__PURE__ */ new Map();
1245
- const files = [];
1246
- for await (const file of glob(PATTERNS, {
1247
- cwd,
1248
- exclude: (p) => IGNORE_DIRS.some((dir) => p === dir || p.endsWith(`/${dir}`))
1249
- })) files.push(join(cwd, file));
1250
- await Promise.all(files.map(async (file) => {
1251
- const content = await readFile(file, "utf8");
1252
- for (const m of content.matchAll(FROM_STATIC_IMPORT_RE)) addPackage(counts, m[1]);
1253
- for (const m of content.matchAll(SIDE_EFFECT_IMPORT_RE)) addPackage(counts, m[1]);
1254
- for (const m of content.matchAll(DYNAMIC_IMPORT_RE)) addPackage(counts, m[1]);
1255
- }));
1256
- const packages = Array.from(counts.entries(), ([name, count]) => ({
1257
- name,
1258
- count,
1259
- source: "import"
1260
- })).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
1261
- const presets = await detectPresetPackages(cwd);
1262
- const importNames = new Set(packages.map((p) => p.name));
1263
- for (const preset of presets) if (!importNames.has(preset.name)) packages.push(preset);
1264
- return { packages };
1265
- } catch (err) {
1266
- return {
1267
- packages: [],
1268
- error: String(err)
1269
- };
1270
- }
1271
- }
1272
- const NODE_BUILTINS = /* @__PURE__ */ new Set([
1273
- "assert",
1274
- "async_hooks",
1275
- "buffer",
1276
- "child_process",
1277
- "cluster",
1278
- "console",
1279
- "constants",
1280
- "crypto",
1281
- "dgram",
1282
- "diagnostics_channel",
1283
- "dns",
1284
- "domain",
1285
- "events",
1286
- "fs",
1287
- "http",
1288
- "http2",
1289
- "https",
1290
- "inspector",
1291
- "module",
1292
- "net",
1293
- "os",
1294
- "path",
1295
- "perf_hooks",
1296
- "process",
1297
- "punycode",
1298
- "querystring",
1299
- "readline",
1300
- "repl",
1301
- "sea",
1302
- "sqlite",
1303
- "stream",
1304
- "string_decoder",
1305
- "sys",
1306
- "test",
1307
- "timers",
1308
- "tls",
1309
- "trace_events",
1310
- "tty",
1311
- "url",
1312
- "util",
1313
- "v8",
1314
- "vm",
1315
- "wasi",
1316
- "worker_threads",
1317
- "zlib"
1318
- ]);
1319
- function isNodeBuiltin(pkg) {
1320
- const base = pkg.startsWith("node:") ? pkg.slice(5) : pkg;
1321
- return NODE_BUILTINS.has(base.split("/")[0]);
1322
- }
1323
- const DEFAULT_MAX_AGE = 6048e5;
1324
- function normalizePromptForHash(prompt) {
1325
- return prompt.replace(/\/[^\s`]*\.(?:claude|codex|gemini)\/skills\/[^\s/`]+/g, "<SKILL_DIR>");
1326
- }
1327
- function hashPrompt(prompt, model, section) {
1328
- return createHash("sha256").update(`exec:${model}:${section}:${normalizePromptForHash(prompt)}`).digest("hex").slice(0, 16);
1329
- }
1330
- function getCached(prompt, model, section, maxAge = DEFAULT_MAX_AGE) {
1331
- const path = join(LLM_CACHE_DIR, `${hashPrompt(prompt, model, section)}.json`);
1332
- if (!existsSync(path)) return null;
1333
- try {
1334
- const { text, timestamp } = JSON.parse(readFileSync(path, "utf-8"));
1335
- return Date.now() - timestamp > maxAge ? null : text;
1336
- } catch {
1337
- return null;
1338
- }
1339
- }
1340
- function setCache(prompt, model, section, text) {
1341
- mkdirSync(LLM_CACHE_DIR, {
1342
- recursive: true,
1343
- mode: 448
1344
- });
1345
- writeFileSync(join(LLM_CACHE_DIR, `${hashPrompt(prompt, model, section)}.json`), JSON.stringify({
1346
- text,
1347
- model,
1348
- section,
1349
- timestamp: Date.now()
1350
- }), { mode: 384 });
1351
- }
1352
- function prepareSection(opts) {
1353
- if (existsSync(opts.outputPath)) unlinkSync(opts.outputPath);
1354
- writeFileSync(join(opts.skilldDir, `PROMPT_${opts.section}.md`), opts.prompt);
1355
- }
1356
- function finalizeSection(opts) {
1357
- const { section, raw, outputFile, outputPath, skilldDir, debug, cliCleanup } = opts;
1358
- if (cliCleanup) for (const entry of readdirSync(skilldDir)) {
1359
- if (entry === outputFile || cliCleanup.preExistingFiles.has(entry)) continue;
1360
- if (Object.values(SECTION_OUTPUT_FILES).includes(entry)) continue;
1361
- if (entry.startsWith("PROMPT_") || entry === "logs") continue;
1362
- try {
1363
- unlinkSync(join(skilldDir, entry));
1364
- } catch {}
1365
- }
1366
- const logsDir = join(skilldDir, "logs");
1367
- const logName = section.toUpperCase().replace(/-/g, "_");
1368
- const text = ((existsSync(outputPath) ? readFileSync(outputPath, "utf-8") : "") || raw.writeContent || raw.text).trim();
1369
- const stderr = raw.stderr ?? "";
1370
- const code = raw.exitCode ?? 0;
1371
- if (debug || stderr && (!text || code !== 0)) {
1372
- mkdirSync(logsDir, { recursive: true });
1373
- if (stderr) writeFileSync(join(logsDir, `${logName}.stderr.log`), stderr);
1374
- }
1375
- if (debug) {
1376
- mkdirSync(logsDir, { recursive: true });
1377
- if (raw.rawLines?.length) writeFileSync(join(logsDir, `${logName}.jsonl`), raw.rawLines.join("\n"));
1378
- if (text) writeFileSync(join(logsDir, `${logName}.md`), text);
1379
- }
1380
- if (!text && code !== 0) return {
1381
- section,
1382
- content: "",
1383
- wasOptimized: false,
1384
- error: stderr.trim() || `CLI exited with code ${code}`
1385
- };
1386
- const content = text ? cleanSectionOutput(text) : "";
1387
- if (content) writeFileSync(outputPath, content);
1388
- const validator = getSectionValidator(section);
1389
- const warnings = (content && validator ? validator(content) : []).map((w) => ({
1390
- section,
1391
- warning: w.warning
1392
- }));
1393
- return {
1394
- section,
1395
- content,
1396
- wasOptimized: !!content,
1397
- warnings: warnings.length ? warnings : void 0,
1398
- usage: raw.usage,
1399
- cost: raw.cost
1400
- };
1401
- }
1402
- function spawnCliAndStream(opts) {
1403
- const { adapter, cliModel, prompt, skillDir, skilldDir, symlinkDirs, timeout, debug, section, onProgress } = opts;
1404
- const args = adapter.buildArgs(cliModel, skillDir, symlinkDirs);
1405
- const parseEvent = adapter.parseEvent;
1406
- return new Promise((resolve) => {
1407
- const proc = spawn(adapter.cli, args, {
1408
- cwd: skilldDir,
1409
- stdio: [
1410
- "pipe",
1411
- "pipe",
1412
- "pipe"
1413
- ],
1414
- timeout,
1415
- env: {
1416
- ...process.env,
1417
- NO_COLOR: "1"
1418
- },
1419
- shell: isWindows
1420
- });
1421
- let buffer = "";
1422
- let accumulatedText = "";
1423
- let lastWriteContent = "";
1424
- let usage;
1425
- let cost;
1426
- const rawLines = [];
1427
- onProgress?.({
1428
- chunk: "[starting...]",
1429
- type: "reasoning",
1430
- text: "",
1431
- reasoning: "",
1432
- section
1433
- });
1434
- proc.stdin.write(prompt);
1435
- proc.stdin.end();
1436
- function applyEvent(evt) {
1437
- switch (evt.kind) {
1438
- case "text":
1439
- if (evt.delta) accumulatedText += evt.delta;
1440
- if (evt.full !== void 0) accumulatedText = evt.full;
1441
- break;
1442
- case "tool-call": {
1443
- if (evt.writeContent) lastWriteContent = evt.writeContent;
1444
- const chunk = evt.hint ? `[${evt.tool}: ${evt.hint}]` : `[${evt.tool}]`;
1445
- onProgress?.({
1446
- chunk,
1447
- type: "reasoning",
1448
- text: "",
1449
- reasoning: chunk,
1450
- section
1451
- });
1452
- break;
1453
- }
1454
- case "done":
1455
- if (evt.usage) usage = evt.usage;
1456
- if (evt.cost != null) cost = evt.cost;
1457
- }
1458
- }
1459
- proc.stdout.on("data", (chunk) => {
1460
- buffer += chunk.toString();
1461
- const lines = buffer.split("\n");
1462
- buffer = lines.pop() || "";
1463
- for (const line of lines) {
1464
- if (!line.trim()) continue;
1465
- if (debug) rawLines.push(line);
1466
- applyEvent(parseEvent(line));
1467
- }
1468
- });
1469
- let stderr = "";
1470
- proc.stderr.on("data", (chunk) => {
1471
- stderr += chunk.toString();
1472
- });
1473
- proc.on("close", (code) => {
1474
- if (buffer.trim()) applyEvent(parseEvent(buffer));
1475
- resolve({
1476
- text: accumulatedText,
1477
- writeContent: lastWriteContent || void 0,
1478
- usage,
1479
- cost,
1480
- stderr,
1481
- exitCode: code ?? 0,
1482
- rawLines: debug ? rawLines : void 0
1483
- });
1484
- });
1485
- proc.on("error", (err) => {
1486
- resolve({
1487
- text: "",
1488
- stderr: err.message,
1489
- exitCode: 1
1490
- });
1491
- });
1492
- });
1493
- }
1494
- function cliExecutor(model) {
1495
- const cliConfig = CLI_MODELS[model];
1496
- if (!cliConfig) return { error: `No CLI mapping for model: ${model}` };
1497
- const adapter = CLI_ADAPTERS[cliConfig.cli];
1498
- return {
1499
- cliCleanup: true,
1500
- run: ({ section, prompt, skillDir, skilldDir, timeout, debug, onProgress }) => spawnCliAndStream({
1501
- adapter,
1502
- cliModel: cliConfig.model,
1503
- prompt,
1504
- skillDir,
1505
- skilldDir,
1506
- symlinkDirs: getSkillReferenceDirs(skillDir),
1507
- timeout,
1508
- debug,
1509
- section,
1510
- onProgress
1511
- })
1512
- };
1513
- }
1514
- async function piAiExecutor(model) {
1515
- const models = createPiAiModels();
1516
- if (!new Set((await getAvailablePiAiModels(models)).map((m) => m.id)).has(model)) return { error: `Pi model unavailable or not authenticated: ${model}` };
1517
- return {
1518
- cliCleanup: false,
1519
- run: async ({ section, prompt, skillDir, timeout, onProgress }) => {
1520
- const ac = new AbortController();
1521
- const timer = setTimeout(() => ac.abort(), timeout);
1522
- try {
1523
- const result = await optimizeSectionPiAi({
1524
- section,
1525
- prompt,
1526
- skillDir,
1527
- model,
1528
- onProgress,
1529
- signal: ac.signal,
1530
- models
1531
- });
1532
- return {
1533
- text: result.text.trim(),
1534
- usage: result.usage,
1535
- cost: result.cost
1536
- };
1537
- } catch (err) {
1538
- return {
1539
- text: "",
1540
- stderr: err.message,
1541
- exitCode: 1
1542
- };
1543
- } finally {
1544
- clearTimeout(timer);
1545
- }
1546
- }
1547
- };
1548
- }
1549
- async function selectExecutor(model) {
1550
- if (isOllamaModel(model)) return ollamaExecutor(model);
1551
- return isPiAiModel(model) ? piAiExecutor(model) : cliExecutor(model);
1552
- }
1553
- const STATIC_REGEX_1 = /\b429\b/;
1554
- const STATIC_REGEX_2 = /rate.?limit/i;
1555
- const STATIC_REGEX_3 = /exhausted.*capacity/i;
1556
- const STATIC_REGEX_4 = /quota.*reset/i;
1557
- const STATIC_REGEX_5 = /reset\s+after\s+(\d+)s/i;
1558
- async function optimizeSection(opts) {
1559
- const { section, prompt, outputFile, skillDir, executor, onProgress, timeout, debug, preExistingFiles } = opts;
1560
- const skilldDir = skillInternalDir(skillDir);
1561
- const outputPath = join(skilldDir, outputFile);
1562
- prepareSection({
1563
- section,
1564
- prompt,
1565
- outputPath,
1566
- skilldDir
1567
- });
1568
- return finalizeSection({
1569
- section,
1570
- raw: await executor.run({
1571
- section,
1572
- prompt,
1573
- skillDir,
1574
- skilldDir,
1575
- timeout,
1576
- debug,
1577
- onProgress
1578
- }),
1579
- outputFile,
1580
- outputPath,
1581
- skilldDir,
1582
- debug: !!debug,
1583
- cliCleanup: executor.cliCleanup ? { preExistingFiles } : void 0
1584
- });
1585
- }
1586
- async function optimizeDocs(opts) {
1587
- const { packageName, skillDir, model = "sonnet", version, hasGithub, hasReleases, hasChangelog, docFiles, docsType, hasShippedDocs, onProgress, timeout = 18e4, debug, noCache, sections, customPrompt, features, pkgFiles, overheadLines } = opts;
1588
- const cache = createReferenceCache(packageName, version);
1589
- const sectionPrompts = buildAllSectionPrompts({
1590
- packageName,
1591
- skillDir,
1592
- version,
1593
- hasIssues: hasGithub,
1594
- hasDiscussions: hasGithub,
1595
- hasReleases,
1596
- hasChangelog,
1597
- docFiles,
1598
- docsType,
1599
- hasShippedDocs,
1600
- customPrompt,
1601
- features,
1602
- pkgFiles,
1603
- overheadLines,
1604
- sections: sections ?? ["api-changes", "best-practices"]
1605
- });
1606
- if (sectionPrompts.size === 0) return {
1607
- optimized: "",
1608
- wasOptimized: false,
1609
- error: "No valid sections to generate"
1610
- };
1611
- const executorOrError = await selectExecutor(model);
1612
- if ("error" in executorOrError) return {
1613
- optimized: "",
1614
- wasOptimized: false,
1615
- error: executorOrError.error
1616
- };
1617
- const executor = executorOrError;
1618
- const cachedResults = [];
1619
- const uncachedSections = [];
1620
- for (const [section, prompt] of sectionPrompts) {
1621
- if (!noCache) {
1622
- if (version) {
1623
- const outputFile = SECTION_OUTPUT_FILES[section];
1624
- const refCached = cache.readSection(outputFile);
1625
- if (refCached) {
1626
- onProgress?.({
1627
- chunk: `[${section}: cached]`,
1628
- type: "text",
1629
- text: refCached,
1630
- reasoning: "",
1631
- section
1632
- });
1633
- cachedResults.push({
1634
- section,
1635
- content: refCached,
1636
- wasOptimized: true
1637
- });
1638
- continue;
1639
- }
1640
- }
1641
- const cached = getCached(prompt, model, section);
1642
- if (cached) {
1643
- onProgress?.({
1644
- chunk: `[${section}: cached]`,
1645
- type: "text",
1646
- text: cached,
1647
- reasoning: "",
1648
- section
1649
- });
1650
- cachedResults.push({
1651
- section,
1652
- content: cached,
1653
- wasOptimized: true
1654
- });
1655
- continue;
1656
- }
1657
- }
1658
- uncachedSections.push({
1659
- section,
1660
- prompt
1661
- });
1662
- }
1663
- const skilldDir = skillInternalDir(skillDir);
1664
- mkdirSync(skilldDir, { recursive: true });
1665
- for (const entry of readdirSync(skilldDir)) {
1666
- const entryPath = join(skilldDir, entry);
1667
- try {
1668
- if (lstatSync(entryPath).isSymbolicLink() && !existsSync(entryPath)) onProgress?.({
1669
- chunk: `[warn: broken symlink .skilld/${entry}]`,
1670
- type: "reasoning",
1671
- text: "",
1672
- reasoning: ""
1673
- });
1674
- } catch {}
1675
- }
1676
- const preExistingFiles = new Set(readdirSync(skilldDir));
1677
- const STAGGER_MS = 3e3;
1678
- const spawnResults = uncachedSections.length > 0 ? await Promise.allSettled(uncachedSections.map(({ section, prompt }, i) => {
1679
- const outputFile = SECTION_OUTPUT_FILES[section];
1680
- const run = () => optimizeSection({
1681
- section,
1682
- prompt,
1683
- outputFile,
1684
- skillDir,
1685
- executor,
1686
- onProgress,
1687
- timeout,
1688
- debug,
1689
- preExistingFiles
1690
- });
1691
- if (i === 0) return run();
1692
- return setTimeout$1(i * STAGGER_MS).then(run);
1693
- })) : [];
1694
- const allResults = [...cachedResults];
1695
- let totalUsage;
1696
- let totalCost = 0;
1697
- const retryQueue = [];
1698
- for (let i = 0; i < spawnResults.length; i++) {
1699
- const r = spawnResults[i];
1700
- const { section, prompt } = uncachedSections[i];
1701
- if (r.status === "fulfilled" && r.value.wasOptimized) {
1702
- allResults.push(r.value);
1703
- if (r.value.usage) {
1704
- totalUsage = totalUsage ?? {
1705
- input: 0,
1706
- output: 0
1707
- };
1708
- totalUsage.input += r.value.usage.input;
1709
- totalUsage.output += r.value.usage.output;
1710
- }
1711
- if (r.value.cost != null) totalCost += r.value.cost;
1712
- if (!noCache) setCache(prompt, model, section, r.value.content);
1713
- } else retryQueue.push({
1714
- index: i,
1715
- section,
1716
- prompt
1717
- });
1718
- }
1719
- for (const { index, section, prompt } of retryQueue) {
1720
- const rateLimitDelay = parseRateLimitDelay(getRetryError(spawnResults[index]));
1721
- if (rateLimitDelay != null) {
1722
- const waitSec = Math.max(rateLimitDelay, 5);
1723
- onProgress?.({
1724
- chunk: `[${section}] Rate limited, waiting ${waitSec}s...`,
1725
- type: "reasoning",
1726
- text: "",
1727
- reasoning: "",
1728
- section
1729
- });
1730
- await setTimeout$1(waitSec * 1e3);
1731
- } else {
1732
- onProgress?.({
1733
- chunk: `[${section}: retrying...]`,
1734
- type: "reasoning",
1735
- text: "",
1736
- reasoning: "",
1737
- section
1738
- });
1739
- await setTimeout$1(STAGGER_MS);
1740
- }
1741
- const result = await optimizeSection({
1742
- section,
1743
- prompt,
1744
- outputFile: SECTION_OUTPUT_FILES[section],
1745
- skillDir,
1746
- executor,
1747
- onProgress,
1748
- timeout,
1749
- debug,
1750
- preExistingFiles
1751
- }).catch((err) => ({
1752
- section,
1753
- content: "",
1754
- wasOptimized: false,
1755
- error: err.message
1756
- }));
1757
- allResults.push(result);
1758
- if (result.wasOptimized && !noCache) setCache(prompt, model, section, result.content);
1759
- if (result.usage) {
1760
- totalUsage = totalUsage ?? {
1761
- input: 0,
1762
- output: 0
1763
- };
1764
- totalUsage.input += result.usage.input;
1765
- totalUsage.output += result.usage.output;
1766
- }
1767
- if (result.cost != null) totalCost += result.cost;
1768
- }
1769
- if (version) {
1770
- const sectionFiles = allResults.filter((r) => r.wasOptimized && r.content).map((r) => ({
1771
- file: SECTION_OUTPUT_FILES[r.section],
1772
- content: r.content
1773
- }));
1774
- if (sectionFiles.length > 0) cache.writeSections(sectionFiles);
1775
- }
1776
- const mergedParts = [];
1777
- for (const section of SECTION_MERGE_ORDER) {
1778
- const result = allResults.find((r) => r.section === section);
1779
- if (result?.wasOptimized && result.content) mergedParts.push(wrapSection(section, result.content));
1780
- }
1781
- const optimized = mergedParts.join("\n\n");
1782
- const wasOptimized = mergedParts.length > 0;
1783
- const usageResult = totalUsage ? {
1784
- inputTokens: totalUsage.input,
1785
- outputTokens: totalUsage.output,
1786
- totalTokens: totalUsage.input + totalUsage.output
1787
- } : void 0;
1788
- const errors = allResults.filter((r) => r.error).map((r) => `${r.section}: ${r.error}`);
1789
- const warnings = allResults.flatMap((r) => r.warnings ?? []).map((w) => `${w.section}: ${w.warning}`);
1790
- const debugLogsDir = debug && uncachedSections.length > 0 ? skillLogDir(skillDir) : void 0;
1791
- return {
1792
- optimized,
1793
- wasOptimized,
1794
- error: errors.length > 0 ? errors.join("; ") : void 0,
1795
- warnings: warnings.length > 0 ? warnings : void 0,
1796
- finishReason: wasOptimized ? "stop" : "error",
1797
- usage: usageResult,
1798
- cost: totalCost || void 0,
1799
- debugLogsDir
1800
- };
1801
- }
1802
- function isRateLimitError(error) {
1803
- if (!error) return false;
1804
- return STATIC_REGEX_1.test(error) || STATIC_REGEX_2.test(error) || STATIC_REGEX_3.test(error) || STATIC_REGEX_4.test(error);
1805
- }
1806
- function parseRateLimitDelay(error) {
1807
- if (!error || !isRateLimitError(error)) return void 0;
1808
- const match = error.match(STATIC_REGEX_5);
1809
- return match ? Number(match[1]) : 10;
1810
- }
1811
- function getRetryError(result) {
1812
- if (result.status === "rejected") return String(result.reason);
1813
- return result.value.error;
1814
- }
1815
- export { cleanSectionOutput, createToolProgress, detectImportedPackages, getAvailableModels, getModelLabel, getModelName, getOAuthProviderList, loginOAuthProvider, logoutOAuthProvider, optimizeDocs };
1816
-
1817
- //# sourceMappingURL=agent.mjs.map