skilld 2.0.0 → 2.2.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 (133) hide show
  1. package/README.md +94 -0
  2. package/dist/_chunks/add.mjs +10 -9
  3. package/dist/_chunks/add.mjs.map +1 -1
  4. package/dist/_chunks/agent-prompt.mjs +4 -4
  5. package/dist/_chunks/agent-prompt.mjs.map +1 -1
  6. package/dist/_chunks/agent.mjs +282 -109
  7. package/dist/_chunks/agent.mjs.map +1 -1
  8. package/dist/_chunks/args.mjs +2 -2
  9. package/dist/_chunks/args.mjs.map +1 -1
  10. package/dist/_chunks/assemble.mjs +4 -4
  11. package/dist/_chunks/assemble.mjs.map +1 -1
  12. package/dist/_chunks/author.mjs +12 -11
  13. package/dist/_chunks/author.mjs.map +1 -1
  14. package/dist/_chunks/cache.mjs +21 -138
  15. package/dist/_chunks/cache.mjs.map +1 -1
  16. package/dist/_chunks/cache2.mjs +3 -3
  17. package/dist/_chunks/cache2.mjs.map +1 -1
  18. package/dist/_chunks/client.mjs +4 -3
  19. package/dist/_chunks/client.mjs.map +1 -1
  20. package/dist/_chunks/core.mjs +1 -1
  21. package/dist/_chunks/detect.mjs +1 -1
  22. package/dist/_chunks/detect.mjs.map +1 -1
  23. package/dist/_chunks/detect2.mjs +1 -1
  24. package/dist/_chunks/eject.mjs +7 -7
  25. package/dist/_chunks/eject.mjs.map +1 -1
  26. package/dist/_chunks/embedding-cache.mjs +1 -1
  27. package/dist/_chunks/embedding-cache2.mjs +14 -13
  28. package/dist/_chunks/embedding-cache2.mjs.map +1 -1
  29. package/dist/_chunks/env.mjs +1 -1
  30. package/dist/_chunks/env.mjs.map +1 -1
  31. package/dist/_chunks/index-identity.mjs +365 -0
  32. package/dist/_chunks/index-identity.mjs.map +1 -0
  33. package/dist/_chunks/index-identity2.mjs +2 -0
  34. package/dist/_chunks/install-many.mjs +20 -18
  35. package/dist/_chunks/install-many.mjs.map +1 -1
  36. package/dist/_chunks/install.mjs +34 -29
  37. package/dist/_chunks/install.mjs.map +1 -1
  38. package/dist/_chunks/intro.mjs +6 -6
  39. package/dist/_chunks/intro.mjs.map +1 -1
  40. package/dist/_chunks/list.mjs +5 -4
  41. package/dist/_chunks/list.mjs.map +1 -1
  42. package/dist/_chunks/lockfile.mjs +8 -6
  43. package/dist/_chunks/lockfile.mjs.map +1 -1
  44. package/dist/_chunks/login.mjs +7 -6
  45. package/dist/_chunks/login.mjs.map +1 -1
  46. package/dist/_chunks/logout.mjs +2 -2
  47. package/dist/_chunks/logout.mjs.map +1 -1
  48. package/dist/_chunks/map.mjs +1 -1
  49. package/dist/_chunks/map.mjs.map +1 -1
  50. package/dist/_chunks/markdown.mjs +2 -2
  51. package/dist/_chunks/markdown.mjs.map +1 -1
  52. package/dist/_chunks/menu.mjs +1 -1
  53. package/dist/_chunks/menu.mjs.map +1 -1
  54. package/dist/_chunks/model-picker.mjs +1 -1
  55. package/dist/_chunks/model-picker.mjs.map +1 -1
  56. package/dist/_chunks/monorepo.mjs +5 -4
  57. package/dist/_chunks/monorepo.mjs.map +1 -1
  58. package/dist/_chunks/package-json.mjs +7 -5
  59. package/dist/_chunks/package-json.mjs.map +1 -1
  60. package/dist/_chunks/paths.mjs +1 -1
  61. package/dist/_chunks/paths.mjs.map +1 -1
  62. package/dist/_chunks/pipeline.mjs +34 -26
  63. package/dist/_chunks/pipeline.mjs.map +1 -1
  64. package/dist/_chunks/pool.mjs +1 -1
  65. package/dist/_chunks/pool2.mjs +2 -2
  66. package/dist/_chunks/pool2.mjs.map +1 -1
  67. package/dist/_chunks/portable.mjs +8 -7
  68. package/dist/_chunks/portable.mjs.map +1 -1
  69. package/dist/_chunks/prepare-hook.mjs +1 -1
  70. package/dist/_chunks/prepare-hook2.mjs +3 -3
  71. package/dist/_chunks/prepare-hook2.mjs.map +1 -1
  72. package/dist/_chunks/prepare.mjs +17 -11
  73. package/dist/_chunks/prepare.mjs.map +1 -1
  74. package/dist/_chunks/prepare2.mjs +12 -10
  75. package/dist/_chunks/prepare2.mjs.map +1 -1
  76. package/dist/_chunks/prompts.mjs +8 -6
  77. package/dist/_chunks/prompts.mjs.map +1 -1
  78. package/dist/_chunks/pull.mjs +9 -8
  79. package/dist/_chunks/pull.mjs.map +1 -1
  80. package/dist/_chunks/regex.mjs +1 -1
  81. package/dist/_chunks/retriv.mjs +2 -2
  82. package/dist/_chunks/retriv2.mjs +22 -4
  83. package/dist/_chunks/retriv2.mjs.map +1 -1
  84. package/dist/_chunks/sanitize.mjs +1 -1
  85. package/dist/_chunks/sanitize.mjs.map +1 -1
  86. package/dist/_chunks/search-helpers.mjs +5 -5
  87. package/dist/_chunks/search-helpers.mjs.map +1 -1
  88. package/dist/_chunks/search-interactive.mjs +4 -4
  89. package/dist/_chunks/search-interactive.mjs.map +1 -1
  90. package/dist/_chunks/search.mjs +6 -6
  91. package/dist/_chunks/search.mjs.map +1 -1
  92. package/dist/_chunks/semver.mjs +111 -77
  93. package/dist/_chunks/semver.mjs.map +1 -1
  94. package/dist/_chunks/skill-installer.mjs +1 -1
  95. package/dist/_chunks/skill-installer2.mjs +26 -17
  96. package/dist/_chunks/skill-installer2.mjs.map +1 -1
  97. package/dist/_chunks/skills.mjs +7 -7
  98. package/dist/_chunks/skills.mjs.map +1 -1
  99. package/dist/_chunks/store.mjs +2 -2
  100. package/dist/_chunks/store.mjs.map +1 -1
  101. package/dist/_chunks/sync.mjs +26 -19
  102. package/dist/_chunks/sync.mjs.map +1 -1
  103. package/dist/_chunks/sync2.mjs +1 -1
  104. package/dist/_chunks/telemetry.mjs +3 -3
  105. package/dist/_chunks/telemetry.mjs.map +1 -1
  106. package/dist/_chunks/uninstall.mjs +32 -28
  107. package/dist/_chunks/uninstall.mjs.map +1 -1
  108. package/dist/_chunks/update.mjs +14 -13
  109. package/dist/_chunks/update.mjs.map +1 -1
  110. package/dist/_chunks/upload.mjs +13 -10
  111. package/dist/_chunks/upload.mjs.map +1 -1
  112. package/dist/_chunks/validate.mjs +1 -1
  113. package/dist/_chunks/validate.mjs.map +1 -1
  114. package/dist/_chunks/version.mjs +1 -1
  115. package/dist/_chunks/version.mjs.map +1 -1
  116. package/dist/_chunks/whoami.mjs +1 -1
  117. package/dist/_chunks/whoami.mjs.map +1 -1
  118. package/dist/_chunks/wizard.mjs +1 -1
  119. package/dist/_chunks/wizard2.mjs +8 -8
  120. package/dist/_chunks/wizard2.mjs.map +1 -1
  121. package/dist/_chunks/yaml.mjs +1 -1
  122. package/dist/_chunks/yaml.mjs.map +1 -1
  123. package/dist/cli-entry.d.mts +1 -1
  124. package/dist/cli.d.mts +1 -1
  125. package/dist/cli.mjs +111 -35
  126. package/dist/cli.mjs.map +1 -1
  127. package/dist/prepare.d.mts +1 -1
  128. package/dist/prepare.mjs +6 -4
  129. package/dist/prepare.mjs.map +1 -1
  130. package/dist/retriv/worker.d.mts.map +1 -1
  131. package/dist/retriv/worker.mjs +11 -5
  132. package/dist/retriv/worker.mjs.map +1 -1
  133. package/package.json +24 -24
