skilld 1.7.4 → 2.1.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.
Files changed (172) hide show
  1. package/README.md +25 -0
  2. package/dist/_chunks/add.mjs +67 -0
  3. package/dist/_chunks/add.mjs.map +1 -0
  4. package/dist/_chunks/agent-prompt.mjs +88 -0
  5. package/dist/_chunks/agent-prompt.mjs.map +1 -0
  6. package/dist/_chunks/agent.mjs +359 -157
  7. package/dist/_chunks/agent.mjs.map +1 -1
  8. package/dist/_chunks/args.mjs +42 -0
  9. package/dist/_chunks/args.mjs.map +1 -0
  10. package/dist/_chunks/assemble.mjs +12 -9
  11. package/dist/_chunks/assemble.mjs.map +1 -1
  12. package/dist/_chunks/author.mjs +35 -19
  13. package/dist/_chunks/author.mjs.map +1 -1
  14. package/dist/_chunks/cache.mjs +153 -185
  15. package/dist/_chunks/cache.mjs.map +1 -1
  16. package/dist/_chunks/cache2.mjs +9 -8
  17. package/dist/_chunks/cache2.mjs.map +1 -1
  18. package/dist/_chunks/client.mjs +118 -0
  19. package/dist/_chunks/client.mjs.map +1 -0
  20. package/dist/_chunks/core.mjs +5 -5
  21. package/dist/_chunks/detect.mjs +54 -44
  22. package/dist/_chunks/detect.mjs.map +1 -1
  23. package/dist/_chunks/detect2.mjs +1 -1
  24. package/dist/_chunks/eject.mjs +69 -0
  25. package/dist/_chunks/eject.mjs.map +1 -0
  26. package/dist/_chunks/embedding-cache.mjs +1 -1
  27. package/dist/_chunks/embedding-cache2.mjs +2 -2
  28. package/dist/_chunks/embedding-cache2.mjs.map +1 -1
  29. package/dist/_chunks/env.mjs +19 -0
  30. package/dist/_chunks/env.mjs.map +1 -0
  31. package/dist/_chunks/install-many.mjs +377 -0
  32. package/dist/_chunks/install-many.mjs.map +1 -0
  33. package/dist/_chunks/install.mjs +93 -334
  34. package/dist/_chunks/install.mjs.map +1 -1
  35. package/dist/_chunks/intro.mjs +63 -0
  36. package/dist/_chunks/intro.mjs.map +1 -0
  37. package/dist/_chunks/list.mjs +5 -4
  38. package/dist/_chunks/list.mjs.map +1 -1
  39. package/dist/_chunks/lockfile.mjs +10 -7
  40. package/dist/_chunks/lockfile.mjs.map +1 -1
  41. package/dist/_chunks/login.mjs +234 -0
  42. package/dist/_chunks/login.mjs.map +1 -0
  43. package/dist/_chunks/logout.mjs +27 -0
  44. package/dist/_chunks/logout.mjs.map +1 -0
  45. package/dist/_chunks/map.mjs +11 -0
  46. package/dist/_chunks/map.mjs.map +1 -0
  47. package/dist/_chunks/markdown.mjs +81 -56
  48. package/dist/_chunks/markdown.mjs.map +1 -1
  49. package/dist/_chunks/menu.mjs +33 -0
  50. package/dist/_chunks/menu.mjs.map +1 -0
  51. package/dist/_chunks/model-picker.mjs +61 -0
  52. package/dist/_chunks/model-picker.mjs.map +1 -0
  53. package/dist/_chunks/monorepo.mjs +7 -4
  54. package/dist/_chunks/monorepo.mjs.map +1 -1
  55. package/dist/_chunks/package-json.mjs +7 -5
  56. package/dist/_chunks/package-json.mjs.map +1 -1
  57. package/dist/_chunks/paths.mjs +3 -5
  58. package/dist/_chunks/paths.mjs.map +1 -1
  59. package/dist/_chunks/{sync-pipeline.mjs → pipeline.mjs} +360 -323
  60. package/dist/_chunks/pipeline.mjs.map +1 -0
  61. package/dist/_chunks/pool.mjs +1 -1
  62. package/dist/_chunks/pool2.mjs +2 -2
  63. package/dist/_chunks/pool2.mjs.map +1 -1
  64. package/dist/_chunks/portable.mjs +151 -0
  65. package/dist/_chunks/portable.mjs.map +1 -0
  66. package/dist/_chunks/prepare-hook.mjs +2 -0
  67. package/dist/_chunks/prepare-hook2.mjs +61 -0
  68. package/dist/_chunks/prepare-hook2.mjs.map +1 -0
  69. package/dist/_chunks/prepare.mjs +58 -8
  70. package/dist/_chunks/prepare.mjs.map +1 -1
  71. package/dist/_chunks/prepare2.mjs +14 -11
  72. package/dist/_chunks/prepare2.mjs.map +1 -1
  73. package/dist/_chunks/prompts.mjs +488 -76
  74. package/dist/_chunks/prompts.mjs.map +1 -1
  75. package/dist/_chunks/pull.mjs +220 -0
  76. package/dist/_chunks/pull.mjs.map +1 -0
  77. package/dist/_chunks/regex.mjs +19 -0
  78. package/dist/_chunks/regex.mjs.map +1 -0
  79. package/dist/_chunks/retriv.mjs +2 -171
  80. package/dist/_chunks/retriv2.mjs +159 -0
  81. package/dist/_chunks/retriv2.mjs.map +1 -0
  82. package/dist/_chunks/sanitize.mjs +13 -10
  83. package/dist/_chunks/sanitize.mjs.map +1 -1
  84. package/dist/_chunks/search-helpers.mjs +11 -9
  85. package/dist/_chunks/search-helpers.mjs.map +1 -1
  86. package/dist/_chunks/search-interactive.mjs +25 -22
  87. package/dist/_chunks/search-interactive.mjs.map +1 -1
  88. package/dist/_chunks/search.mjs +6 -6
  89. package/dist/_chunks/search.mjs.map +1 -1
  90. package/dist/_chunks/semver.mjs +2793 -5
  91. package/dist/_chunks/semver.mjs.map +1 -1
  92. package/dist/_chunks/skill-installer.mjs +1 -1
  93. package/dist/_chunks/skill-installer2.mjs +31 -23
  94. package/dist/_chunks/skill-installer2.mjs.map +1 -1
  95. package/dist/_chunks/skills.mjs +9 -10
  96. package/dist/_chunks/skills.mjs.map +1 -1
  97. package/dist/_chunks/store.mjs +107 -0
  98. package/dist/_chunks/store.mjs.map +1 -0
  99. package/dist/_chunks/sync.mjs +422 -915
  100. package/dist/_chunks/sync.mjs.map +1 -1
  101. package/dist/_chunks/sync2.mjs +2 -5
  102. package/dist/_chunks/telemetry.mjs +26 -0
  103. package/dist/_chunks/telemetry.mjs.map +1 -0
  104. package/dist/_chunks/uninstall.mjs +38 -32
  105. package/dist/_chunks/uninstall.mjs.map +1 -1
  106. package/dist/_chunks/update.mjs +172 -0
  107. package/dist/_chunks/update.mjs.map +1 -0
  108. package/dist/_chunks/upload.mjs +16 -13
  109. package/dist/_chunks/upload.mjs.map +1 -1
  110. package/dist/_chunks/validate.mjs +1 -1
  111. package/dist/_chunks/validate.mjs.map +1 -1
  112. package/dist/_chunks/version.mjs +16 -17
  113. package/dist/_chunks/version.mjs.map +1 -1
  114. package/dist/_chunks/whoami.mjs +21 -0
  115. package/dist/_chunks/whoami.mjs.map +1 -0
  116. package/dist/_chunks/wizard.mjs +2 -190
  117. package/dist/_chunks/wizard2.mjs +200 -0
  118. package/dist/_chunks/wizard2.mjs.map +1 -0
  119. package/dist/_chunks/yaml.mjs +1 -1
  120. package/dist/_chunks/yaml.mjs.map +1 -1
  121. package/dist/cli-entry.d.mts +1 -1
  122. package/dist/cli.d.mts +1 -1
  123. package/dist/cli.mjs +94 -71
  124. package/dist/cli.mjs.map +1 -1
  125. package/dist/prepare.d.mts +1 -1
  126. package/dist/prepare.mjs +9 -6
  127. package/dist/prepare.mjs.map +1 -1
  128. package/dist/retriv/worker.d.mts +5 -1
  129. package/dist/retriv/worker.d.mts.map +1 -1
  130. package/dist/retriv/worker.mjs +1 -1
  131. package/dist/retriv/worker.mjs.map +1 -1
  132. package/package.json +27 -37
  133. package/dist/_chunks/author-group.mjs +0 -17
  134. package/dist/_chunks/author-group.mjs.map +0 -1
  135. package/dist/_chunks/cli-helpers.mjs +0 -335
  136. package/dist/_chunks/cli-helpers.mjs.map +0 -1
  137. package/dist/_chunks/cli-helpers2.mjs +0 -2
  138. package/dist/_chunks/index.d.mts +0 -344
  139. package/dist/_chunks/index.d.mts.map +0 -1
  140. package/dist/_chunks/index2.d.mts +0 -279
  141. package/dist/_chunks/index2.d.mts.map +0 -1
  142. package/dist/_chunks/index3.d.mts +0 -44
  143. package/dist/_chunks/index3.d.mts.map +0 -1
  144. package/dist/_chunks/index4.d.mts +0 -553
  145. package/dist/_chunks/index4.d.mts.map +0 -1
  146. package/dist/_chunks/package-registry.mjs +0 -465
  147. package/dist/_chunks/package-registry.mjs.map +0 -1
  148. package/dist/_chunks/retriv.mjs.map +0 -1
  149. package/dist/_chunks/setup.mjs +0 -17
  150. package/dist/_chunks/setup.mjs.map +0 -1
  151. package/dist/_chunks/sources.mjs +0 -2654
  152. package/dist/_chunks/sources.mjs.map +0 -1
  153. package/dist/_chunks/sync-pipeline.mjs.map +0 -1
  154. package/dist/_chunks/sync-registry.mjs +0 -65
  155. package/dist/_chunks/sync-registry.mjs.map +0 -1
  156. package/dist/_chunks/types.d.mts +0 -76
  157. package/dist/_chunks/types.d.mts.map +0 -1
  158. package/dist/_chunks/types2.d.mts +0 -88
  159. package/dist/_chunks/types2.d.mts.map +0 -1
  160. package/dist/_chunks/wizard.mjs.map +0 -1
  161. package/dist/agent/index.d.mts +0 -2
  162. package/dist/agent/index.mjs +0 -4
  163. package/dist/cache/index.d.mts +0 -2
  164. package/dist/cache/index.mjs +0 -5
  165. package/dist/index.d.mts +0 -6
  166. package/dist/index.mjs +0 -6
  167. package/dist/retriv/index.d.mts +0 -3
  168. package/dist/retriv/index.mjs +0 -2
  169. package/dist/sources/index.d.mts +0 -3
  170. package/dist/sources/index.mjs +0 -3
  171. package/dist/types.d.mts +0 -4
  172. package/dist/types.mjs +0 -1