@@ -1,17 +1,17 @@
1
- import { a as targets, t as detectInstalledAgents } from "./detect.mjs";
2
- import { A as resolveSkilldCommand, C as SECTION_OUTPUT_FILES, S as SECTION_MERGE_ORDER, _ as buildAllSectionPrompts, x as wrapSection, y as getSectionValidator } from "./prompts.mjs";
3
- import { g as skillLogDir, i as LLM_CACHE_DIR, m as skillInternalDir, n as CACHE_DIR, o as PI_AI_AUTH_PATH } from "./paths.mjs";
4
- import { d as SECTION_HEADING_RE, m as TRAILING_SLASH_RE, p as SOURCE_LINK_RE, t as API_CHANGE_BULLET_RE } from "./regex.mjs";
5
- import { n as sanitizeMarkdown } from "./sanitize.mjs";
6
- import { n as getSkillReferenceDirs, t as createReferenceCache } from "./cache.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 { 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";
7
8
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
8
9
  import { promisify, styleText } from "node:util";
9
10
  import { join } from "pathe";
10
11
  import { exec, execFileSync, spawn } from "node:child_process";
11
12
  import { isWindows } from "std-env";
12
13
  import { homedir } from "node:os";
13
- import { getEnvApiKey, getEnvApiKey as getEnvApiKey$1, getModel, getModels, getProviders, streamSimple } from "@earendil-works/pi-ai";
14
- import { getOAuthApiKey, getOAuthProvider, getOAuthProviders } from "@earendil-works/pi-ai/oauth";
14
+ import { builtinModels, builtinProviders, getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
15
15
  import { resolve as resolve$1 } from "node:path";
16
16
  import { Type } from "typebox";
17
17
  import { glob, readFile } from "node:fs/promises";
@@ -42,7 +42,7 @@ function compareVersions(a, b) {
42
42
  }
43
43
  function resolve$2(opts) {
44
44
  const { provider, prefix, contains, exclude } = opts;
45
- 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];
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
46
  }