@@ -1,28 +1,29 @@
1
- import { a as PI_AI_AUTH_PATH, h as skillLogDir, p as skillInternalDir, r as LLM_CACHE_DIR, t as CACHE_DIR } from "./paths.mjs";
2
- import { E as getSkillReferenceDirs, t as createReferenceCache } from "./cache.mjs";
3
- import { n as sanitizeMarkdown } from "./sanitize.mjs";
4
- import { a as targets, t as detectInstalledAgents } from "./detect.mjs";
5
- import { E as SECTION_OUTPUT_FILES, S as getSectionValidator, T as SECTION_MERGE_ORDER, k as resolveSkilldCommand, w as wrapSection, y as buildAllSectionPrompts } from "./prompts.mjs";
1
+ import { detectInstalledAgents, targets } from "./detect.mjs";
2
+ import { SECTION_MERGE_ORDER, SECTION_OUTPUT_FILES, buildAllSectionPrompts, getSectionValidator, resolveSkilldCommand, wrapSection } from "./prompts.mjs";
3
+ import { CACHE_DIR, LLM_CACHE_DIR, PI_AI_AUTH_PATH, skillInternalDir, skillLogDir } from "./paths.mjs";
4
+ import { API_CHANGE_BULLET_RE, SECTION_HEADING_RE, SOURCE_LINK_RE, TRAILING_SLASH_RE as TRAILING_SLASH_RE$1 } from "./regex.mjs";
5
+ import { sanitizeMarkdown } from "./sanitize.mjs";
6
+ import { createReferenceCache, getSkillReferenceDirs } from "./cache.mjs";
6
7
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
7
- import { homedir } from "node:os";
8
+ import { promisify, styleText } from "node:util";
8
9
  import { join } from "pathe";
9
10
  import { exec, execFileSync, spawn } from "node:child_process";
10
- import { glob } from "tinyglobby";
11
- import { findDynamicImports, findStaticImports } from "mlly";
12
- import { promisify } from "node:util";
13
11
  import { isWindows } from "std-env";