47
47
  function buildModelEntry(opts) {
48
48
  const found = resolve$2(opts);
@@ -387,32 +387,175 @@ const adapter = {
387
387
  buildArgs,
388
388
  parseEvent
389
389
  };
390
- const BLOCKED_OAUTH_PROVIDERS = new Set([
391
- "google-antigravity",
392
- "google-gemini-cli",
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([
393
525
  "github-copilot",
394
526
  "anthropic",
395
527
  "openai-codex"
396
528
  ]);
397
529
  const PI_AGENT_AUTH_PATH = join(process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"), "auth.json");
398
530
  const SKILLD_AUTH_PATH = PI_AI_AUTH_PATH;
399
- const OAUTH_PROVIDER_OVERRIDES = {
400
- google: "google-gemini-cli",
401
- openai: "openai-codex"
402
- };
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
+ }
403
543
  function readAuthFile(path) {
404
544
  if (!existsSync(path)) return {};
405
545
  try {
406
- return JSON.parse(readFileSync(path, "utf-8"));
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])));
407
549
  } catch {
408
550
  return {};
409
551
  }
410
552
  }
411
553
  function loadAuth() {
412
554
  const piAuth = readAuthFile(PI_AGENT_AUTH_PATH);
555
+ const skilldAuth = readAuthFile(SKILLD_AUTH_PATH);
413
556
  return {
414
- ...readAuthFile(SKILLD_AUTH_PATH),
415
- ...piAuth
557
+ ...piAuth,
558
+ ...skilldAuth
416
559
  };
417
560
  }
418
561
  function saveAuth(auth) {
@@ -422,58 +565,79 @@ function saveAuth(auth) {
422
565
  });