14
- import { getEnvApiKey, getEnvApiKey as getEnvApiKey$1, getModel, getModels, getProviders, streamSimple } from "@mariozechner/pi-ai";
15
- import { getOAuthApiKey, getOAuthProvider, getOAuthProviders } from "@mariozechner/pi-ai/oauth";
12
+ import { homedir } from "node:os";
13
+ import { builtinModels, builtinProviders, getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
16
14
  import { resolve as resolve$1 } from "node:path";
17
15
  import { Type } from "typebox";
18
- import { readFile } from "node:fs/promises";
16
+ import { glob, readFile } from "node:fs/promises";
19
17
  import { parseSync } from "oxc-parser";
20
18
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
21
19
  import { createHash } from "node:crypto";
20
+ const STATIC_REGEX_1$6 = /-\d{8}$/;
21
+ const STATIC_REGEX_2$5 = /-\d{4}-\d{2}-\d{2}$/;
22
+ const STATIC_REGEX_3$3 = /-preview/;
22
23
  function isStableId(id) {
23
- if (/-\d{8}$/.test(id)) return false;
24
- if (/-\d{4}-\d{2}-\d{2}$/.test(id)) return false;
25
- if (/-preview/.test(id)) return false;
24
+ if (STATIC_REGEX_1$6.test(id)) return false;
25
+ if (STATIC_REGEX_2$5.test(id)) return false;
26
+ if (STATIC_REGEX_3$3.test(id)) return false;
26
27
  return true;
27
28
  }
28
29
  function compareVersions(a, b) {
@@ -40,7 +41,7 @@ function compareVersions(a, b) {
40
41
  }
41
42
  function resolve$2(opts) {
42
43
  const { provider, prefix, contains, exclude } = opts;
43
- return getModels(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];
44
+ 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];
44
45
  }
45
46
  function buildModelEntry(opts) {
46
47
  const found = resolve$2(opts);
@@ -120,7 +121,9 @@ function extractToolHint(input) {
120
121
  if (typeof v === "string" && v) return v;
121
122
  }
122
123
  }
123
- const stripClaude = (n) => n.replace(/^Claude\s+/, "").replace(/\s*\(latest\)\s*$/i, "");
124
+ const STATIC_REGEX_1$5 = /^Claude\s+/;
125
+ const STATIC_REGEX_2$4 = /\s*\(latest\)\s*$/i;
126
+ const stripClaude = (n) => n.replace(STATIC_REGEX_1$5, "").replace(STATIC_REGEX_2$4, "");
124
127
  function buildArgs$2(model, skillDir, symlinkDirs) {
125
128
  return [
126
129
  "-p",
@@ -218,6 +221,7 @@ const adapter$2 = {
218
221
  buildArgs: buildArgs$2,
219
222
  parseEvent: parseEvent$2
220
223
  };
224
+ const STATIC_REGEX_1$4 = /^cat\s*>|>/;
221
225
  function buildArgs$1(model, _skillDir, _symlinkDirs) {
222
226
  return [
223
227
  "exec",
@@ -240,7 +244,7 @@ function parseEvent$1(line) {
240
244
  };
241
245
  if (item.type === "command_execution" && item.aggregated_output) {
242
246
  const cmd = item.command || "";
243
- const writeContent = /^cat\s*>|>/.test(cmd) ? item.aggregated_output : void 0;
247
+ const writeContent = STATIC_REGEX_1$4.test(cmd) ? item.aggregated_output : void 0;
244
248
  return {
245
249
  kind: "tool-call",
246
250
  tool: "Bash",
@@ -382,32 +386,181 @@ const adapter = {
382
386
  buildArgs,
383
387
  parseEvent
384
388
  };
385
- const BLOCKED_OAUTH_PROVIDERS = new Set([
386
- "google-antigravity",
387
- "google-gemini-cli",
389
+ const OLLAMA_PREFIX = "ollama:";
390
+ function isOllamaModel(model) {
391
+ return model.startsWith(OLLAMA_PREFIX);
392
+ }
393
+ function parseOllamaModelId(model) {
394
+ return isOllamaModel(model) ? model.slice(7) : null;
395
+ }
396
+ const HAS_SCHEME_RE = /^https?:\/\//;
397
+ const TRAILING_SLASH_RE = /\/$/;
398
+ function ollamaHost() {
399
+ const raw = process.env.OLLAMA_HOST || "http://localhost:11434";
400
+ return (HAS_SCHEME_RE.test(raw) ? raw : `http://${raw}`).replace(TRAILING_SLASH_RE, "");
401
+ }
402
+ async function isCompletionModel(name) {
403
+ const res = await fetch(`${ollamaHost()}/api/show`, {
404
+ method: "POST",
405
+ headers: { "content-type": "application/json" },
406
+ body: JSON.stringify({ model: name }),
407
+ signal: AbortSignal.timeout(1500)
408
+ }).catch(() => null);
409
+ if (!res?.ok) return true;
410
+ const caps = (await res.json().catch(() => null))?.capabilities;
411
+ return !caps?.length || caps.includes("completion") || caps.includes("insert");
412
+ }
413
+ async function getAvailableOllamaModels() {
414
+ const res = await fetch(`${ollamaHost()}/api/tags`, { signal: AbortSignal.timeout(1500) }).catch(() => null);
415
+ if (!res?.ok) return [];
416
+ const data = await res.json().catch(() => null);
417
+ if (!data?.models?.length) return [];
418
+ return (await Promise.all(data.models.map(async (m) => {
419
+ if (!await isCompletionModel(m.name)) return null;
420
+ const params = m.details?.parameter_size;
421
+ const quant = m.details?.quantization_level;
422
+ const sizeGb = m.size ? `${(m.size / 1e9).toFixed(1)}GB` : void 0;
423
+ const detail = params ? `${params}${quant ? ` ${quant}` : ""}` : sizeGb;
424
+ return {
425
+ id: `ollama:${m.name}`,
426
+ name: m.name,
427
+ hint: detail ? `local · ${detail}` : "local"
428
+ };
429
+ }))).filter((m) => m !== null);
430
+ }
431
+ function ollamaExecutor(model) {
432
+ const modelId = parseOllamaModelId(model);
433
+ if (!modelId) return { error: `Not an Ollama model: ${model}` };
434
+ return {
435
+ cliCleanup: false,
436
+ run: async ({ section, prompt, timeout, onProgress }) => {
437
+ const ac = new AbortController();
438
+ const timer = setTimeout(() => ac.abort(), timeout);
439
+ onProgress?.({
440
+ chunk: "[ollama]",
441
+ type: "reasoning",
442
+ text: "",
443
+ reasoning: "Generating locally…",
444
+ section
445
+ });
446
+ const res = await fetch(`${ollamaHost()}/api/chat`, {
447
+ method: "POST",
448
+ headers: { "content-type": "application/json" },
449
+ body: JSON.stringify({
450
+ model: modelId,
451
+ messages: [{
452
+ role: "user",
453
+ content: prompt
454
+ }],
455
+ stream: true,
456
+ options: {
457
+ temperature: .2,
458
+ num_ctx: Number(process.env.OLLAMA_NUM_CTX) || 32768
459
+ }
460
+ }),
461
+ signal: ac.signal
462
+ }).catch((err) => ({
463
+ ok: false,
464
+ statusText: err.message,
465
+ body: null
466
+ }));
467
+ if (!res.ok || !res.body) {
468
+ clearTimeout(timer);
469
+ return {
470
+ text: "",
471
+ stderr: `Ollama request failed: ${res.statusText}. Is \`ollama serve\` running at ${ollamaHost()}?`,
472
+ exitCode: 1
473
+ };
474
+ }
475
+ let text = "";
476
+ let usage;
477
+ const drain = async () => {
478
+ const reader = res.body.getReader();
479
+ const decoder = new TextDecoder();
480
+ let buffer = "";
481
+ for (;;) {
482
+ const { done, value } = await reader.read();
483
+ if (done) break;
484
+ buffer += decoder.decode(value, { stream: true });
485
+ const lines = buffer.split("\n");
486
+ buffer = lines.pop() || "";
487
+ for (const line of lines) {
488
+ if (!line.trim()) continue;
489
+ const chunk = JSON.parse(line);
490
+ if (chunk.error) throw new Error(chunk.error);
491
+ const delta = chunk.message?.content;
492
+ if (delta) {
493
+ text += delta;
494
+ onProgress?.({
495
+ chunk: delta,
496
+ type: "text",
497
+ text,
498
+ reasoning: "",
499
+ section
500
+ });
501
+ }
502
+ if (chunk.done) usage = {
503
+ input: chunk.prompt_eval_count ?? 0,
504
+ output: chunk.eval_count ?? 0
505
+ };
506
+ }
507
+ }
508
+ };
509
+ const streamError = await drain().then(() => void 0).catch((err) => err.message);
510
+ clearTimeout(timer);
511
+ if (streamError) return {
512
+ text: "",
513
+ stderr: `Ollama stream error: ${streamError}`,
514
+ exitCode: 1
515
+ };
516
+ if (!text.trim()) return {
517
+ text: "",
518
+ stderr: "Ollama returned no content",
519
+ exitCode: 1
520
+ };
521
+ return {
522
+ text: text.trim(),
523
+ usage,
524
+ cost: 0
525
+ };
526
+ }
527
+ };
528
+ }
529
+ const BLOCKED_OAUTH_PROVIDERS = /* @__PURE__ */ new Set([
388
530
  "github-copilot",
389
531
  "anthropic",
390
532
  "openai-codex"
391
533
  ]);
392
534
  const PI_AGENT_AUTH_PATH = join(process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"), "auth.json");
393
535
  const SKILLD_AUTH_PATH = PI_AI_AUTH_PATH;
394
- const OAUTH_PROVIDER_OVERRIDES = {
395
- google: "google-gemini-cli",
396
- openai: "openai-codex"
397
- };
536
+ function isObjectRecord(value) {
537
+ return typeof value === "object" && value !== null && !Array.isArray(value);
538
+ }
539
+ function isStringRecord(value) {
540
+ return isObjectRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
541
+ }
542
+ function isCredential(value) {
543
+ if (!isObjectRecord(value) || !("type" in value)) return false;
544
+ 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";
545
+ if (value.type !== "api_key") return false;
546
+ return (!("key" in value) || value.key === void 0 || typeof value.key === "string") && (!("env" in value) || value.env === void 0 || isStringRecord(value.env));
547
+ }
398
548
  function readAuthFile(path) {
399
549
  if (!existsSync(path)) return {};
400
550
  try {
401
- return JSON.parse(readFileSync(path, "utf-8"));
551
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
552
+ if (!isObjectRecord(parsed)) return {};
553
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => isCredential(entry[1])));
402
554
  } catch {
403
555
  return {};
404
556
  }
405
557
  }
406
558
  function loadAuth() {
407
559
  const piAuth = readAuthFile(PI_AGENT_AUTH_PATH);
560
+ const skilldAuth = readAuthFile(SKILLD_AUTH_PATH);
408
561
  return {
409
- ...readAuthFile(SKILLD_AUTH_PATH),
410
- ...piAuth
562
+ ...piAuth,
563
+ ...skilldAuth
411
564
  };
412
565
  }
413
566
  function saveAuth(auth) {
@@ -417,58 +570,79 @@ function saveAuth(auth) {
417
570
  });
418
571
  writeFileSync(SKILLD_AUTH_PATH, JSON.stringify(auth, null, 2), { mode: 384 });
419
572
  }
420
- function resolveOAuthProviderId(modelProvider) {
421
- const oauthId = OAUTH_PROVIDER_OVERRIDES[modelProvider] ?? modelProvider;
422
- if (BLOCKED_OAUTH_PROVIDERS.has(oauthId)) return null;
423
- if (OAUTH_PROVIDER_OVERRIDES[modelProvider]) return OAUTH_PROVIDER_OVERRIDES[modelProvider];
424
- if (new Set(getOAuthProviders().map((p) => p.id)).has(modelProvider)) return modelProvider;
425
- return null;
426
- }
427
- async function resolveApiKey(provider) {
428
- const envKey = getEnvApiKey$1(provider);
429
- if (envKey) return envKey;
430
- const oauthProviderId = resolveOAuthProviderId(provider);
431
- if (!oauthProviderId) return null;
432
- const auth = loadAuth();
433
- if (!auth[oauthProviderId]) return null;
434
- const result = await getOAuthApiKey(oauthProviderId, auth);
435
- if (!result) return null;
436
- const skilldAuth = readAuthFile(SKILLD_AUTH_PATH);
437
- skilldAuth[oauthProviderId] = {
438
- type: "oauth",
439
- ...result.newCredentials
573
+ function createCredentialStore() {
574
+ const chains = /* @__PURE__ */ new Map();
575
+ return {
576
+ async read(providerId) {
577
+ return loadAuth()[providerId];
578
+ },
579
+ async list() {
580
+ return Object.entries(loadAuth()).map(([providerId, credential]) => ({
581
+ providerId,
582
+ type: credential.type
583
+ }));
584
+ },
585
+ async modify(providerId, update) {
586
+ let result;
587
+ const operation = (chains.get(providerId) ?? Promise.resolve()).then(async () => {
588
+ const current = loadAuth()[providerId];
589
+ const next = await update(current);
590
+ result = next ?? current;
591
+ if (next) {
592
+ const localAuth = readAuthFile(SKILLD_AUTH_PATH);
593
+ localAuth[providerId] = next;
594
+ saveAuth(localAuth);
595
+ }
596
+ });
597
+ chains.set(providerId, operation.then(() => void 0, () => void 0));
598
+ await operation;
599
+ return result;
600
+ },
601
+ async delete(providerId) {
602
+ const localAuth = readAuthFile(SKILLD_AUTH_PATH);
603
+ delete localAuth[providerId];
604
+ saveAuth(localAuth);
605
+ }
440
606
  };
441
- saveAuth(skilldAuth);
442
- return result.apiKey;
607
+ }
608
+ function createPiAiModels() {
609
+ return builtinModels({ credentials: createCredentialStore() });
443
610
  }
444
611
  function getOAuthProviderList() {
445
612
  const auth = loadAuth();
446
- return getOAuthProviders().filter((p) => !BLOCKED_OAUTH_PROVIDERS.has(p.id)).map((p) => ({
447
- id: p.id,
448
- name: p.name ?? p.id,
449
- loggedIn: !!auth[p.id]
613
+ return builtinProviders().filter((provider) => provider.auth.oauth && !BLOCKED_OAUTH_PROVIDERS.has(provider.id)).map((provider) => ({
614
+ id: provider.id,
615
+ name: provider.auth.oauth?.name ?? provider.name,
616
+ loggedIn: auth[provider.id]?.type === "oauth"
450
617
  }));
451
618
  }
452
619
  async function loginOAuthProvider(providerId, callbacks) {
453
- const provider = getOAuthProvider(providerId);
454
- if (!provider) return false;
455
- const credentials = await provider.login({
456
- onAuth: (info) => callbacks.onAuth(info.url, info.instructions),
457
- onPrompt: async (prompt) => callbacks.onPrompt(prompt.message, prompt.placeholder),
458
- onProgress: (msg) => callbacks.onProgress?.(msg)
459
- });
460
- const auth = loadAuth();
461
- auth[providerId] = {
462
- type: "oauth",
463
- ...credentials
620
+ const models = createPiAiModels();
621
+ if (!models.getProvider(providerId)?.auth.oauth || BLOCKED_OAUTH_PROVIDERS.has(providerId)) return false;
622
+ const notify = (event) => {
623
+ if (event.type === "auth_url") callbacks.onAuth(event.url, event.instructions);
624
+ else if (event.type === "device_code") {
625
+ if (callbacks.onDeviceCode) callbacks.onDeviceCode(event.userCode, event.verificationUri);
626
+ else callbacks.onAuth(event.verificationUri, `Enter code ${event.userCode}`);
627
+ } else callbacks.onProgress?.(event.message);
628
+ };
629
+ const prompt = async (input) => {
630
+ if (input.type !== "select") return callbacks.onPrompt(input.message, input.placeholder);
631
+ const options = input.options.map((option) => ({
632
+ id: option.id,
633
+ label: option.label
634
+ }));
635
+ return await callbacks.onSelect?.(input.message, options) ?? options[0]?.id ?? "";
464
636
  };
465
- saveAuth(auth);
637
+ const interaction = {
638
+ notify,
639
+ prompt
640
+ };
641
+ await models.login(providerId, "oauth", interaction);
466
642
  return true;
467
643
  }
468
- function logoutOAuthProvider(providerId) {
469
- const auth = loadAuth();
470
- delete auth[providerId];
471
- saveAuth(auth);
644
+ async function logoutOAuthProvider(providerId) {
645
+ await createPiAiModels().logout(providerId);
472
646
  }
473
647
  function isPiAiModel(model) {
474
648
  return model.startsWith("pi:");
@@ -505,47 +679,36 @@ const RECOMMENDED_MODELS = {
505
679
  google: /flash/,
506
680
  openai: /gpt-4\.1-mini/
507
681
  };
508
- function getAvailablePiAiModels() {
509
- const providers = getProviders();
510
- const auth = loadAuth();
682
+ async function getAvailablePiAiModels(models = createPiAiModels()) {
683
+ const modelsByProvider = Map.groupBy(await models.getAvailable(), (model) => model.provider);
511
684
  const available = [];
512
- const recommendedPicked = /* @__PURE__ */ new Set();
513
- for (const provider of providers) {
514
- let authSource = "none";
515
- if (getEnvApiKey(provider)) authSource = "env";
516
- else {
517
- const oauthId = resolveOAuthProviderId(provider);
518
- if (oauthId && auth[oauthId]) authSource = "oauth";
519
- }
520
- if (authSource === "none") continue;
521
- const models = getModels(provider);
685
+ for (const [provider, providerModels] of modelsByProvider) {
686
+ const auth = await models.checkAuth(provider);
687
+ if (!auth) continue;
688
+ const authSource = auth.type === "oauth" ? "oauth" : "api-key";
522
689
  const recPattern = RECOMMENDED_MODELS[provider];
523
- let recModelId = null;
524
- if (recPattern) {
525
- for (const model of models) if (!isLegacyModel(model.id) && recPattern.test(model.id)) {
526
- recModelId = model.id;
527
- break;
528
- }
529
- }
530
- for (const model of models) {
690
+ const recModelId = recPattern ? providerModels.find((model) => !isLegacyModel(model.id) && recPattern.test(model.id))?.id : void 0;
691
+ for (const model of providerModels) {
531
692
  if (model.contextWindow && model.contextWindow < MIN_CONTEXT_WINDOW) continue;
532
693
  if (isLegacyModel(model.id)) continue;
533
694
  const id = `pi:${provider}/${model.id}`;
534
695
  const ctx = model.contextWindow ? ` · ${Math.round(model.contextWindow / 1e3)}k ctx` : "";
535
696
  const cost = model.cost?.input ? ` · $${model.cost.input}/Mtok` : "";
536
- const isRecommended = model.id === recModelId && !recommendedPicked.has(provider);
537
- if (isRecommended) recommendedPicked.add(provider);
538
697
  available.push({
539
698
  id,
540
699
  name: model.name || model.id,
541
700
  hint: `${authSource === "oauth" ? "OAuth" : "API key"}${ctx}${cost}`,
542
701
  authSource,
543
- recommended: isRecommended
702
+ recommended: model.id === recModelId
544
703
  });
545
704
  }
546
705
  }
547
706
  return available;
548
707
  }
708
+ const STATIC_REGEX_1$3 = /^\.\/\.skilld\//;
709
+ const STATIC_REGEX_2$3 = /^\.skilld\//;
710
+ const STATIC_REGEX_3$2 = /^\.\//;
711
+ const STATIC_REGEX_5$2 = /\s+/;
549
712
  const TOOLS = [
550
713
  {
551
714
  name: "Read",
@@ -574,7 +737,7 @@ const TOOLS = [
574
737
  parameters: Type.Object({ command: Type.String({ description: "Shell command to run" }) })
575
738
  }
576
739
  ];
577
- const SAFE_COMMANDS = new Set([
740
+ const SAFE_COMMANDS = /* @__PURE__ */ new Set([
578
741
  "skilld",
579
742
  "ls",
580
743
  "cat",
@@ -582,7 +745,8 @@ const SAFE_COMMANDS = new Set([
582
745
  ]);
583
746
  const SHELL_META_RE = /[;&|`$()<>]/;
584
747
  function resolveSandboxedPath(p, skilldDir) {
585
- const resolved = resolve$1(skilldDir, String(p).replace(/^\.\/\.skilld\//, "./").replace(/^\.skilld\//, "./").replace(/^\.\//, ""));
748
+ const cleaned = String(p).replace(STATIC_REGEX_1$3, "./").replace(STATIC_REGEX_2$3, "./").replace(STATIC_REGEX_3$2, "");
749
+ const resolved = resolve$1(skilldDir, cleaned);
586
750
  if (!resolved.startsWith(`${skilldDir}/`) && resolved !== skilldDir) throw new Error(`Path traversal blocked: ${p}`);
587
751
  return resolved;
588
752
  }
@@ -638,7 +802,7 @@ function executeTool(toolCall, skilldDir) {
638
802
  return sanitizeMarkdown(readFileSync(filePath, "utf-8"));
639
803
  }
640
804
  case "Glob": {
641
- const pattern = String(args.pattern).replace(/^\.\/\.skilld\//, "./").replace(/^\.skilld\//, "./").replace(/^\.\//, "");
805
+ const pattern = String(args.pattern).replace(STATIC_REGEX_1$3, "./").replace(STATIC_REGEX_2$3, "./").replace(STATIC_REGEX_3$2, "");
642
806
  const results = [];
643
807
  const walkDir = (dir, prefix) => {
644
808
  if (!existsSync(dir)) return;
@@ -648,17 +812,19 @@ function executeTool(toolCall, skilldDir) {
648
812
  else results.push(`./.skilld/${relPath}`);
649
813
  }
650
814
  };
651
- const baseDir = pattern.split("*")[0]?.replace(/\/$/, "") ?? "";
815
+ const baseDir = pattern.split("*")[0]?.replace(TRAILING_SLASH_RE$1, "") ?? "";
652
816
  walkDir(join(skilldDir, baseDir), baseDir);
653
- const matched = results.filter((r) => globMatch(r.replace(/^\.\/\.skilld\//, ""), pattern));
817
+ const matched = results.filter((r) => globMatch(r.replace(STATIC_REGEX_1$3, ""), pattern));
654
818
  return matched.length > 0 ? matched.join("\n") : `No files matching: ${args.pattern}`;
655
819
  }
656
- case "Write":
657
- writeFileSync(resolveSandboxedPath(args.path, skilldDir), sanitizeMarkdown(String(args.content)));
820
+ case "Write": {
821
+ const filePath = resolveSandboxedPath(args.path, skilldDir);
822
+ writeFileSync(filePath, sanitizeMarkdown(String(args.content)));
658
823
  return "File written successfully.";
824
+ }
659
825
  case "Bash": {
660
826
  const cmd = String(args.command).trim();
661
- const parts = cmd.split(/\s+/);
827
+ const parts = cmd.split(STATIC_REGEX_5$2);
662
828
  const bin = parts[0] ?? "";
663
829
  if (!SAFE_COMMANDS.has(bin) || SHELL_META_RE.test(cmd)) return `Error: command not allowed. Only skilld, ls, cat, find commands are permitted.`;
664
830
  try {
@@ -666,7 +832,7 @@ function executeTool(toolCall, skilldDir) {
666
832
  cwd: skilldDir,
667
833
  timeout: 15e3,
668
834
  encoding: "utf-8",
669
- maxBuffer: 512 * 1024
835
+ maxBuffer: 524288
670
836
  }).trim();
671
837
  } catch (err) {
672
838
  return `Error: ${err.message}`;
@@ -679,8 +845,9 @@ const SYSTEM_PROMPT = "You are a technical documentation expert generating SKILL
679
845
  async function optimizeSectionPiAi(opts) {
680
846
  const parsed = parsePiAiModelId(opts.model);
681
847
  if (!parsed) throw new Error(`Invalid pi-ai model ID: ${opts.model}. Expected format: pi:provider/model-id`);
682
- const model = getModel(parsed.provider, parsed.modelId);
683
- const apiKey = await resolveApiKey(parsed.provider);
848
+ const models = opts.models ?? createPiAiModels();
849
+ const model = models.getModel(parsed.provider, parsed.modelId);
850
+ if (!model) throw new Error(`Unknown pi-ai model: ${parsed.provider}/${parsed.modelId}`);
684
851
  const skilldDir = skillInternalDir(opts.skillDir);
685
852
  const fullPrompt = opts.prompt;
686
853
  opts.onProgress?.({
@@ -705,14 +872,14 @@ async function optimizeSectionPiAi(opts) {
705
872
  let lastWriteContent = "";
706
873
  for (let turn = 0; turn < 30; turn++) {
707
874
  if (opts.signal?.aborted) throw new Error("pi-ai request timed out");
708
- const eventStream = streamSimple(model, {
875
+ const eventStream = models.streamSimple(model, {
709
876
  systemPrompt: SYSTEM_PROMPT,
710
877
  messages,
711
878
  tools: TOOLS
712
879
  }, {
713
880
  reasoning: turn === 0 ? "medium" : void 0,
714
881
  maxTokens: 16384,
715
- ...apiKey ? { apiKey } : {}
882
+ signal: opts.signal
716
883
  });
717
884
  let assistantMessage;
718
885
  let turnText = "";
@@ -789,24 +956,31 @@ async function optimizeSectionPiAi(opts) {
789
956
  cost: totalCost
790
957
  };
791
958
  }
959
+ const STATIC_REGEX_1$2 = /^```(?:markdown|md)?[^\S\n]*\n([\s\S]+)\n```[^\S\n]*$/;
960
+ const STATIC_REGEX_2$2 = /^```(?:markdown|md)/;
961
+ const STATIC_REGEX_5$1 = /^-{3,}\n/;
962
+ const STATIC_REGEX_6 = /\n-{3,}/;
963
+ const STATIC_REGEX_7 = /^(##\s|- (?:BREAKING|DEPRECATED|NEW): )/m;
964
+ const STATIC_REGEX_8 = /^(## .+)\n/;
965
+ const STATIC_REGEX_9 = /^\.\/(?:\.skilld\/|references\/)/;
792
966
  function cleanSectionOutput(content) {
793
967
  let cleaned = content.trim();
794
- const wrapMatch = cleaned.match(/^```(?:markdown|md)?[^\S\n]*\n([\s\S]+)\n```[^\S\n]*$/);
968
+ const wrapMatch = cleaned.match(STATIC_REGEX_1$2);
795
969
  if (wrapMatch) {
796
970
  const inner = wrapMatch[1].trim();
797
- if (/^```(?:markdown|md)/.test(cleaned) || /^##\s/m.test(inner) || /^- (?:BREAKING|DEPRECATED|NEW): /m.test(inner)) cleaned = inner;
971
+ if (STATIC_REGEX_2$2.test(cleaned) || SECTION_HEADING_RE.test(inner) || API_CHANGE_BULLET_RE.test(inner)) cleaned = inner;
798
972
  }
799
973
  cleaned = cleaned.replace(/^# (?!#)/gm, "## ");
800
- const fmMatch = cleaned.match(/^-{3,}\n/);
974
+ const fmMatch = cleaned.match(STATIC_REGEX_5$1);
801
975
  if (fmMatch) {
802
976
  const afterOpen = fmMatch[0].length;
803
- const closeMatch = cleaned.slice(afterOpen).match(/\n-{3,}/);
977
+ const closeMatch = cleaned.slice(afterOpen).match(STATIC_REGEX_6);
804
978
  if (closeMatch) cleaned = cleaned.slice(afterOpen + closeMatch.index + closeMatch[0].length).trim();
805
979
  else cleaned = cleaned.slice(afterOpen).trim();
806
980
  }
807
- const firstMarker = cleaned.match(/^(##\s|- (?:BREAKING|DEPRECATED|NEW): )/m);
981
+ const firstMarker = cleaned.match(STATIC_REGEX_7);
808
982
  if (firstMarker?.index && firstMarker.index > 0) cleaned = cleaned.slice(firstMarker.index).trim();
809
- const headingMatch = cleaned.match(/^(## .+)\n/);
983
+ const headingMatch = cleaned.match(STATIC_REGEX_8);
810
984
  if (headingMatch) {
811
985
  const heading = headingMatch[1];
812
986
  const afterFirst = headingMatch[0].length;
@@ -816,14 +990,17 @@ function cleanSectionOutput(content) {
816
990
  }
817
991
  }
818
992
  cleaned = cleaned.replace(/\(?\[`?\.\/(?:\.skilld\/|references\/)[^)\]]*\]\(([^)]+)\)\)?/g, (match, url) => {
819
- if (/^\.\/(?:\.skilld\/|references\/)/.test(url)) return `[source](${url})`;
993
+ if (STATIC_REGEX_9.test(url)) return `[source](${url})`;
820
994
  return match;
821
995
  });
822
996
  cleaned = cleaned.replace(/\[source\]\(\.\/((docs|issues|discussions|releases|pkg|guide)\/)/g, "[source](./.skilld/$1");
823
997
  cleaned = sanitizeMarkdown(cleaned);
824
- if (!/^##\s/m.test(cleaned) && !/^- (?:BREAKING|DEPRECATED|NEW): /m.test(cleaned) && !/\[source\]/.test(cleaned)) return "";
998
+ if (!SECTION_HEADING_RE.test(cleaned) && !API_CHANGE_BULLET_RE.test(cleaned) && !SOURCE_LINK_RE.test(cleaned)) return "";
825
999
  return cleaned;
826
1000
  }
1001
+ const STATIC_REGEX_1$1 = /^\[(?:starting|retrying|cached)/;
1002
+ const STATIC_REGEX_2$1 = /^\[([^:[\]]+)(?::\s(.+))?\]$/;
1003
+ const STATIC_REGEX_3$1 = /skilld search\s+"([^"]+)"/;
827
1004
  function createToolProgress(log) {
828
1005
  let lastMsg = "";
829
1006
  let repeatCount = 0;
@@ -832,7 +1009,7 @@ function createToolProgress(log) {
832
1009
  function emit(msg) {
833
1010
  if (msg === lastMsg) {
834
1011
  repeatCount++;
835
- log.message(`${msg} \x1B[90m(+${repeatCount})\x1B[0m`);
1012
+ log.message(`${msg} ${styleText("gray", `(+${repeatCount})`)}`);
836
1013
  } else {
837
1014
  lastMsg = msg;
838
1015
  repeatCount = 0;
@@ -845,17 +1022,17 @@ function createToolProgress(log) {
845
1022
  const now = Date.now();
846
1023
  if (now - (lastTextEmit.get(key) ?? 0) < TEXT_THROTTLE_MS) return;
847
1024
  lastTextEmit.set(key, now);
848
- const prefix = section ? `\x1B[90m[${section}]\x1B[0m ` : "";
1025
+ const prefix = section ? `${styleText("gray", `[${section}]`)} ` : "";
849
1026
  const items = text ? text.match(/^- (?:BREAKING|DEPRECATED|NEW|CHANGED|REMOVED|Use |Do |Set |Add |Avoid |Always |Never |Prefer |Check |Ensure )/gm)?.length ?? 0 : 0;
850
- emit(items > 0 ? `${prefix}Writing... \x1B[90m(${items} items)\x1B[0m` : `${prefix}Writing...`);
1027
+ emit(items > 0 ? `${prefix}Writing... ${styleText("gray", `(${items} items)`)}` : `${prefix}Writing...`);
851
1028
  return;
852
1029
  }
853
1030
  if (type !== "reasoning" || !chunk.startsWith("[")) return;
854
- if (/^\[(?:starting|retrying|cached)/.test(chunk)) {
855
- emit(`${section ? `\x1B[90m[${section}]\x1B[0m ` : ""}${chunk.slice(1, -1)}`);
1031
+ if (STATIC_REGEX_1$1.test(chunk)) {
1032
+ emit(`${section ? `${styleText("gray", `[${section}]`)} ` : ""}${chunk.slice(1, -1)}`);
856
1033
  return;
857
1034
  }
858
- const match = chunk.match(/^\[([^:[\]]+)(?::\s(.+))?\]$/);
1035
+ const match = chunk.match(STATIC_REGEX_2$1);
859
1036
  if (!match) return;
860
1037
  const names = match[1].split(",").map((n) => n.trim());
861
1038
  const hints = match[2]?.split(",").map((h) => h.trim()) ?? [];
@@ -863,16 +1040,19 @@ function createToolProgress(log) {
863
1040
  const rawName = names[i];
864
1041
  const hint = hints[i] ?? hints[0] ?? "";
865
1042
  const verb = TOOL_NAMES[rawName]?.verb ?? rawName;
866
- const prefix = section ? `\x1B[90m[${section}]\x1B[0m ` : "";
1043
+ const prefix = section ? `${styleText("gray", `[${section}]`)} ` : "";
867
1044
  if ((rawName === "Bash" || rawName === "run_shell_command") && hint) {
868
- const searchMatch = hint.match(/skilld search\s+"([^"]+)"/);
869
- if (searchMatch) emit(`${prefix}Searching \x1B[36m"${searchMatch[1]}"\x1B[0m`);
1045
+ const searchMatch = hint.match(STATIC_REGEX_3$1);
1046
+ if (searchMatch) emit(`${prefix}Searching ${styleText("cyan", `"${searchMatch[1]}"`)}`);
870
1047
  else if (hint.includes("skilld validate")) emit(`${prefix}Validating...`);
871
1048
  else {
872
1049
  const shortened = shortenCommand(hint);
873
1050
  emit(`${prefix}Running ${shortened.length > 50 ? `${shortened.slice(0, 47)}...` : shortened}`);
874
1051
  }
875
- } else emit(`${prefix}${verb} \x1B[90m${shortenPath(hint || "...")}\x1B[0m`);
1052
+ } else {
1053
+ const path = shortenPath(hint || "...");
1054
+ emit(`${prefix}${verb} ${styleText("gray", path)}`);
1055
+ }
876
1056
  }
877
1057
  };
878
1058
  }
@@ -913,10 +1093,12 @@ const CLI_MODELS = Object.fromEntries(Object.values(CLI_ADAPTERS).flatMap((adapt
913
1093
  agentId: adapter.agentId
914
1094
  }])));
915
1095
  function getModelName(id) {
1096
+ if (isOllamaModel(id)) return parseOllamaModelId(id) ?? id;
916
1097
  if (isPiAiModel(id)) return parsePiAiModelId(id)?.modelId ?? id;
917
1098
  return CLI_MODELS[id]?.name ?? id;
918
1099
  }
919
1100
  function getModelLabel(id) {
1101
+ if (isOllamaModel(id)) return `Ollama · ${parseOllamaModelId(id) ?? id}`;
920
1102
  if (isPiAiModel(id)) {
921
1103
  const parsed = parsePiAiModelId(id);
922
1104
  return parsed ? `${PI_PROVIDER_NAMES[parsed.provider] ?? parsed.provider} · ${parsed.modelId}` : id;
@@ -928,6 +1110,7 @@ function getModelLabel(id) {
928
1110
  async function getAvailableModels() {
929
1111
  const execAsync = promisify(exec);
930
1112
  const lookupCmd = isWindows ? "where" : "which";
1113
+ const ollamaModelsPromise = getAvailableOllamaModels();
931
1114
  const agentsWithCli = detectInstalledAgents().filter((id) => targets[id].cli);
932
1115
  const cliChecks = await Promise.all(agentsWithCli.map(async (agentId) => {
933
1116
  const cli = targets[agentId].cli;
@@ -953,10 +1136,10 @@ async function getAvailableModels() {
953
1136
  vendorGroup: providerName
954
1137
  };
955
1138
  });
956
- const piAiEntries = getAvailablePiAiModels().map((m) => {
1139
+ const piAiEntries = (await getAvailablePiAiModels()).map((m) => {
957
1140
  const piProvider = parsePiAiModelId(m.id)?.provider ?? "pi-ai";
958
1141
  const displayName = PI_PROVIDER_NAMES[piProvider] ?? piProvider;
959
- const authLabel = m.authSource === "env" ? "API" : "OAuth";
1142
+ const authLabel = m.authSource === "api-key" ? "API key" : "OAuth";
960
1143
  return {
961
1144
  id: m.id,
962
1145
  name: m.name,
@@ -969,7 +1152,21 @@ async function getAvailableModels() {
969
1152
  vendorGroup: displayName
970
1153
  };
971
1154
  });
972
- return [...cliModels, ...piAiEntries];
1155
+ const ollamaEntries = (await ollamaModelsPromise).map((m) => ({
1156
+ id: m.id,
1157
+ name: m.name,
1158
+ hint: m.hint,
1159
+ agentId: "ollama",
1160
+ agentName: "Ollama (local)",
1161
+ provider: "ollama",
1162
+ providerName: "Ollama (local)",
1163
+ vendorGroup: "Ollama"
1164
+ }));
1165
+ return [
1166
+ ...cliModels,
1167
+ ...piAiEntries,
1168
+ ...ollamaEntries
1169
+ ];
973
1170
  }
974
1171
  const NUXT_CONFIG_FILES = [
975
1172
  "nuxt.config.ts",
@@ -1031,13 +1228,16 @@ async function detectNuxtModules(cwd) {
1031
1228
  async function detectPresetPackages(cwd) {
1032
1229
  return detectNuxtModules(cwd);
1033
1230
  }
1231
+ const FROM_STATIC_IMPORT_RE = /\bfrom\s*['"]([^'"\n]+)['"]/g;
1232
+ const SIDE_EFFECT_IMPORT_RE = /\bimport\s*['"]([^'"\n]+)['"]/g;
1233
+ const DYNAMIC_IMPORT_RE = /\bimport\s*\(\s*['"]([^'"\n]+)['"]\s*\)/g;
1034
1234
  const PATTERNS = ["**/*.{ts,js,vue,mjs,cjs,tsx,jsx,mts,cts}"];
1035
- const IGNORE = [
1036
- "**/node_modules/**",
1037
- "**/dist/**",
1038
- "**/.nuxt/**",
1039
- "**/.output/**",
1040
- "**/coverage/**"
1235
+ const IGNORE_DIRS = [
1236
+ "node_modules",
1237
+ "dist",
1238
+ ".nuxt",
1239
+ ".output",
1240
+ "coverage"
1041
1241
  ];
1042
1242
  function addPackage(counts, specifier) {
1043
1243
  if (!specifier || specifier.startsWith(".") || specifier.startsWith("/")) return;
@@ -1047,19 +1247,16 @@ function addPackage(counts, specifier) {
1047
1247
  async function detectImportedPackages(cwd = process.cwd()) {
1048
1248
  try {
1049
1249
  const counts = /* @__PURE__ */ new Map();
1050
- const files = await glob(PATTERNS, {
1250
+ const files = [];
1251
+ for await (const file of glob(PATTERNS, {
1051
1252
  cwd,
1052
- ignore: IGNORE,
1053
- absolute: true,
1054
- expandDirectories: false
1055
- });
1253
+ exclude: (p) => IGNORE_DIRS.some((dir) => p === dir || p.endsWith(`/${dir}`))
1254
+ })) files.push(join(cwd, file));
1056
1255
  await Promise.all(files.map(async (file) => {
1057
1256
  const content = await readFile(file, "utf8");
1058
- for (const imp of findStaticImports(content)) addPackage(counts, imp.specifier);
1059
- for (const imp of findDynamicImports(content)) {
1060
- const match = imp.expression.match(/^['"]([^'"]+)['"]$/);
1061
- if (match) addPackage(counts, match[1]);
1062
- }
1257
+ for (const m of content.matchAll(FROM_STATIC_IMPORT_RE)) addPackage(counts, m[1]);
1258
+ for (const m of content.matchAll(SIDE_EFFECT_IMPORT_RE)) addPackage(counts, m[1]);
1259
+ for (const m of content.matchAll(DYNAMIC_IMPORT_RE)) addPackage(counts, m[1]);
1063
1260
  }));
1064
1261
  const packages = Array.from(counts.entries(), ([name, count]) => ({
1065
1262
  name,
@@ -1077,7 +1274,7 @@ async function detectImportedPackages(cwd = process.cwd()) {
1077
1274
  };
1078
1275
  }
1079
1276
  }
1080
- const NODE_BUILTINS = new Set([
1277
+ const NODE_BUILTINS = /* @__PURE__ */ new Set([
1081
1278
  "assert",
1082
1279
  "async_hooks",
1083
1280
  "buffer",
@@ -1128,7 +1325,7 @@ function isNodeBuiltin(pkg) {
1128
1325
  const base = pkg.startsWith("node:") ? pkg.slice(5) : pkg;
1129
1326
  return NODE_BUILTINS.has(base.split("/")[0]);
1130
1327
  }
1131
- const DEFAULT_MAX_AGE = 10080 * 60 * 1e3;
1328
+ const DEFAULT_MAX_AGE = 6048e5;
1132
1329
  function normalizePromptForHash(prompt) {
1133
1330
  return prompt.replace(/\/[^\s`]*\.(?:claude|codex|gemini)\/skills\/[^\s/`]+/g, "<SKILL_DIR>");
1134
1331
  }
@@ -1262,9 +1459,6 @@ function spawnCliAndStream(opts) {
1262
1459
  case "done":
1263
1460
  if (evt.usage) usage = evt.usage;
1264
1461
  if (evt.cost != null) cost = evt.cost;
1265
- break;
1266
- case "error":
1267
- case "noop": break;
1268
1462
  }
1269
1463
  }
1270
1464
  proc.stdout.on("data", (chunk) => {
@@ -1322,8 +1516,9 @@ function cliExecutor(model) {
1322
1516
  })
1323
1517
  };
1324
1518
  }
1325
- function piAiExecutor(model) {
1326
- if (!new Set(getAvailablePiAiModels().map((m) => m.id)).has(model)) return { error: `Pi model unavailable or not authenticated: ${model}` };
1519
+ async function piAiExecutor(model) {
1520
+ const models = createPiAiModels();
1521
+ if (!new Set((await getAvailablePiAiModels(models)).map((m) => m.id)).has(model)) return { error: `Pi model unavailable or not authenticated: ${model}` };
1327
1522
  return {
1328
1523
  cliCleanup: false,
1329
1524
  run: async ({ section, prompt, skillDir, timeout, onProgress }) => {
@@ -1336,7 +1531,8 @@ function piAiExecutor(model) {
1336
1531
  skillDir,
1337
1532
  model,
1338
1533
  onProgress,
1339
- signal: ac.signal
1534
+ signal: ac.signal,
1535
+ models
1340
1536
  });
1341
1537
  return {
1342
1538
  text: result.text.trim(),
@@ -1355,9 +1551,15 @@ function piAiExecutor(model) {
1355
1551
  }
1356
1552
  };
1357
1553
  }
1358
- function selectExecutor(model) {
1554
+ async function selectExecutor(model) {
1555
+ if (isOllamaModel(model)) return ollamaExecutor(model);
1359
1556
  return isPiAiModel(model) ? piAiExecutor(model) : cliExecutor(model);
1360
1557
  }
1558
+ const STATIC_REGEX_1 = /\b429\b/;
1559
+ const STATIC_REGEX_2 = /rate.?limit/i;
1560
+ const STATIC_REGEX_3 = /exhausted.*capacity/i;
1561
+ const STATIC_REGEX_4 = /quota.*reset/i;
1562
+ const STATIC_REGEX_5 = /reset\s+after\s+(\d+)s/i;
1361
1563
  async function optimizeSection(opts) {
1362
1564
  const { section, prompt, outputFile, skillDir, executor, onProgress, timeout, debug, preExistingFiles } = opts;
1363
1565
  const skilldDir = skillInternalDir(skillDir);
@@ -1411,7 +1613,7 @@ async function optimizeDocs(opts) {
1411
1613
  wasOptimized: false,
1412
1614
  error: "No valid sections to generate"
1413
1615
  };
1414
- const executorOrError = selectExecutor(model);
1616
+ const executorOrError = await selectExecutor(model);
1415
1617
  if ("error" in executorOrError) return {
1416
1618
  optimized: "",
1417
1619
  wasOptimized: false,
@@ -1604,17 +1806,17 @@ async function optimizeDocs(opts) {
1604
1806
  }
1605
1807
  function isRateLimitError(error) {
1606
1808
  if (!error) return false;
1607
- return /\b429\b/.test(error) || /rate.?limit/i.test(error) || /exhausted.*capacity/i.test(error) || /quota.*reset/i.test(error);
1809
+ return STATIC_REGEX_1.test(error) || STATIC_REGEX_2.test(error) || STATIC_REGEX_3.test(error) || STATIC_REGEX_4.test(error);
1608
1810
  }
1609
1811
  function parseRateLimitDelay(error) {
1610
1812
  if (!error || !isRateLimitError(error)) return void 0;
1611
- const match = error.match(/reset\s+after\s+(\d+)s/i);
1813
+ const match = error.match(STATIC_REGEX_5);
1612
1814
  return match ? Number(match[1]) : 10;
1613
1815
  }
1614
1816
  function getRetryError(result) {
1615
1817
  if (result.status === "rejected") return String(result.reason);
1616
1818
  return result.value.error;
1617
1819
  }
1618
- export { getModelName as a, getOAuthProviderList as c, getModelLabel as i, loginOAuthProvider as l, detectImportedPackages as n, createToolProgress as o, getAvailableModels as r, cleanSectionOutput as s, optimizeDocs as t, logoutOAuthProvider as u };
1820
+ export { cleanSectionOutput, createToolProgress, detectImportedPackages, getAvailableModels, getModelLabel, getModelName, getOAuthProviderList, loginOAuthProvider, logoutOAuthProvider, optimizeDocs };
1619
1821
 
1620
1822
  //# sourceMappingURL=agent.mjs.map