423
566
  writeFileSync(SKILLD_AUTH_PATH, JSON.stringify(auth, null, 2), { mode: 384 });
424
567
  }
425
- function resolveOAuthProviderId(modelProvider) {
426
- const oauthId = OAUTH_PROVIDER_OVERRIDES[modelProvider] ?? modelProvider;
427
- if (BLOCKED_OAUTH_PROVIDERS.has(oauthId)) return null;
428
- if (OAUTH_PROVIDER_OVERRIDES[modelProvider]) return OAUTH_PROVIDER_OVERRIDES[modelProvider];
429
- if (new Set(getOAuthProviders().map((p) => p.id)).has(modelProvider)) return modelProvider;
430
- return null;
431
- }
432
- async function resolveApiKey(provider) {
433
- const envKey = getEnvApiKey$1(provider);
434
- if (envKey) return envKey;
435
- const oauthProviderId = resolveOAuthProviderId(provider);
436
- if (!oauthProviderId) return null;
437
- const auth = loadAuth();
438
- if (!auth[oauthProviderId]) return null;
439
- const result = await getOAuthApiKey(oauthProviderId, auth);
440
- if (!result) return null;
441
- const skilldAuth = readAuthFile(SKILLD_AUTH_PATH);
442
- skilldAuth[oauthProviderId] = {
443
- type: "oauth",
444
- ...result.newCredentials
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
+ }
445
601
  };
446
- saveAuth(skilldAuth);
447
- return result.apiKey;
602
+ }
603
+ function createPiAiModels() {
604
+ return builtinModels({ credentials: createCredentialStore() });
448
605
  }
449
606
  function getOAuthProviderList() {
450
607
  const auth = loadAuth();
451
- return getOAuthProviders().filter((p) => !BLOCKED_OAUTH_PROVIDERS.has(p.id)).map((p) => ({
452
- id: p.id,
453
- name: p.name ?? p.id,
454
- loggedIn: !!auth[p.id]
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"
455
612
  }));
456
613
  }
457
614
  async function loginOAuthProvider(providerId, callbacks) {
458
- const provider = getOAuthProvider(providerId);
459
- if (!provider) return false;
460
- const credentials = await provider.login({
461
- onAuth: (info) => callbacks.onAuth(info.url, info.instructions),
462
- onPrompt: async (prompt) => callbacks.onPrompt(prompt.message, prompt.placeholder),
463
- onProgress: (msg) => callbacks.onProgress?.(msg)
464
- });
465
- const auth = loadAuth();
466
- auth[providerId] = {
467
- type: "oauth",
468
- ...credentials
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
469
635
  };
470
- saveAuth(auth);
636
+ await models.login(providerId, "oauth", interaction);
471
637
  return true;
472
638
  }
473
- function logoutOAuthProvider(providerId) {
474
- const auth = loadAuth();
475
- delete auth[providerId];
476
- saveAuth(auth);
639
+ async function logoutOAuthProvider(providerId) {
640
+ await createPiAiModels().logout(providerId);
477
641
  }
478
642
  function isPiAiModel(model) {
479
643
  return model.startsWith("pi:");
@@ -510,42 +674,27 @@ const RECOMMENDED_MODELS = {
510
674
  google: /flash/,
511
675
  openai: /gpt-4\.1-mini/
512
676
  };
513
- function getAvailablePiAiModels() {
514
- const providers = getProviders();
515
- const auth = loadAuth();
677
+ async function getAvailablePiAiModels(models = createPiAiModels()) {
678
+ const modelsByProvider = Map.groupBy(await models.getAvailable(), (model) => model.provider);
516
679
  const available = [];
517
- const recommendedPicked = /* @__PURE__ */ new Set();
518
- for (const provider of providers) {
519
- let authSource = "none";
520
- if (getEnvApiKey(provider)) authSource = "env";
521
- else {
522
- const oauthId = resolveOAuthProviderId(provider);
523
- if (oauthId && auth[oauthId]) authSource = "oauth";
524
- }
525
- if (authSource === "none") continue;
526
- const models = getModels(provider);
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";
527
684
  const recPattern = RECOMMENDED_MODELS[provider];
528
- let recModelId = null;
529
- if (recPattern) {
530
- for (const model of models) if (!isLegacyModel(model.id) && recPattern.test(model.id)) {
531
- recModelId = model.id;
532
- break;
533
- }
534
- }
535
- for (const model of models) {
685
+ const recModelId = recPattern ? providerModels.find((model) => !isLegacyModel(model.id) && recPattern.test(model.id))?.id : void 0;
686
+ for (const model of providerModels) {
536
687
  if (model.contextWindow && model.contextWindow < MIN_CONTEXT_WINDOW) continue;
537
688
  if (isLegacyModel(model.id)) continue;
538
689
  const id = `pi:${provider}/${model.id}`;
539
690
  const ctx = model.contextWindow ? ` · ${Math.round(model.contextWindow / 1e3)}k ctx` : "";
540
691
  const cost = model.cost?.input ? ` · $${model.cost.input}/Mtok` : "";
541
- const isRecommended = model.id === recModelId && !recommendedPicked.has(provider);
542
- if (isRecommended) recommendedPicked.add(provider);
543
692
  available.push({
544
693
  id,
545
694
  name: model.name || model.id,
546
695
  hint: `${authSource === "oauth" ? "OAuth" : "API key"}${ctx}${cost}`,
547
696
  authSource,
548
- recommended: isRecommended
697
+ recommended: model.id === recModelId
549
698
  });
550
699
  }
551
700
  }
@@ -583,7 +732,7 @@ const TOOLS = [
583
732
  parameters: Type.Object({ command: Type.String({ description: "Shell command to run" }) })
584
733
  }
585
734
  ];
586
- const SAFE_COMMANDS = new Set([
735
+ const SAFE_COMMANDS = /* @__PURE__ */ new Set([
587
736
  "skilld",
588
737
  "ls",
589
738
  "cat",
@@ -591,7 +740,8 @@ const SAFE_COMMANDS = new Set([
591
740
  ]);
592
741
  const SHELL_META_RE = /[;&|`$()<>]/;
593
742
  function resolveSandboxedPath(p, skilldDir) {
594
- const resolved = resolve$1(skilldDir, String(p).replace(STATIC_REGEX_1$3, "./").replace(STATIC_REGEX_2$3, "./").replace(STATIC_REGEX_3$2, ""));
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);
595
745
  if (!resolved.startsWith(`${skilldDir}/`) && resolved !== skilldDir) throw new Error(`Path traversal blocked: ${p}`);
596
746
  return resolved;
597
747
  }
@@ -662,9 +812,11 @@ function executeTool(toolCall, skilldDir) {
662
812
  const matched = results.filter((r) => globMatch(r.replace(STATIC_REGEX_1$3, ""), pattern));
663
813
  return matched.length > 0 ? matched.join("\n") : `No files matching: ${args.pattern}`;
664
814
  }
665
- case "Write":
666
- writeFileSync(resolveSandboxedPath(args.path, skilldDir), sanitizeMarkdown(String(args.content)));
815
+ case "Write": {
816
+ const filePath = resolveSandboxedPath(args.path, skilldDir);
817
+ writeFileSync(filePath, sanitizeMarkdown(String(args.content)));
667
818
  return "File written successfully.";
819
+ }
668
820
  case "Bash": {
669
821
  const cmd = String(args.command).trim();
670
822
  const parts = cmd.split(STATIC_REGEX_5$2);
@@ -675,7 +827,7 @@ function executeTool(toolCall, skilldDir) {
675
827
  cwd: skilldDir,
676
828
  timeout: 15e3,
677
829
  encoding: "utf-8",
678
- maxBuffer: 512 * 1024
830
+ maxBuffer: 524288
679
831
  }).trim();
680
832
  } catch (err) {
681
833
  return `Error: ${err.message}`;
@@ -688,8 +840,9 @@ const SYSTEM_PROMPT = "You are a technical documentation expert generating SKILL
688
840
  async function optimizeSectionPiAi(opts) {
689
841
  const parsed = parsePiAiModelId(opts.model);
690
842
  if (!parsed) throw new Error(`Invalid pi-ai model ID: ${opts.model}. Expected format: pi:provider/model-id`);
691
- const model = getModel(parsed.provider, parsed.modelId);
692
- const apiKey = await resolveApiKey(parsed.provider);
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}`);
693
846
  const skilldDir = skillInternalDir(opts.skillDir);
694
847
  const fullPrompt = opts.prompt;
695
848
  opts.onProgress?.({
@@ -714,14 +867,14 @@ async function optimizeSectionPiAi(opts) {
714
867
  let lastWriteContent = "";
715
868
  for (let turn = 0; turn < 30; turn++) {
716
869
  if (opts.signal?.aborted) throw new Error("pi-ai request timed out");
717
- const eventStream = streamSimple(model, {
870
+ const eventStream = models.streamSimple(model, {
718
871
  systemPrompt: SYSTEM_PROMPT,
719
872
  messages,
720
873
  tools: TOOLS
721
874
  }, {
722
875
  reasoning: turn === 0 ? "medium" : void 0,
723
876
  maxTokens: 16384,
724
- ...apiKey ? { apiKey } : {}
877
+ signal: opts.signal
725
878
  });
726
879
  let assistantMessage;
727
880
  let turnText = "";
@@ -891,7 +1044,10 @@ function createToolProgress(log) {
891
1044
  const shortened = shortenCommand(hint);
892
1045
  emit(`${prefix}Running ${shortened.length > 50 ? `${shortened.slice(0, 47)}...` : shortened}`);
893
1046
  }
894
- } else emit(`${prefix}${verb} ${styleText("gray", shortenPath(hint || "..."))}`);
1047
+ } else {
1048
+ const path = shortenPath(hint || "...");
1049
+ emit(`${prefix}${verb} ${styleText("gray", path)}`);
1050
+ }
895
1051
  }
896
1052
  };
897
1053
  }
@@ -932,10 +1088,12 @@ const CLI_MODELS = Object.fromEntries(Object.values(CLI_ADAPTERS).flatMap((adapt
932
1088
  agentId: adapter.agentId
933
1089
  }])));
934
1090
  function getModelName(id) {
1091
+ if (isOllamaModel(id)) return parseOllamaModelId(id) ?? id;
935
1092
  if (isPiAiModel(id)) return parsePiAiModelId(id)?.modelId ?? id;
936
1093
  return CLI_MODELS[id]?.name ?? id;
937
1094
  }
938
1095
  function getModelLabel(id) {
1096
+ if (isOllamaModel(id)) return `Ollama · ${parseOllamaModelId(id) ?? id}`;
939
1097
  if (isPiAiModel(id)) {
940
1098
  const parsed = parsePiAiModelId(id);
941
1099
  return parsed ? `${PI_PROVIDER_NAMES[parsed.provider] ?? parsed.provider} · ${parsed.modelId}` : id;
@@ -947,6 +1105,7 @@ function getModelLabel(id) {
947
1105
  async function getAvailableModels() {
948
1106
  const execAsync = promisify(exec);
949
1107
  const lookupCmd = isWindows ? "where" : "which";
1108
+ const ollamaModelsPromise = getAvailableOllamaModels();
950
1109
  const agentsWithCli = detectInstalledAgents().filter((id) => targets[id].cli);
951
1110
  const cliChecks = await Promise.all(agentsWithCli.map(async (agentId) => {
952
1111
  const cli = targets[agentId].cli;
@@ -972,10 +1131,10 @@ async function getAvailableModels() {
972
1131
  vendorGroup: providerName
973
1132
  };
974
1133
  });
975
- const piAiEntries = getAvailablePiAiModels().map((m) => {
1134
+ const piAiEntries = (await getAvailablePiAiModels()).map((m) => {
976
1135
  const piProvider = parsePiAiModelId(m.id)?.provider ?? "pi-ai";
977
1136
  const displayName = PI_PROVIDER_NAMES[piProvider] ?? piProvider;
978
- const authLabel = m.authSource === "env" ? "API" : "OAuth";
1137
+ const authLabel = m.authSource === "api-key" ? "API key" : "OAuth";
979
1138
  return {
980
1139
  id: m.id,
981
1140
  name: m.name,
@@ -988,7 +1147,21 @@ async function getAvailableModels() {
988
1147
  vendorGroup: displayName
989
1148
  };
990
1149
  });
991
- return [...cliModels, ...piAiEntries];
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
+ ];
992
1165
  }
993
1166
  const NUXT_CONFIG_FILES = [
994
1167
  "nuxt.config.ts",
@@ -1096,7 +1269,7 @@ async function detectImportedPackages(cwd = process.cwd()) {
1096
1269
  };
1097
1270
  }
1098
1271
  }
1099
- const NODE_BUILTINS = new Set([
1272
+ const NODE_BUILTINS = /* @__PURE__ */ new Set([
1100
1273
  "assert",
1101
1274
  "async_hooks",
1102
1275
  "buffer",
@@ -1147,7 +1320,7 @@ function isNodeBuiltin(pkg) {
1147
1320
  const base = pkg.startsWith("node:") ? pkg.slice(5) : pkg;
1148
1321
  return NODE_BUILTINS.has(base.split("/")[0]);
1149
1322
  }
1150
- const DEFAULT_MAX_AGE = 10080 * 60 * 1e3;
1323
+ const DEFAULT_MAX_AGE = 6048e5;
1151
1324
  function normalizePromptForHash(prompt) {
1152
1325
  return prompt.replace(/\/[^\s`]*\.(?:claude|codex|gemini)\/skills\/[^\s/`]+/g, "<SKILL_DIR>");
1153
1326
  }
@@ -1281,9 +1454,6 @@ function spawnCliAndStream(opts) {
1281
1454
  case "done":
1282
1455
  if (evt.usage) usage = evt.usage;
1283
1456
  if (evt.cost != null) cost = evt.cost;
1284
- break;
1285
- case "error":
1286
- case "noop": break;
1287
1457
  }
1288
1458
  }
1289
1459
  proc.stdout.on("data", (chunk) => {
@@ -1341,8 +1511,9 @@ function cliExecutor(model) {
1341
1511
  })
1342
1512
  };
1343
1513
  }
1344
- function piAiExecutor(model) {
1345
- if (!new Set(getAvailablePiAiModels().map((m) => m.id)).has(model)) return { error: `Pi model unavailable or not authenticated: ${model}` };
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}` };
1346
1517
  return {
1347
1518
  cliCleanup: false,
1348
1519
  run: async ({ section, prompt, skillDir, timeout, onProgress }) => {
@@ -1355,7 +1526,8 @@ function piAiExecutor(model) {
1355
1526
  skillDir,
1356
1527
  model,
1357
1528
  onProgress,
1358
- signal: ac.signal
1529
+ signal: ac.signal,
1530
+ models
1359
1531
  });
1360
1532
  return {
1361
1533
  text: result.text.trim(),
@@ -1374,7 +1546,8 @@ function piAiExecutor(model) {
1374
1546
  }
1375
1547
  };
1376
1548
  }
1377
- function selectExecutor(model) {
1549
+ async function selectExecutor(model) {
1550
+ if (isOllamaModel(model)) return ollamaExecutor(model);
1378
1551
  return isPiAiModel(model) ? piAiExecutor(model) : cliExecutor(model);
1379
1552
  }
1380
1553
  const STATIC_REGEX_1 = /\b429\b/;
@@ -1435,7 +1608,7 @@ async function optimizeDocs(opts) {
1435
1608
  wasOptimized: false,
1436
1609
  error: "No valid sections to generate"
1437
1610
  };
1438
- const executorOrError = selectExecutor(model);
1611
+ const executorOrError = await selectExecutor(model);
1439
1612
  if ("error" in executorOrError) return {
1440
1613
  optimized: "",
1441
1614
  wasOptimized: false,
@@ -1639,6 +1812,6 @@ function getRetryError(result) {
1639
1812
  if (result.status === "rejected") return String(result.reason);
1640
1813
  return result.value.error;
1641
1814
  }
1642
- 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 };
1815
+ export { cleanSectionOutput, createToolProgress, detectImportedPackages, getAvailableModels, getModelLabel, getModelName, getOAuthProviderList, loginOAuthProvider, logoutOAuthProvider, optimizeDocs };
1643
1816
 
1644
1817
  //# sourceMappingURL=agent.mjs.map