@politty/valibot 0.6.1 → 0.7.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 (49) hide show
  1. package/README.md +2 -2
  2. package/dist/agent.d.ts +1 -1
  3. package/dist/argv-parser-BEwhz0XV.js +1 -0
  4. package/dist/cli-main-Dccv0RoX.js +1 -0
  5. package/dist/{cli-main-DblimvdD.js → cli-main-qfjIxAaA.js} +2 -2
  6. package/dist/cli-run-DdmVF2c9.js +1 -0
  7. package/dist/cli.js +1 -1
  8. package/dist/compile-cache.d.ts +1 -3
  9. package/dist/{completion-NbQ2jmWx.js → completion-07BWyhmL.js} +1 -1
  10. package/dist/completion-B9wrL5rH.js +1 -0
  11. package/dist/completion.d.ts +2 -22
  12. package/dist/completion.js +1 -1
  13. package/dist/{detect-agent-EHaSY1KW.d.ts → detect-agent-hU93hctO.d.ts} +0 -4
  14. package/dist/docs.d.ts +1 -21
  15. package/dist/docs.js +2 -2
  16. package/dist/dynamic-CxhC0uOL.js +1 -0
  17. package/dist/{dynamic-DvdL7L96.js → dynamic-D3fYVKon.js} +2 -2
  18. package/dist/index.d.ts +40 -48
  19. package/dist/index.js +1 -1
  20. package/dist/prompt-QPFzhQ3p.js +1 -0
  21. package/dist/prompt-clack.d.ts +2 -4
  22. package/dist/prompt-clack.js +1 -1
  23. package/dist/prompt-inquirer.d.ts +2 -4
  24. package/dist/prompt-inquirer.js +1 -1
  25. package/dist/prompt.d.ts +2 -10
  26. package/dist/prompt.js +1 -1
  27. package/dist/register-DsOawdf2.js +1 -0
  28. package/dist/runner-Bfxogqk4.js +1 -0
  29. package/dist/runner-BxFyJbWK.js +33 -0
  30. package/dist/schema-C2QqQGOQ.js +1 -0
  31. package/dist/schema-extractor-DL8vjWso.js +1 -0
  32. package/dist/skill.d.ts +7 -22
  33. package/dist/skill.js +2 -2
  34. package/dist/{types-DtQ-Zt3n.d.ts → types-dRfhGb8j.d.ts} +84 -28
  35. package/dist/{field-meta-CEtC5Mir.js → unflatten-D6YJ7e-J.js} +1 -1
  36. package/dist/{with-completion-command-QHQsd0Zt.d.ts → with-completion-command-BjPGpPV0.d.ts} +1 -9
  37. package/dist/{with-completion-command-CI1rxHay.js → with-completion-command-DSqob4X0.js} +2 -2
  38. package/package.json +2 -2
  39. package/dist/argv-parser-BzWc9lXh.js +0 -1
  40. package/dist/cli-main-CykIbGzU.js +0 -1
  41. package/dist/cli-run-DE7y0mXj.js +0 -1
  42. package/dist/completion-CmxAA8Op.js +0 -1
  43. package/dist/dynamic-BEW8hYW1.js +0 -1
  44. package/dist/prompt-Bs_O6SmK.js +0 -1
  45. package/dist/register-BtPBdvwq.js +0 -1
  46. package/dist/runner-Bg6kLaM9.js +0 -1
  47. package/dist/runner-BsHTbOwS.js +0 -33
  48. package/dist/schema-C20skX3E.js +0 -1
  49. package/dist/schema-extractor-lB6-WHOF.js +0 -1
package/dist/skill.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { L as UnknownKeysMode, a as ArgsSchema, r as AnyCommand } from "./types-DtQ-Zt3n.js";
2
- //#region ../core/src/skill/types.d.ts
1
+ import { R as UnknownKeysMode, a as ArgsSchema, r as AnyCommand } from "./types-dRfhGb8j.js";
3
2
  /**
4
3
  * SKILL.md frontmatter metadata, validated against the Agent Skills
5
4
  * specification (https://agentskills.io/specification). Unknown fields are
@@ -200,8 +199,8 @@ interface SkillCommandOptions {
200
199
  * A same-named field of another type (e.g. a string verbosity level)
201
200
  * doesn't trigger this — the local boolean flag stays declared. However,
202
201
  * politty itself independently rejects that combination: when
203
- * `globalArgs` and a command's own schema declare a same-named field
204
- * with different definitions, `runMain`/`runCommand` throws
202
+ * `globalArgs` and a command's own schema declare a same-named field,
203
+ * `runMain`/`runCommand` throws
205
204
  * `FieldTypeConflictError` at parse time. {@link SkillFlagOverrides} can't
206
205
  * help here — it only renames the short alias (`-v`/`-x`), not the long
207
206
  * `--verbose`/`--json` field name itself, so the conflicting name stays
@@ -209,15 +208,10 @@ interface SkillCommandOptions {
209
208
  * `json` field must rename or remove that global field (or make it a
210
209
  * plain boolean) instead.
211
210
  *
212
- * (Historical note: this omission used to also be required to work around
213
- * a politty core bug where a global flag typed *before* the subcommand
214
- * resolved correctly as a global value, but a same-named local field's
215
- * own default would then overwrite it during the merge. That bug is
216
- * fixed in politty core independently of this option — a same-named
217
- * local and global field with *identical* definitions now resolves
218
- * correctly regardless of position. This option still omits the local
219
- * flag by default for simplicity: hosts don't need to duplicate the
220
- * flag's definition on both schemas to get the expected behavior.)
211
+ * (This omission is required: politty rejects a field declared in both
212
+ * `globalArgs` and a command's own schema, even when the definitions are
213
+ * identical. Omitting the local flag leaves the host's global field as the
214
+ * only declaration.)
221
215
  *
222
216
  * @example
223
217
  * ```ts
@@ -357,8 +351,6 @@ type WithSkillCommand<T extends AnyCommand> = T & {
357
351
  skills: AnyCommand;
358
352
  };
359
353
  };
360
- //#endregion
361
- //#region ../core/src/skill/frontmatter.d.ts
362
354
  /**
363
355
  * Result of parsing a SKILL.md file.
364
356
  */
@@ -403,8 +395,6 @@ export declare function parseFrontmatter(content: string): {
403
395
  * missing or fails schema validation.
404
396
  */
405
397
  export declare function parseSkillMd(content: string): ParsedSkillMd | null;
406
- //#endregion
407
- //#region ../core/src/skill/installer.d.ts
408
398
  /**
409
399
  * Key used to read provenance off an installed skill. The SKILL.md's
410
400
  * `metadata["politty-cli"]` must equal `"{packageName}:{cliName}"` for the
@@ -521,8 +511,6 @@ export declare function hasInstalledSkill(name: string, cwd?: string): boolean;
521
511
  * Use {@link hasInstalledSkill} to distinguish the two cases.
522
512
  */
523
513
  export declare function readInstalledOwnership(name: string, cwd?: string): string | null;
524
- //#endregion
525
- //#region ../core/src/skill/scanner.d.ts
526
514
  /**
527
515
  * Scan a source directory for SKILL.md files.
528
516
  *
@@ -551,8 +539,6 @@ export declare function readInstalledOwnership(name: string, cwd?: string): stri
551
539
  * ```
552
540
  */
553
541
  export declare function scanSourceDir(sourceDir: string): ScanResult;
554
- //#endregion
555
- //#region ../core/src/skill/index.d.ts
556
542
  /**
557
543
  * Wrap a command with a `skills` subcommand for managing SKILL.md-based skills.
558
544
  *
@@ -577,5 +563,4 @@ export declare function scanSourceDir(sourceDir: string): ScanResult;
577
563
  * overwriting it would hide a configuration bug.
578
564
  */
579
565
  export declare function withSkillCommand<T extends AnyCommand>(command: T, options: SkillCommandOptions): WithSkillCommand<T>;
580
- //#endregion
581
566
  export type { DiscoveredSkill, InstallMode, InstallSkillOptions, ParsedSkillMd, ScanError, ScanErrorReason, ScanResult, SkillCommandOptions, SkillFlagOverrides, SkillFrontmatter, UninstallSkillOptions, WithSkillCommand };
package/dist/skill.js CHANGED
@@ -1,2 +1,2 @@
1
- import"./register-BtPBdvwq.js";import{d as e,n as t,u as n}from"./schema-extractor-lB6-WHOF.js";import{n as r}from"./command-BXsTrIgI.js";import{a as i,n as a}from"./logger-CoeDrmRr.js";import{copyFileSync as o,existsSync as s,lstatSync as c,mkdirSync as l,mkdtempSync as u,readFileSync as d,readdirSync as f,readlinkSync as p,realpathSync as m,renameSync as ee,rmSync as h,statSync as g,symlinkSync as te,unlinkSync as _}from"node:fs";import{basename as v,dirname as y,isAbsolute as b,join as x,parse as ne,relative as S,resolve as C,sep as w}from"node:path";import{parse as re}from"yaml";const ie=/^[a-z0-9]+(-[a-z0-9]+)*$/;function T(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function ae(e){let t=[],n=(n,r)=>{let i=e[n];i===void 0?r.required&&t.push({path:[n],message:`Invalid input: expected string, received undefined`}):typeof i==`string`?(r.min!==void 0&&i.length<r.min&&t.push({path:[n],message:`Too small: expected string to have >=${r.min} characters`}),r.max!==void 0&&i.length>r.max&&t.push({path:[n],message:`Too big: expected string to have <=${r.max} characters`})):t.push({path:[n],message:`Invalid input: expected string, received ${T(i)}`})};n(`name`,{required:!0,min:1,max:64}),typeof e.name==`string`&&!ie.test(e.name)&&t.push({path:[`name`],message:`name must be lowercase alphanumerics separated by single hyphens`}),n(`description`,{required:!0,min:1,max:1024}),n(`license`,{min:1}),n(`compatibility`,{max:500}),n(`allowed-tools`,{});let r=e.metadata;if(r!==void 0){if(typeof r!=`object`||!r||Array.isArray(r))t.push({path:[`metadata`],message:`Invalid input: expected record, received ${T(r)}`});else for(let[e,n]of Object.entries(r))typeof n!=`string`&&t.push({path:[`metadata`,e],message:`Invalid input: expected string, received ${T(n)}`})}return t.length>0?{success:!1,issues:t}:{success:!0,data:{...e}}}const oe=/^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/;function E(e){let t=e.match(oe);if(!t)return{data:{},body:e};let n=t[1],r=t[2];try{let e=re(n);return se(e)?{data:e,body:r}:{data:{},body:r}}catch(e){return{data:{},body:r,parseError:e instanceof Error?e.message:String(e)}}}function se(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ce(e){let{data:t,body:n}=E(e),r=ae(t);return r.success?{frontmatter:r.data,body:n,rawContent:e}:null}const D=`.agents/skills`,O=[`.claude/skills`],k=`politty-cli`;function A(e){if(e.length<1||e.length>64||!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e))throw Error(`Invalid skill name: ${JSON.stringify(e)}`)}function le(e,t=process.cwd(),n={}){let r=e.frontmatter.name;A(r);let i=n.mode??`symlink`,a=e.frontmatter.metadata?.[`politty-cli`]??null;if(i===`copy`&&a===null)throw Error(`Refusing to install "${e.frontmatter.name}" in copy mode without an ownership stamp. Add metadata.${k}="{package}:{cli}" to the source SKILL.md so subsequent installs can replace the copy in place.`);let o=C(t,D),s=m(e.sourcePath),c=ue(e.sourcePath),u=[x(M(o),r),...O.map(e=>x(M(C(t,e)),r))].find(e=>ye(e,s));if(u!==void 0)throw Error(`Refusing to install "${r}": source ${s} overlaps install destination ${u}. Choose a sourceDir outside .agents/skills/ and any agent-specific slot directory (e.g. .claude/skills/).`);if(i===`symlink`){let e=M(o);j(x(e,r),S(e,c));for(let n of O){let i=M(C(t,n));j(x(i,r),x(S(i,e),r))}}l(o,{recursive:!0});let d=m(o),f=x(d,r);he(f,a),ge({linkTarget:S(d,c),linkPath:f,copyFrom:s,mode:i}),ve(t,r,f,a,i)}function j(e,t){if(b(t))throw Error(`Refusing to write an absolute symlink target at ${e} → ${t}. The skill source and install root appear to live on different filesystem roots (e.g. different Windows drive letters); retry with mode: "copy".`)}function ue(e){let t=C(e),{root:n}=ne(t),r=t.slice(n.length).split(w).filter(e=>e!==``),i=n;for(let[e,t]of r.entries()){let n=x(i,t),a;try{a=c(n)}catch{return x(i,...r.slice(e))}if(a.isSymbolicLink()){if(de(i))return x(i,...r.slice(e));i=m(n)}else i=n}return i}function de(e){return v(e)===`node_modules`||v(e).startsWith(`@`)&&v(y(e))===`node_modules`}function M(e){let t=e,n=[];for(;;)try{let e=m(t);return n.length===0?e:C(e,...n.reverse())}catch{let r=y(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[/\\]+/,``)),t=r}}function fe(e,t=process.cwd(),n={}){A(e);let r=n.expectedOwnership??null,i=C(t,D,e);for(let n of O)me(C(t,n,e),r,{restrictSymlinkTo:i});me(i,r)}function pe(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n);if(r===t)return!0;try{return m(r)===m(t)}catch{return!1}}function me(e,t,n={}){let r;try{r=c(e)}catch(e){if(L(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return;throw e}if(r.isSymbolicLink()){if(n.restrictSymlinkTo!==void 0){pe(e,n.restrictSymlinkTo)&&_(e);return}(t===null||P(e)===t)&&_(e)}else r.isDirectory()&&t!==null&&P(e)===t&&h(e,{recursive:!0,force:!0})}function he(e,t,n={}){let r;try{r=c(e)}catch(e){if(L(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return;throw e}if(r.isSymbolicLink()){if(n.restrictSymlinkTo===void 0||pe(e,n.restrictSymlinkTo)){_(e);return}throw Error(`Refusing to replace symlink at ${e}: it does not route to this CLI's canonical slot (${n.restrictSymlinkTo}). Remove or migrate the foreign symlink before retrying.`)}if(r.isDirectory()&&t!==null&&P(e)===t)h(e,{recursive:!0,force:!0});else throw Error(`Refusing to replace non-symlink path at ${e}. This looks like a legacy or manual install; remove or migrate it before retrying.`)}function ge(e){let{linkTarget:t,linkPath:n,copyFrom:r,mode:i}=e;if(i===`copy`)_e(r,n);else{j(n,t);try{te(t,n,`dir`)}catch(e){let r=e instanceof Error?e.message:String(e);throw Error(`Failed to symlink ${n} → ${t}: ${r}. If this filesystem does not support symlinks (e.g. Windows without Developer Mode), retry with mode: "copy".`,{cause:e})}}}function _e(e,t){let n=u(`${t}.partial-`);try{N(e,n),ee(n,t)}catch(e){try{h(n,{recursive:!0,force:!0})}catch{}throw e}}function N(e,t,n=/* @__PURE__ */ new Set){let r=g(e);if(r.isDirectory()){let r=m(e);if(n.has(r))throw Error(`Refusing to recursively copy cyclic directory symlink at ${e} (resolves to ${r}, already on the copy stack).`);n.add(r);try{l(t,{recursive:!0});for(let r of f(e))N(x(e,r),x(t,r),n)}finally{n.delete(r)}}else r.isFile()&&o(e,t)}function P(e){let t;try{t=d(x(e,`SKILL.md`),`utf-8`)}catch(e){if(L(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return null;throw e}let{data:n}=E(t),r=n.metadata;if(!r||typeof r!=`object`||Array.isArray(r))return null;let i=r[k];return typeof i==`string`?i:null}function F(e,t=process.cwd()){return A(e),s(C(t,D,e,`SKILL.md`))}function I(e,t=process.cwd()){A(e);let n=C(t,D,e,`SKILL.md`),r;try{r=d(n,`utf-8`)}catch(e){if(L(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return null;throw e}let{data:i}=E(r),a=i.metadata;if(!a||typeof a!=`object`||Array.isArray(a))return null;let o=a[k];return typeof o==`string`?o:null}function ve(e,t,n,r,i){for(let a of O){let o=C(e,a);l(o,{recursive:!0});let s=m(o),c=x(s,t);he(c,r,{restrictSymlinkTo:n});let u=m(C(n,`..`));ge({linkTarget:x(S(s,u),t),linkPath:c,copyFrom:n,mode:i})}}function L(e){return e instanceof Error&&typeof e.code==`string`}function ye(e,t){if(e===t)return!0;let n=(e,t)=>{let n=S(t,e);return n===``||n===`.`||!b(n)&&n!==`..`&&!n.startsWith(`..${w}`)};return n(e,t)||n(t,e)}const R=`SKILL.md`;function z(e){let t=[],n=[];try{let r;try{r=g(e)}catch(r){return H(r)&&(r.code===`ENOENT`||r.code===`ENOTDIR`)?n.push({path:e,reason:`missing-source`,message:`Source directory does not exist: ${e}`}):n.push({path:e,reason:`read-failed`,message:`Failed to stat source directory ${e}: ${V(r)}`}),{skills:t,errors:n}}if(!r.isDirectory())return n.push({path:e,reason:`missing-source`,message:`Source path is not a directory: ${e}`}),{skills:t,errors:n};let i=x(e,R),a=xe(i);if(a.kind===`error`)return n.push({path:e,reason:`read-failed`,message:`Failed to check ${i}: ${a.message}`}),{skills:t,errors:n};if(a.kind===`present`)return be(B(e,{enforceParentMatch:!1}),t,n),{skills:t,errors:n};let o=f(e,{withFileTypes:!0});for(let r of o){let i=x(e,r.name),a;try{a=g(i).isDirectory()}catch(e){if(H(e)&&e.code===`ENOENT`&&!r.isSymbolicLink())continue;n.push({path:i,reason:`read-failed`,message:r.isSymbolicLink()?`Dangling symlink at ${i}: ${V(e)}`:`Failed to stat ${i}: ${V(e)}`});continue}if(!a)continue;let o=x(i,R),s=xe(o);s.kind===`error`?n.push({path:i,reason:`read-failed`,message:`Failed to check ${o}: ${s.message}`}):s.kind!==`absent`&&be(B(i,{enforceParentMatch:!0}),t,n)}}catch(t){n.push({path:e,reason:`read-failed`,message:`Failed to scan ${e}: ${V(t)}`})}return t.sort((e,t)=>e.frontmatter.name<t.frontmatter.name?-1:+(e.frontmatter.name>t.frontmatter.name)),{skills:t,errors:n}}function B(e,t){let n=x(e,R),r;try{r=d(n,`utf-8`)}catch(t){return{path:e,reason:`read-failed`,message:`Failed to read ${n}: ${V(t)}`}}let{data:i,parseError:a}=E(r);if(a!==void 0)return{path:e,reason:`parse-failed`,message:`Invalid SKILL.md frontmatter in ${e}: YAML parse error: ${a}`};let o=ae(i);if(!o.success)return{path:e,reason:`parse-failed`,message:`Invalid SKILL.md frontmatter in ${e}: ${o.issues.map(e=>`${e.path.join(`.`)||`<root>`}: ${e.message}`).join(`; `)}`};if(t.enforceParentMatch){let t=v(e);if(t!==o.data.name)return{path:e,reason:`name-mismatch`,message:`Skill name "${o.data.name}" does not match directory "${t}"`,skillName:o.data.name}}return{frontmatter:o.data,sourcePath:e,rawContent:r}}function be(e,t,n){`frontmatter`in e?t.push(e):n.push(e)}function V(e){return e instanceof Error?e.message:String(e)}function H(e){return e instanceof Error&&typeof e.code==`string`}function xe(e){try{return c(e),{kind:`present`}}catch(e){return H(e)&&e.code===`ENOENT`?{kind:`absent`}:{kind:`error`,message:V(e)}}}function Se(e,t={}){let n=0,r=!1;for(let i of e)i.reason===`missing-source`||i.path===t.sourceDir?(r=!0,a.warn(`Failed to scan source directory ${i.path}: ${i.message}`)):(n+=1,a.warn(`Skipping skill at ${i.path}: ${i.message}`));t.silentStdout||(n>0&&a.info(`${i.warning} Skipped ${n} skill(s) due to scan errors (see warnings above).`),r&&a.info(`${i.warning} Source directory scan failed (see warnings above); subsequent operations may be skipped.`))}function U(e,t){let n=e.errors.some(e=>e.reason===`missing-source`||e.path===t),r=e.errors.length>0&&e.skills.length===0;return n||r}function W(e,t={}){let n=z(e.sourceDir);return Se(n.errors,{...t,sourceDir:e.sourceDir}),n}function Ce(e){let t={description:`Skill names to exclude from sync`};return e.excludeAlias!==void 0&&(t.alias=e.excludeAlias),t}function G(e){let t={description:`Print install paths and modes`};return e.verbose.alias!==void 0&&(t.alias=e.verbose.alias),t}function K(e,t){return!!e[t]}function we(t){function i(e,n){let{skills:r,errors:i}=W(t),o=t.stamp,s=new Set(r.map(e=>e.frontmatter.name)),c=new Set(Pe(o,t.cwd,t.sourceDir)),l=Array.from(new Set(e.exclude)).filter(e=>!s.has(e)&&!c.has(e));if(l.length>0){let e=l.length===1?`Skill`:`Skills`,t=l.map(e=>JSON.stringify(e)).join(`, `);throw Error(`--exclude: ${e} ${t} not found in source directory or among installed skills.\n`+J({source:r,installed:c}))}let u=new Set(e.exclude),d=r.filter(e=>!u.has(e.frontmatter.name)),f=U({skills:r,errors:i},t.sourceDir),p=0;if(!f){let e=new Set(d.map(e=>e.frontmatter.name)),n=/* @__PURE__ */ new Set;for(let e of i)e.path!==t.sourceDir&&(n.add(v(e.path)),e.skillName!==void 0&&n.add(e.skillName));for(let r of c)e.has(r)||u.has(r)||n.has(r)||(X(r,o,t.cwd,t.sourceDir),p+=1)}let m=0;for(let e of d)Y(e,o,t,n),m+=1;if(m===0&&p===0){let e=f?`source directory scan failed; see warnings`:r.length>0&&d.length===0?`all skills excluded`:`no skills bundled`;a.info(`No skills installed (${e}).`)}else a.info(`Sync complete: ${m} installed, ${p} removed.`)}return t.verbose.disabled?r({name:`sync`,description:t.descriptions.sync,args:n({exclude:e.stringArray(Ce(t))},{unknownKeys:t.unknownKeys}),run(e){i(e,K(e,`verbose`))}}):r({name:`sync`,description:t.descriptions.sync,args:n({exclude:e.stringArray(Ce(t)),verbose:e.boolean(G(t))},{unknownKeys:t.unknownKeys}),run(e){i(e,e.verbose)}})}function Te(t){let i={positional:!0,description:`Skill name(s) to install (default: all)`,placeholder:`NAME`};function o(e,n){let r=W(t),i=r.skills,o=t.stamp;if(e.name.length>0){let r=new Set(i.map(e=>e.frontmatter.name)),a=Array.from(new Set(e.name)),s=a.filter(e=>!r.has(e));if(s.length>0){let e=s.length===1?`Skill`:`Skills`,t=s.map(e=>JSON.stringify(e)).join(`, `);throw Error(`${e} ${t} not found in source directory.\n`+J({source:i}))}let c=new Set(a);for(let e of i)c.has(e.frontmatter.name)&&Y(e,o,t,n)}else if(i.length===0)U(r,t.sourceDir)?a.info(`No skills installed (source directory scan failed; see warnings).`):a.info(`No skills found in source directory.`);else for(let e of i)Y(e,o,t,n)}return t.verbose.disabled?r({name:t.commandNames.add.name,...t.commandNames.add.aliases.length>0?{aliases:t.commandNames.add.aliases}:{},description:t.descriptions.add,args:n({name:e.stringArray(i)},{unknownKeys:t.unknownKeys}),run(e){o(e,K(e,`verbose`))}}):r({name:t.commandNames.add.name,...t.commandNames.add.aliases.length>0?{aliases:t.commandNames.add.aliases}:{},description:t.descriptions.add,args:n({name:e.stringArray(i),verbose:e.boolean(G(t))},{unknownKeys:t.unknownKeys}),run(e){o(e,e.verbose)}})}function Ee(t){return r({name:t.commandNames.remove.name,...t.commandNames.remove.aliases.length>0?{aliases:t.commandNames.remove.aliases}:{},description:t.descriptions.remove,args:n({name:e.optionalString({positional:!0,description:`Skill name to remove (default: all)`,placeholder:`NAME`})},{unknownKeys:t.unknownKeys}),run(e){let n=W(t),r=n.skills,i=t.stamp;if(e.name){if(r.some(t=>t.frontmatter.name===e.name)&&Ae(r,e.name),!X(e.name,i,t.cwd,t.sourceDir)){if(q(e.name,t.cwd))a.info(`${e.name} is installed without a ${k} stamp this CLI recognises; refusing to remove. Remove .agents/skills/${e.name} manually if intended.`);else{let n=new Set(Pe(i,t.cwd,t.sourceDir));a.info(`${e.name} is not installed; nothing to remove.\n`+J({installed:n}))}}return}if(r.length===0){U(n,t.sourceDir)?a.info(`No skills found (source directory scan failed; see warnings); nothing to remove.`):a.info(`No skills found in source directory; nothing to remove.`);return}let o=0;for(let e of r)X(e.frontmatter.name,i,t.cwd,t.sourceDir)&&(o+=1);o===0&&a.info(`No installed skills owned by this CLI; nothing to remove.`)}})}function De(e,t,n,r){let i;try{i=I(e,n)}catch(t){return a.warn(`Failed to read ownership for installed skill ${e}: ${Oe(t)}`),`unreadable`}if(i===t)return`installed`;if(i!==null)return`foreign`;if(!F(e,n)){let t=C(n,D,e);return Q(t)&&Z(t,r)?`missing`:q(e,n)?`unstamped`:`not-installed`}return`unstamped`}function Oe(e){return e instanceof Error?e.message:String(e)}function q(e,t){try{return c(C(t,D,e)),!0}catch{return!1}}function ke(t){function i(e){let n=W(t,{silentStdout:e}),r=n.skills,i=t.stamp;if(e)console.log(JSON.stringify(r.map(e=>({name:e.frontmatter.name,description:e.frontmatter.description,owner:e.frontmatter.metadata?.[`politty-cli`]??null,expectedOwner:i,status:De(e.frontmatter.name,i,t.cwd,t.sourceDir),sourcePath:e.sourcePath}))));else if(r.length===0)U(n,t.sourceDir)?a.info(`Source directory scan failed; see warnings.`):a.info(`No skills found in source directory.`);else{a.info(`Available skills:`);for(let e of r){let n=De(e.frontmatter.name,i,t.cwd,t.sourceDir);a.info(` ${e.frontmatter.name.padEnd(20)} ${n.padEnd(14)} ${e.frontmatter.description}`)}}}return t.json.disabled?r({name:`list`,description:t.descriptions.list,args:n({},{unknownKeys:t.unknownKeys}),run(e){i(K(e,`json`))}}):r({name:`list`,description:t.descriptions.list,args:n({json:e.boolean({description:`Output as JSON`})},{unknownKeys:t.unknownKeys}),run(e){i(e.json)}})}function Ae(e,t){let n=e.find(e=>e.frontmatter.name===t);if(!n){let n=e.map(e=>e.frontmatter.name).join(`, `)||`<none>`;throw Error(`Skill "${t}" not found in source directory. Available: ${n}`)}return n}function J(e){let t=[];return e.source!==void 0&&t.push(` Source: ${e.source.map(e=>e.frontmatter.name).join(`, `)||`<none>`}`),e.installed!==void 0&&t.push(` Installed: ${[...e.installed].sort().join(`, `)||`<none>`}`),t.join(`
2
- `)}function Y(e,t,n,r){let o=e.frontmatter.name,s=n.cwd,c=n.mode,l=e.frontmatter.metadata?.[`politty-cli`]??null;if(l!==t)throw Error(`Refusing to install "${o}": source SKILL.md declares metadata.${k}=${JSON.stringify(l)}, expected ${JSON.stringify(t)}.`);let u=I(o,s);if(u!==null&&u!==t)throw Error(`Refusing to install "${o}": owned by ${JSON.stringify(u)}, not ${JSON.stringify(t)}. Check metadata.${k} in .agents/skills/${o}/SKILL.md.`);let d=C(s,D,o),f=Q(d)&&Z(d,n.sourceDir);if(u===null&&q(o,s)&&!f)throw Error(`Refusing to install "${o}": .agents/skills/${o} exists without a ${k} stamp, so it was not installed by this CLI. Remove it manually (or add the stamp to take ownership) before running "skills add".`);if(le(e,s,c===void 0?{}:{mode:c}),a.info(`${i.success} Installed ${o}`),r){let e=c??`symlink`;a.info(` mode=${e} path=${d}`)}}function X(e,t,n,r){let o=I(e,n);if(o===null)return je(e,n,r)?(a.info(`${i.success} Removed ${e} (broken symlink)`),!0):!1;if(o!==t)throw Error(`Refusing to remove "${e}": owned by ${JSON.stringify(o)}, not ${JSON.stringify(t)}. Check metadata.${k} in .agents/skills/${e}/SKILL.md.`);return fe(e,n,{expectedOwnership:t}),a.info(`${i.success} Removed ${e}`),!0}function je(e,t,n){let r=C(t,D,e);if(!Q(r)||!Z(r,n))return!1;for(let n of O){let i=C(t,n,e);Q(i)&&Ne(i,r)&&_(i)}return _(r),!0}function Z(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n),i=Me(C(t)),a=Me(r),o=S(i,a);return!(b(o)||o===`..`||o.startsWith(`..${w}`))}function Me(e){let t=e,n=[];for(;;)try{let e=m(t);return n.length===0?e:C(e,...n.reverse())}catch{let r=y(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[/\\]+/,``)),t=r}}function Ne(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n);if(r===t)return!0;try{return m(r)===m(t)}catch{return!1}}function Q(e){let t;try{t=c(e)}catch{return!1}return t.isSymbolicLink()?!s(e):!1}function Pe(e,t,n){let r=C(t,D),i=[],o;try{o=f(r,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`||a.warn(`Failed to enumerate ${r}: ${e instanceof Error?e.message:String(e)}`),i}for(let s of o){if(!s.isDirectory()&&!s.isSymbolicLink()||s.name.length<1||s.name.length>64||!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(s.name))continue;let o;try{o=I(s.name,t)}catch(e){a.warn(`Failed to read ownership for ${s.name}: ${e instanceof Error?e.message:String(e)}`);continue}if(o===e){i.push(s.name);continue}let c=C(r,s.name);o===null&&Q(c)&&Z(c,n)&&i.push(s.name)}return i}const Fe=[`add`,`install`],Ie=[`remove`,`uninstall`],$={skills:`Manage agent skills`,sync:`Remove and reinstall all skills from source`,add:`Install skills from source`,remove:`Remove installed skills`,list:`List available skills from source`},Le=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/,Re=[`.git`,`package.json`];function ze(e,t){return{sourceDir:e.sourceDir,package:e.package,mode:e.mode,cwd:Ve(e.cwd),excludeAlias:Ue(e.flags?.exclude?.alias),verbose:Ge(e.flags?.verbose,e.globalArgs),json:{disabled:Ke(e.globalArgs,`json`)},commandNames:{add:We(e.commandMap?.add,Fe,`add`),remove:We(e.commandMap?.remove,Ie,`remove`)},unknownKeys:e.unknownKeys??`strip`,descriptionAppend:qe(e.descriptionAppend,t),stamp:`${e.package}:${t}`,descriptions:Be(e.descriptions)}}function Be(e){return{skills:e?.skills??$.skills,sync:e?.sync??$.sync,add:e?.add??$.add,remove:e?.remove??$.remove,list:e?.list??$.list}}function Ve(e){if(e!==void 0)return C(e);let t=process.cwd();return He(t)??t}function He(e){let t=C(e);for(;;){for(let e of Re)if(s(C(t,e)))return t;let e=y(t);if(e===t)return null;t=e}}function Ue(e){if(e!==!1)return typeof e==`string`?e:`x`}function We(e,t,n){let r=e??t;if(r.length===0)throw Error(`SkillCommandOptions.commandMap.${n} must include at least one name.`);let i=r.find(e=>!Le.test(e));if(i!==void 0)throw Error(`SkillCommandOptions.commandMap.${n} contains an invalid entry ${JSON.stringify(i)}. Names/aliases must start with an alphanumeric character and contain only alphanumeric characters, hyphens, or underscores.`);return{name:r[0],aliases:r.slice(1)}}function Ge(e,t){return{alias:e?.alias===!1?void 0:e?.alias??`v`,disabled:Ke(t,`verbose`)}}function Ke(e,n){return e?t(e).fields.some(e=>e.name===n&&e.named&&e.type===`boolean`):!1}function qe(e,t){return e===!1?!1:typeof e==`string`?e:`Manage agent skills with \`${t} skills <add|sync|remove|list>\`.`}const Je=[`parse-failed`,`name-mismatch`,`read-failed`,`missing-source`];function Ye(e,t){if(e.subCommands&&Object.hasOwn(e.subCommands,`skills`))throw Error(`withSkillCommand: command "${e.name}" already defines a "skills" subcommand.`);let n=ze(t,e.name),i=n.commandNames.add.name,a=n.commandNames.remove.name,o=[`sync`,`list`,i,...n.commandNames.add.aliases,a,...n.commandNames.remove.aliases],s=o.find((e,t)=>o.indexOf(e)!==t);if(s)throw Error(`withSkillCommand: commandMap produced duplicate subcommand name/alias "${s}".`);let c=r({name:`skills`,description:n.descriptions.skills,subCommands:{sync:we(n),[i]:Te(n),[a]:Ee(n),list:ke(n)}});return{...e,description:Xe(e.description,n.descriptionAppend),subCommands:{...e.subCommands,skills:c}}}function Xe(e,t){return t===!1||t===``?e:e?e.endsWith(t)?e:`${e}\n\n${t}`:t}export{k as OWNERSHIP_METADATA_KEY,Je as SCAN_ERROR_REASONS,F as hasInstalledSkill,le as installSkill,E as parseFrontmatter,ce as parseSkillMd,I as readInstalledOwnership,z as scanSourceDir,fe as uninstallSkill,Ye as withSkillCommand};
1
+ import"./register-DsOawdf2.js";import{d as e,f as t,n}from"./schema-extractor-DL8vjWso.js";import{n as r}from"./command-BXsTrIgI.js";import{a as i,n as a}from"./logger-CoeDrmRr.js";import{copyFileSync as o,existsSync as s,lstatSync as c,mkdirSync as l,mkdtempSync as u,readFileSync as d,readdirSync as f,readlinkSync as p,realpathSync as m,renameSync as ee,rmSync as h,statSync as g,symlinkSync as te,unlinkSync as _}from"node:fs";import{basename as v,dirname as y,isAbsolute as b,join as x,parse as ne,relative as S,resolve as C,sep as w}from"node:path";import{parse as re}from"yaml";const ie=/^[a-z0-9]+(-[a-z0-9]+)*$/;function T(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function ae(e){let t=[],n=(n,r)=>{let i=e[n];i===void 0?r.required&&t.push({path:[n],message:`Invalid input: expected string, received undefined`}):typeof i==`string`?(r.min!==void 0&&i.length<r.min&&t.push({path:[n],message:`Too small: expected string to have >=${r.min} characters`}),r.max!==void 0&&i.length>r.max&&t.push({path:[n],message:`Too big: expected string to have <=${r.max} characters`})):t.push({path:[n],message:`Invalid input: expected string, received ${T(i)}`})};n(`name`,{required:!0,min:1,max:64}),typeof e.name==`string`&&!ie.test(e.name)&&t.push({path:[`name`],message:`name must be lowercase alphanumerics separated by single hyphens`}),n(`description`,{required:!0,min:1,max:1024}),n(`license`,{min:1}),n(`compatibility`,{max:500}),n(`allowed-tools`,{});let r=e.metadata;if(r!==void 0){if(typeof r!=`object`||!r||Array.isArray(r))t.push({path:[`metadata`],message:`Invalid input: expected record, received ${T(r)}`});else for(let[e,n]of Object.entries(r))typeof n!=`string`&&t.push({path:[`metadata`,e],message:`Invalid input: expected string, received ${T(n)}`})}return t.length>0?{success:!1,issues:t}:{success:!0,data:{...e}}}const oe=/^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/;function E(e){let t=e.match(oe);if(!t)return{data:{},body:e};let n=t[1],r=t[2];try{let e=re(n);return se(e)?{data:e,body:r}:{data:{},body:r}}catch(e){return{data:{},body:r,parseError:e instanceof Error?e.message:String(e)}}}function se(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ce(e){let{data:t,body:n}=E(e),r=ae(t);return r.success?{frontmatter:r.data,body:n,rawContent:e}:null}const D=`.agents/skills`,O=[`.claude/skills`],k=`politty-cli`;function A(e){if(e.length<1||e.length>64||!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e))throw Error(`Invalid skill name: ${JSON.stringify(e)}`)}function le(e,t=process.cwd(),n={}){let r=e.frontmatter.name;A(r);let i=n.mode??`symlink`,a=e.frontmatter.metadata?.[`politty-cli`]??null;if(i===`copy`&&a===null)throw Error(`Refusing to install "${e.frontmatter.name}" in copy mode without an ownership stamp. Add metadata.${k}="{package}:{cli}" to the source SKILL.md so subsequent installs can replace the copy in place.`);let o=C(t,D),s=m(e.sourcePath),c=ue(e.sourcePath),u=[x(M(o),r),...O.map(e=>x(M(C(t,e)),r))].find(e=>ye(e,s));if(u!==void 0)throw Error(`Refusing to install "${r}": source ${s} overlaps install destination ${u}. Choose a sourceDir outside .agents/skills/ and any agent-specific slot directory (e.g. .claude/skills/).`);if(i===`symlink`){let e=M(o);j(x(e,r),S(e,c));for(let n of O){let i=M(C(t,n));j(x(i,r),x(S(i,e),r))}}l(o,{recursive:!0});let d=m(o),f=x(d,r);he(f,a),ge({linkTarget:S(d,c),linkPath:f,copyFrom:s,mode:i}),ve(t,r,f,a,i)}function j(e,t){if(b(t))throw Error(`Refusing to write an absolute symlink target at ${e} → ${t}. The skill source and install root appear to live on different filesystem roots (e.g. different Windows drive letters); retry with mode: "copy".`)}function ue(e){let t=C(e),{root:n}=ne(t),r=t.slice(n.length).split(w).filter(e=>e!==``),i=n;for(let[e,t]of r.entries()){let n=x(i,t),a;try{a=c(n)}catch{return x(i,...r.slice(e))}if(a.isSymbolicLink()){if(de(i))return x(i,...r.slice(e));i=m(n)}else i=n}return i}function de(e){return v(e)===`node_modules`||v(e).startsWith(`@`)&&v(y(e))===`node_modules`}function M(e){let t=e,n=[];for(;;)try{let e=m(t);return n.length===0?e:C(e,...n.reverse())}catch{let r=y(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[/\\]+/,``)),t=r}}function fe(e,t=process.cwd(),n={}){A(e);let r=n.expectedOwnership??null,i=C(t,D,e);for(let n of O)me(C(t,n,e),r,{restrictSymlinkTo:i});me(i,r)}function pe(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n);if(r===t)return!0;try{return m(r)===m(t)}catch{return!1}}function me(e,t,n={}){let r;try{r=c(e)}catch(e){if(L(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return;throw e}if(r.isSymbolicLink()){if(n.restrictSymlinkTo!==void 0){pe(e,n.restrictSymlinkTo)&&_(e);return}(t===null||P(e)===t)&&_(e)}else r.isDirectory()&&t!==null&&P(e)===t&&h(e,{recursive:!0,force:!0})}function he(e,t,n={}){let r;try{r=c(e)}catch(e){if(L(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return;throw e}if(r.isSymbolicLink()){if(n.restrictSymlinkTo===void 0||pe(e,n.restrictSymlinkTo)){_(e);return}throw Error(`Refusing to replace symlink at ${e}: it does not route to this CLI's canonical slot (${n.restrictSymlinkTo}). Remove or migrate the foreign symlink before retrying.`)}if(r.isDirectory()&&t!==null&&P(e)===t)h(e,{recursive:!0,force:!0});else throw Error(`Refusing to replace non-symlink path at ${e}. This looks like a legacy or manual install; remove or migrate it before retrying.`)}function ge(e){let{linkTarget:t,linkPath:n,copyFrom:r,mode:i}=e;if(i===`copy`)_e(r,n);else{j(n,t);try{te(t,n,`dir`)}catch(e){let r=e instanceof Error?e.message:String(e);throw Error(`Failed to symlink ${n} → ${t}: ${r}. If this filesystem does not support symlinks (e.g. Windows without Developer Mode), retry with mode: "copy".`,{cause:e})}}}function _e(e,t){let n=u(`${t}.partial-`);try{N(e,n),ee(n,t)}catch(e){try{h(n,{recursive:!0,force:!0})}catch{}throw e}}function N(e,t,n=/* @__PURE__ */ new Set){let r=g(e);if(r.isDirectory()){let r=m(e);if(n.has(r))throw Error(`Refusing to recursively copy cyclic directory symlink at ${e} (resolves to ${r}, already on the copy stack).`);n.add(r);try{l(t,{recursive:!0});for(let r of f(e))N(x(e,r),x(t,r),n)}finally{n.delete(r)}}else r.isFile()&&o(e,t)}function P(e){let t;try{t=d(x(e,`SKILL.md`),`utf-8`)}catch(e){if(L(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return null;throw e}let{data:n}=E(t),r=n.metadata;if(!r||typeof r!=`object`||Array.isArray(r))return null;let i=r[k];return typeof i==`string`?i:null}function F(e,t=process.cwd()){return A(e),s(C(t,D,e,`SKILL.md`))}function I(e,t=process.cwd()){A(e);let n=C(t,D,e,`SKILL.md`),r;try{r=d(n,`utf-8`)}catch(e){if(L(e)&&(e.code===`ENOENT`||e.code===`ENOTDIR`))return null;throw e}let{data:i}=E(r),a=i.metadata;if(!a||typeof a!=`object`||Array.isArray(a))return null;let o=a[k];return typeof o==`string`?o:null}function ve(e,t,n,r,i){for(let a of O){let o=C(e,a);l(o,{recursive:!0});let s=m(o),c=x(s,t);he(c,r,{restrictSymlinkTo:n});let u=m(C(n,`..`));ge({linkTarget:x(S(s,u),t),linkPath:c,copyFrom:n,mode:i})}}function L(e){return e instanceof Error&&typeof e.code==`string`}function ye(e,t){if(e===t)return!0;let n=(e,t)=>{let n=S(t,e);return n===``||n===`.`||!b(n)&&n!==`..`&&!n.startsWith(`..${w}`)};return n(e,t)||n(t,e)}const R=`SKILL.md`;function z(e){let t=[],n=[];try{let r;try{r=g(e)}catch(r){return H(r)&&(r.code===`ENOENT`||r.code===`ENOTDIR`)?n.push({path:e,reason:`missing-source`,message:`Source directory does not exist: ${e}`}):n.push({path:e,reason:`read-failed`,message:`Failed to stat source directory ${e}: ${V(r)}`}),{skills:t,errors:n}}if(!r.isDirectory())return n.push({path:e,reason:`missing-source`,message:`Source path is not a directory: ${e}`}),{skills:t,errors:n};let i=x(e,R),a=xe(i);if(a.kind===`error`)return n.push({path:e,reason:`read-failed`,message:`Failed to check ${i}: ${a.message}`}),{skills:t,errors:n};if(a.kind===`present`)return be(B(e,{enforceParentMatch:!1}),t,n),{skills:t,errors:n};let o=f(e,{withFileTypes:!0});for(let r of o){let i=x(e,r.name),a;try{a=g(i).isDirectory()}catch(e){if(H(e)&&e.code===`ENOENT`&&!r.isSymbolicLink())continue;n.push({path:i,reason:`read-failed`,message:r.isSymbolicLink()?`Dangling symlink at ${i}: ${V(e)}`:`Failed to stat ${i}: ${V(e)}`});continue}if(!a)continue;let o=x(i,R),s=xe(o);s.kind===`error`?n.push({path:i,reason:`read-failed`,message:`Failed to check ${o}: ${s.message}`}):s.kind!==`absent`&&be(B(i,{enforceParentMatch:!0}),t,n)}}catch(t){n.push({path:e,reason:`read-failed`,message:`Failed to scan ${e}: ${V(t)}`})}return t.sort((e,t)=>e.frontmatter.name<t.frontmatter.name?-1:+(e.frontmatter.name>t.frontmatter.name)),{skills:t,errors:n}}function B(e,t){let n=x(e,R),r;try{r=d(n,`utf-8`)}catch(t){return{path:e,reason:`read-failed`,message:`Failed to read ${n}: ${V(t)}`}}let{data:i,parseError:a}=E(r);if(a!==void 0)return{path:e,reason:`parse-failed`,message:`Invalid SKILL.md frontmatter in ${e}: YAML parse error: ${a}`};let o=ae(i);if(!o.success)return{path:e,reason:`parse-failed`,message:`Invalid SKILL.md frontmatter in ${e}: ${o.issues.map(e=>`${e.path.join(`.`)||`<root>`}: ${e.message}`).join(`; `)}`};if(t.enforceParentMatch){let t=v(e);if(t!==o.data.name)return{path:e,reason:`name-mismatch`,message:`Skill name "${o.data.name}" does not match directory "${t}"`,skillName:o.data.name}}return{frontmatter:o.data,sourcePath:e,rawContent:r}}function be(e,t,n){`frontmatter`in e?t.push(e):n.push(e)}function V(e){return e instanceof Error?e.message:String(e)}function H(e){return e instanceof Error&&typeof e.code==`string`}function xe(e){try{return c(e),{kind:`present`}}catch(e){return H(e)&&e.code===`ENOENT`?{kind:`absent`}:{kind:`error`,message:V(e)}}}function Se(e,t={}){let n=0,r=!1;for(let i of e)i.reason===`missing-source`||i.path===t.sourceDir?(r=!0,a.warn(`Failed to scan source directory ${i.path}: ${i.message}`)):(n+=1,a.warn(`Skipping skill at ${i.path}: ${i.message}`));t.silentStdout||(n>0&&a.info(`${i.warning} Skipped ${n} skill(s) due to scan errors (see warnings above).`),r&&a.info(`${i.warning} Source directory scan failed (see warnings above); subsequent operations may be skipped.`))}function U(e,t){let n=e.errors.some(e=>e.reason===`missing-source`||e.path===t),r=e.errors.length>0&&e.skills.length===0;return n||r}function W(e,t={}){let n=z(e.sourceDir);return Se(n.errors,{...t,sourceDir:e.sourceDir}),n}function Ce(e){let t={description:`Skill names to exclude from sync`};return e.excludeAlias!==void 0&&(t.alias=e.excludeAlias),t}function G(e){let t={description:`Print install paths and modes`};return e.verbose.alias!==void 0&&(t.alias=e.verbose.alias),t}function K(e,t){return!!e[t]}function we(n){function i(e,t){let{skills:r,errors:i}=W(n),o=n.stamp,s=new Set(r.map(e=>e.frontmatter.name)),c=new Set(Pe(o,n.cwd,n.sourceDir)),l=Array.from(new Set(e.exclude)).filter(e=>!s.has(e)&&!c.has(e));if(l.length>0){let e=l.length===1?`Skill`:`Skills`,t=l.map(e=>JSON.stringify(e)).join(`, `);throw Error(`--exclude: ${e} ${t} not found in source directory or among installed skills.\n`+J({source:r,installed:c}))}let u=new Set(e.exclude),d=r.filter(e=>!u.has(e.frontmatter.name)),f=U({skills:r,errors:i},n.sourceDir),p=0;if(!f){let e=new Set(d.map(e=>e.frontmatter.name)),t=/* @__PURE__ */ new Set;for(let e of i)e.path!==n.sourceDir&&(t.add(v(e.path)),e.skillName!==void 0&&t.add(e.skillName));for(let r of c)e.has(r)||u.has(r)||t.has(r)||(X(r,o,n.cwd,n.sourceDir),p+=1)}let m=0;for(let e of d)Y(e,o,n,t),m+=1;if(m===0&&p===0){let e=f?`source directory scan failed; see warnings`:r.length>0&&d.length===0?`all skills excluded`:`no skills bundled`;a.info(`No skills installed (${e}).`)}else a.info(`Sync complete: ${m} installed, ${p} removed.`)}return n.verbose.disabled?r({name:`sync`,description:n.descriptions.sync,args:e({exclude:t.stringArray(Ce(n))},{unknownKeys:n.unknownKeys}),run(e){i(e,K(e,`verbose`))}}):r({name:`sync`,description:n.descriptions.sync,args:e({exclude:t.stringArray(Ce(n)),verbose:t.boolean(G(n))},{unknownKeys:n.unknownKeys}),run(e){i(e,e.verbose)}})}function Te(n){let i={positional:!0,description:`Skill name(s) to install (default: all)`,placeholder:`NAME`};function o(e,t){let r=W(n),i=r.skills,o=n.stamp;if(e.name.length>0){let r=new Set(i.map(e=>e.frontmatter.name)),a=Array.from(new Set(e.name)),s=a.filter(e=>!r.has(e));if(s.length>0){let e=s.length===1?`Skill`:`Skills`,t=s.map(e=>JSON.stringify(e)).join(`, `);throw Error(`${e} ${t} not found in source directory.\n`+J({source:i}))}let c=new Set(a);for(let e of i)c.has(e.frontmatter.name)&&Y(e,o,n,t)}else if(i.length===0)U(r,n.sourceDir)?a.info(`No skills installed (source directory scan failed; see warnings).`):a.info(`No skills found in source directory.`);else for(let e of i)Y(e,o,n,t)}return n.verbose.disabled?r({name:n.commandNames.add.name,...n.commandNames.add.aliases.length>0?{aliases:n.commandNames.add.aliases}:{},description:n.descriptions.add,args:e({name:t.stringArray(i)},{unknownKeys:n.unknownKeys}),run(e){o(e,K(e,`verbose`))}}):r({name:n.commandNames.add.name,...n.commandNames.add.aliases.length>0?{aliases:n.commandNames.add.aliases}:{},description:n.descriptions.add,args:e({name:t.stringArray(i),verbose:t.boolean(G(n))},{unknownKeys:n.unknownKeys}),run(e){o(e,e.verbose)}})}function Ee(n){return r({name:n.commandNames.remove.name,...n.commandNames.remove.aliases.length>0?{aliases:n.commandNames.remove.aliases}:{},description:n.descriptions.remove,args:e({name:t.optionalString({positional:!0,description:`Skill name to remove (default: all)`,placeholder:`NAME`})},{unknownKeys:n.unknownKeys}),run(e){let t=W(n),r=t.skills,i=n.stamp;if(e.name){if(r.some(t=>t.frontmatter.name===e.name)&&Ae(r,e.name),!X(e.name,i,n.cwd,n.sourceDir)){if(q(e.name,n.cwd))a.info(`${e.name} is installed without a ${k} stamp this CLI recognises; refusing to remove. Remove .agents/skills/${e.name} manually if intended.`);else{let t=new Set(Pe(i,n.cwd,n.sourceDir));a.info(`${e.name} is not installed; nothing to remove.\n`+J({installed:t}))}}return}if(r.length===0){U(t,n.sourceDir)?a.info(`No skills found (source directory scan failed; see warnings); nothing to remove.`):a.info(`No skills found in source directory; nothing to remove.`);return}let o=0;for(let e of r)X(e.frontmatter.name,i,n.cwd,n.sourceDir)&&(o+=1);o===0&&a.info(`No installed skills owned by this CLI; nothing to remove.`)}})}function De(e,t,n,r){let i;try{i=I(e,n)}catch(t){return a.warn(`Failed to read ownership for installed skill ${e}: ${Oe(t)}`),`unreadable`}if(i===t)return`installed`;if(i!==null)return`foreign`;if(!F(e,n)){let t=C(n,D,e);return Q(t)&&Z(t,r)?`missing`:q(e,n)?`unstamped`:`not-installed`}return`unstamped`}function Oe(e){return e instanceof Error?e.message:String(e)}function q(e,t){try{return c(C(t,D,e)),!0}catch{return!1}}function ke(n){function i(e){let t=W(n,{silentStdout:e}),r=t.skills,i=n.stamp;if(e)console.log(JSON.stringify(r.map(e=>({name:e.frontmatter.name,description:e.frontmatter.description,owner:e.frontmatter.metadata?.[`politty-cli`]??null,expectedOwner:i,status:De(e.frontmatter.name,i,n.cwd,n.sourceDir),sourcePath:e.sourcePath}))));else if(r.length===0)U(t,n.sourceDir)?a.info(`Source directory scan failed; see warnings.`):a.info(`No skills found in source directory.`);else{a.info(`Available skills:`);for(let e of r){let t=De(e.frontmatter.name,i,n.cwd,n.sourceDir);a.info(` ${e.frontmatter.name.padEnd(20)} ${t.padEnd(14)} ${e.frontmatter.description}`)}}}return n.json.disabled?r({name:`list`,description:n.descriptions.list,args:e({},{unknownKeys:n.unknownKeys}),run(e){i(K(e,`json`))}}):r({name:`list`,description:n.descriptions.list,args:e({json:t.boolean({description:`Output as JSON`})},{unknownKeys:n.unknownKeys}),run(e){i(e.json)}})}function Ae(e,t){let n=e.find(e=>e.frontmatter.name===t);if(!n){let n=e.map(e=>e.frontmatter.name).join(`, `)||`<none>`;throw Error(`Skill "${t}" not found in source directory. Available: ${n}`)}return n}function J(e){let t=[];return e.source!==void 0&&t.push(` Source: ${e.source.map(e=>e.frontmatter.name).join(`, `)||`<none>`}`),e.installed!==void 0&&t.push(` Installed: ${[...e.installed].sort().join(`, `)||`<none>`}`),t.join(`
2
+ `)}function Y(e,t,n,r){let o=e.frontmatter.name,s=n.cwd,c=n.mode,l=e.frontmatter.metadata?.[`politty-cli`]??null;if(l!==t)throw Error(`Refusing to install "${o}": source SKILL.md declares metadata.${k}=${JSON.stringify(l)}, expected ${JSON.stringify(t)}.`);let u=I(o,s);if(u!==null&&u!==t)throw Error(`Refusing to install "${o}": owned by ${JSON.stringify(u)}, not ${JSON.stringify(t)}. Check metadata.${k} in .agents/skills/${o}/SKILL.md.`);let d=C(s,D,o),f=Q(d)&&Z(d,n.sourceDir);if(u===null&&q(o,s)&&!f)throw Error(`Refusing to install "${o}": .agents/skills/${o} exists without a ${k} stamp, so it was not installed by this CLI. Remove it manually (or add the stamp to take ownership) before running "skills add".`);if(le(e,s,c===void 0?{}:{mode:c}),a.info(`${i.success} Installed ${o}`),r){let e=c??`symlink`;a.info(` mode=${e} path=${d}`)}}function X(e,t,n,r){let o=I(e,n);if(o===null)return je(e,n,r)?(a.info(`${i.success} Removed ${e} (broken symlink)`),!0):!1;if(o!==t)throw Error(`Refusing to remove "${e}": owned by ${JSON.stringify(o)}, not ${JSON.stringify(t)}. Check metadata.${k} in .agents/skills/${e}/SKILL.md.`);return fe(e,n,{expectedOwnership:t}),a.info(`${i.success} Removed ${e}`),!0}function je(e,t,n){let r=C(t,D,e);if(!Q(r)||!Z(r,n))return!1;for(let n of O){let i=C(t,n,e);Q(i)&&Ne(i,r)&&_(i)}return _(r),!0}function Z(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n),i=Me(C(t)),a=Me(r),o=S(i,a);return!(b(o)||o===`..`||o.startsWith(`..${w}`))}function Me(e){let t=e,n=[];for(;;)try{let e=m(t);return n.length===0?e:C(e,...n.reverse())}catch{let r=y(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[/\\]+/,``)),t=r}}function Ne(e,t){let n;try{n=p(e)}catch{return!1}let r=b(n)?n:C(y(e),n);if(r===t)return!0;try{return m(r)===m(t)}catch{return!1}}function Q(e){let t;try{t=c(e)}catch{return!1}return t.isSymbolicLink()?!s(e):!1}function Pe(e,t,n){let r=C(t,D),i=[],o;try{o=f(r,{withFileTypes:!0})}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`||a.warn(`Failed to enumerate ${r}: ${e instanceof Error?e.message:String(e)}`),i}for(let s of o){if(!s.isDirectory()&&!s.isSymbolicLink()||s.name.length<1||s.name.length>64||!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(s.name))continue;let o;try{o=I(s.name,t)}catch(e){a.warn(`Failed to read ownership for ${s.name}: ${e instanceof Error?e.message:String(e)}`);continue}if(o===e){i.push(s.name);continue}let c=C(r,s.name);o===null&&Q(c)&&Z(c,n)&&i.push(s.name)}return i}const Fe=[`add`,`install`],Ie=[`remove`,`uninstall`],$={skills:`Manage agent skills`,sync:`Remove and reinstall all skills from source`,add:`Install skills from source`,remove:`Remove installed skills`,list:`List available skills from source`},Le=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/,Re=[`.git`,`package.json`];function ze(e,t){return{sourceDir:e.sourceDir,package:e.package,mode:e.mode,cwd:Ve(e.cwd),excludeAlias:Ue(e.flags?.exclude?.alias),verbose:Ge(e.flags?.verbose,e.globalArgs),json:{disabled:Ke(e.globalArgs,`json`)},commandNames:{add:We(e.commandMap?.add,Fe,`add`),remove:We(e.commandMap?.remove,Ie,`remove`)},unknownKeys:e.unknownKeys??`strip`,descriptionAppend:qe(e.descriptionAppend,t),stamp:`${e.package}:${t}`,descriptions:Be(e.descriptions)}}function Be(e){return{skills:e?.skills??$.skills,sync:e?.sync??$.sync,add:e?.add??$.add,remove:e?.remove??$.remove,list:e?.list??$.list}}function Ve(e){if(e!==void 0)return C(e);let t=process.cwd();return He(t)??t}function He(e){let t=C(e);for(;;){for(let e of Re)if(s(C(t,e)))return t;let e=y(t);if(e===t)return null;t=e}}function Ue(e){if(e!==!1)return typeof e==`string`?e:`x`}function We(e,t,n){let r=e??t;if(r.length===0)throw Error(`SkillCommandOptions.commandMap.${n} must include at least one name.`);let i=r.find(e=>!Le.test(e));if(i!==void 0)throw Error(`SkillCommandOptions.commandMap.${n} contains an invalid entry ${JSON.stringify(i)}. Names/aliases must start with an alphanumeric character and contain only alphanumeric characters, hyphens, or underscores.`);return{name:r[0],aliases:r.slice(1)}}function Ge(e,t){return{alias:e?.alias===!1?void 0:e?.alias??`v`,disabled:Ke(t,`verbose`)}}function Ke(e,t){return e?n(e).fields.some(e=>e.name===t&&e.named&&e.type===`boolean`):!1}function qe(e,t){return e===!1?!1:typeof e==`string`?e:`Manage agent skills with \`${t} skills <add|sync|remove|list>\`.`}const Je=[`parse-failed`,`name-mismatch`,`read-failed`,`missing-source`];function Ye(e,t){if(e.subCommands&&Object.hasOwn(e.subCommands,`skills`))throw Error(`withSkillCommand: command "${e.name}" already defines a "skills" subcommand.`);let n=ze(t,e.name),i=n.commandNames.add.name,a=n.commandNames.remove.name,o=[`sync`,`list`,i,...n.commandNames.add.aliases,a,...n.commandNames.remove.aliases],s=o.find((e,t)=>o.indexOf(e)!==t);if(s)throw Error(`withSkillCommand: commandMap produced duplicate subcommand name/alias "${s}".`);let c=r({name:`skills`,description:n.descriptions.skills,subCommands:{sync:we(n),[i]:Te(n),[a]:Ee(n),list:ke(n)}});return{...e,description:Xe(e.description,n.descriptionAppend),subCommands:{...e.subCommands,skills:c}}}function Xe(e,t){return t===!1||t===``?e:e?e.endsWith(t)?e:`${e}\n\n${t}`:t}export{k as OWNERSHIP_METADATA_KEY,Je as SCAN_ERROR_REASONS,F as hasInstalledSkill,le as installSkill,E as parseFrontmatter,ce as parseSkillMd,I as readInstalledOwnership,z as scanSourceDir,fe as uninstallSkill,Ye as withSkillCommand};
@@ -1,5 +1,4 @@
1
- import { t as AgentInfo } from "./detect-agent-EHaSY1KW.js";
2
- //#region ../core/src/adapter/standard-schema.d.ts
1
+ import { t as AgentInfo } from "./detect-agent-hU93hctO.js";
3
2
  /**
4
3
  * Type-level subset of the Standard Schema V1 interface
5
4
  * (https://standardschema.dev), vendored so `@politty/core` can constrain
@@ -44,8 +43,6 @@ interface SchemaLike<Output = unknown> {
44
43
  }
45
44
  /** Infer the output type of a {@link SchemaLike}. */
46
45
  type InferSchemaOutput<S> = S extends SchemaLike ? NonNullable<S["~standard"]["types"]>["output"] : never;
47
- //#endregion
48
- //#region ../core/src/package-requirements.d.ts
49
46
  interface PackageRequirement<TArgs = unknown> {
50
47
  name: string;
51
48
  install?: string | undefined;
@@ -54,8 +51,6 @@ interface PackageRequirement<TArgs = unknown> {
54
51
  when?: ((args: TArgs) => boolean) | undefined;
55
52
  }
56
53
  declare function loadPackage<TModule = unknown>(requirement: Pick<PackageRequirement, "name" | "install" | "from">): Promise<TModule>;
57
- //#endregion
58
- //#region ../core/src/core/dynamic-completion-types.d.ts
59
54
  /**
60
55
  * Types for in-process dynamic value completion.
61
56
  *
@@ -111,8 +106,6 @@ interface DynamicCompletionResult {
111
106
  directive?: CompletionDirectiveMask;
112
107
  }
113
108
  type DynamicCompletionResolver = (ctx: DynamicCompletionContext) => DynamicCompletionResult | Promise<DynamicCompletionResult>;
114
- //#endregion
115
- //#region ../core/src/core/expand-completion-types.d.ts
116
109
  /**
117
110
  * Types for "expand" completion — candidates that depend on sibling arg
118
111
  * values.
@@ -157,8 +150,6 @@ interface ExpandCompletion {
157
150
  dependsOn: readonly string[];
158
151
  enumerate: (deps: Readonly<Record<string, string>>) => ReadonlyArray<string | ExpandCandidate>;
159
152
  }
160
- //#endregion
161
- //#region ../core/src/core/arg-registry.d.ts
162
153
  /**
163
154
  * Built-in completion types
164
155
  */
@@ -245,6 +236,15 @@ type CompletionMeta = {
245
236
  * - "directory": directory path input (inherited from completion type)
246
237
  */
247
238
  type PromptType = "text" | "password" | "confirm" | "select" | "file" | "directory";
239
+ interface PromptChoicesContext {
240
+ rawArgs: Readonly<Record<string, unknown>>;
241
+ globalArgs: Readonly<Record<string, unknown>>;
242
+ }
243
+ type PromptChoices = Array<string | {
244
+ label: string;
245
+ value: string;
246
+ }>;
247
+ type PromptChoicesResolver = (context: PromptChoicesContext) => PromptChoices | Promise<PromptChoices>;
248
248
  /**
249
249
  * Prompt metadata for interactive input when a value is missing.
250
250
  * Used by the `politty/prompt` module to request user input for unresolved arguments.
@@ -273,10 +273,7 @@ interface PromptMeta {
273
273
  /** Explicit prompt type. Overrides auto-detection from schema/completion. */
274
274
  type?: PromptType;
275
275
  /** Choices for select prompt. Overrides enum values from schema. */
276
- choices?: Array<string | {
277
- label: string;
278
- value: string;
279
- }>;
276
+ choices?: PromptChoices | PromptChoicesResolver;
280
277
  /** Whether to enable prompting for this field (default: true when prompt is set) */
281
278
  enabled?: boolean;
282
279
  }
@@ -539,8 +536,38 @@ interface ArgFn<TSchemaBase extends SchemaLike = SchemaLike> {
539
536
  <T extends TSchemaBase>(schema: T): T;
540
537
  <T extends TSchemaBase, M extends ArgMeta<InferSchemaOutput<T>>>(schema: T, meta: ValidateArgMeta<M, InferSchemaOutput<T>>): T;
541
538
  }
542
- //#endregion
543
- //#region ../core/src/adapter/field-meta.d.ts
539
+ type UnflattenOptions = {
540
+ readonly style?: "dot";
541
+ } | {
542
+ readonly style: "kebab" | "camel";
543
+ readonly prefixes: readonly string[];
544
+ };
545
+ type PrefixRest<K, St, H extends string> = St extends "kebab" ? K extends `${H}-${infer R}` ? R : never : K extends `${H}${infer C}${infer R}` ? C extends Lowercase<C> ? never : `${Lowercase<C>}${R}` : never;
546
+ type MatchingPrefixes<K, St, P extends string> = P extends unknown ? [PrefixRest<K, St, P>] extends [never] ? never : P : never;
547
+ type ShortestPrefix<M extends string, St, All extends string = M> = M extends unknown ? [MatchingPrefixes<M, St, Exclude<All, M>>] extends [never] ? M : never : never;
548
+ type KeyHead<K, St, P extends string> = St extends "dot" ? K extends `${infer H}.${string}` ? H : never : ShortestPrefix<MatchingPrefixes<K, St, P>, St>;
549
+ type KeyRest<K, St, H extends string> = St extends "dot" ? K extends `${H}.${infer R}` ? R : never : PrefixRest<K, St, H>;
550
+ type UnflattenGroup<T, St, P extends string, H extends string> = { [K in keyof T as [KeyHead<K, St, P>] extends [H] ? KeyRest<K, St, H> : never]: T[K]; };
551
+ type UnflattenHeads<T, St, P extends string> = { [K in keyof T]-?: KeyHead<K, St, P>; }[keyof T];
552
+ type StringKeys<T> = { [K in keyof T as K extends number ? `${K}` : K]: T[K]; };
553
+ type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
554
+ type HasPatternKey<T> = true extends { [K in keyof T]-?: object extends Record<K, 1> ? true : false; }[keyof T] ? true : false;
555
+ type UnflattenLevel<T, St, P extends string> = HasPatternKey<T> extends true ? Record<string, unknown> : UnflattenKeys<StringKeys<T>, St, P>;
556
+ type UnflattenKeys<T, St, P extends string> = (UnflattenHeads<T, St, P> extends (infer Heads extends string) ? { [K in keyof T as K extends symbol ? never : [KeyHead<K, St, P>] extends [never] ? K extends Heads ? never : K : never]: T[K]; } & { [H in Heads & keyof T]?: unknown; } & { [H in Exclude<Heads, keyof T> as object extends UnflattenGroup<T, St, P, H & string> ? never : H]: UnflattenLevel<UnflattenGroup<T, St, P, H & string>, St, PrefixRest<P, St, H & string>>; } & { [H in Exclude<Heads, keyof T> as object extends UnflattenGroup<T, St, P, H & string> ? H : never]?: UnflattenLevel<UnflattenGroup<T, St, P, H & string>, St, PrefixRest<P, St, H & string>>; } : never) extends (infer X) ? { [K in keyof X]: X[K]; } : never;
557
+ type UnflattenPrefixed<T, St, A extends readonly string[]> = A extends unknown ? number extends A["length"] ? Record<string, unknown> : string extends A[number] ? Record<string, unknown> : true extends { [I in keyof A]: IsUnion<A[I]>; }[number] ? Record<string, unknown> : UnflattenLevel<T, St, A[number]> : never;
558
+ type UnflattenWith<T, O> = O extends unknown ? (O extends {
559
+ readonly style?: infer St;
560
+ } ? St : "dot") extends (infer St) ? St extends "kebab" | "camel" ? O extends {
561
+ readonly prefixes: infer A extends readonly string[];
562
+ } ? UnflattenPrefixed<T, St, A> : Record<string, unknown> : UnflattenLevel<T, "dot", never> : never : never;
563
+ /** The nested output type of a flat record `T` under the given options */
564
+ type Unflatten<T, O extends UnflattenOptions = {
565
+ style: "dot";
566
+ }> = T extends unknown ? UnflattenWith<T, O> : never;
567
+ /** Where a flat field's value sits in the nested output */
568
+ interface NestedFieldInfo {
569
+ path: readonly string[];
570
+ }
544
571
  /**
545
572
  * Resolved metadata for an argument field
546
573
  */
@@ -619,6 +646,11 @@ interface ResolvedFieldMeta {
619
646
  negationDescription?: string | undefined;
620
647
  /** Side-effect callback from arg() metadata */
621
648
  effect?: ((value: unknown, context: EffectContext) => void | PromiseLike<void>) | undefined;
649
+ /**
650
+ * Where the validated value sits when the schema was wrapped by an
651
+ * `unflatten` helper, which nests its output while the field name stays flat.
652
+ */
653
+ nested?: NestedFieldInfo | undefined;
622
654
  }
623
655
  /**
624
656
  * Extracted fields from a schema
@@ -677,8 +709,6 @@ declare function toKebabCase(str: string): string;
677
709
  * @example toCamelCase("dryRun") => "dryRun"
678
710
  */
679
711
  declare function toCamelCase(str: string): string;
680
- //#endregion
681
- //#region ../core/src/lazy.d.ts
682
712
  /**
683
713
  * A lazily-loaded command that carries synchronous metadata for
684
714
  * static analysis (completion, help) while deferring full module
@@ -722,8 +752,6 @@ declare function isLazyCommand(value: unknown): value is LazyCommand;
722
752
  * ```
723
753
  */
724
754
  declare function lazy<T extends AnyCommand>(meta: T, load: () => Promise<AnyCommand>): LazyCommand<T>;
725
- //#endregion
726
- //#region ../core/src/types.d.ts
727
755
  /**
728
756
  * Global args interface for declaration merging (Pattern 3).
729
757
  * Users can extend this interface to add global options to all commands:
@@ -743,10 +771,11 @@ type IsEmpty<T> = keyof T extends never ? true : false;
743
771
  * Where a resolved arg value came from:
744
772
  * - `"cli"`: an explicit CLI token (flag or positional)
745
773
  * - `"env"`: `field.env` fallback (no CLI token was provided)
746
- * - `"default"`: neither of the above (e.g. a schema default, or a value
747
- * resolved by a `prompt` handler)
774
+ * - `"prompt"`: answered by a `prompt` resolver, whether returned or written
775
+ * into its `rawArgs` in place
776
+ * - `"default"`: none of the above (e.g. a schema default)
748
777
  */
749
- type ArgSource = "cli" | "env" | "default";
778
+ type ArgSource = "cli" | "env" | "prompt" | "default";
750
779
  /**
751
780
  * Identifies the CLI name a command was invoked with in the current run.
752
781
  * - `name`: the literal token typed on the CLI to reach this command
@@ -822,6 +851,19 @@ interface GlobalCleanupContext {
822
851
  agent?: AgentInfo | undefined;
823
852
  /** Error if command execution failed */
824
853
  error?: Error | undefined;
854
+ /**
855
+ * Validated global option values recovered when the run failed before the
856
+ * global effects ran (an unknown flag, an invalid value, a failed local
857
+ * validation). A value that fails its own validation is dropped, so the
858
+ * schema's default applies where it defines one. `$source` reports where
859
+ * each value came from. Undefined when the run did not fail that way, no
860
+ * `globalArgs` schema is set, a required global value is missing, or
861
+ * recovering the values throws. A failed `setup` runs before any argument is
862
+ * parsed, so it passes none.
863
+ */
864
+ globalArgs?: (Readonly<IsEmpty<GlobalArgs> extends true ? Record<string, unknown> : GlobalArgs> & {
865
+ $source?: (name: string) => ArgSource;
866
+ }) | undefined;
825
867
  }
826
868
  /**
827
869
  * Context passed to a function-form {@link AgentHelp}
@@ -942,12 +984,19 @@ type SubCommandValue = AnyCommand | (() => Promise<AnyCommand>) | LazyCommand;
942
984
  * Record of subcommands indexed by name
943
985
  */
944
986
  type SubCommandsRecord = Record<string, SubCommandValue>;
987
+ /**
988
+ * Shared-argument context passed from the runner to a {@link PromptResolver}.
989
+ */
990
+ interface PromptResolverContext {
991
+ /** Validated global args for command prompts, or values resolved so far for global prompts */
992
+ globalArgs: Record<string, unknown>;
993
+ }
945
994
  /**
946
995
  * Async callback to resolve missing argument values interactively.
947
996
  * Called after env fallback, before schema validation.
948
997
  * Provided by adapter subpath modules (e.g. `politty/prompt/clack`).
949
998
  */
950
- type PromptResolver = (rawArgs: Record<string, unknown>, extracted: ExtractedFields) => Promise<Record<string, unknown>>;
999
+ type PromptResolver = (rawArgs: Record<string, unknown>, extracted: ExtractedFields, context?: PromptResolverContext) => Promise<Record<string, unknown>>;
951
1000
  /**
952
1001
  * Options for runMain (CLI entry point)
953
1002
  */
@@ -958,7 +1007,11 @@ interface MainOptions {
958
1007
  debug?: boolean;
959
1008
  /** Capture console and process.stdout/stderr output during execution (default: false) */
960
1009
  captureLogs?: boolean;
961
- /** Skip command definition validation (useful in production where tests already verified) */
1010
+ /**
1011
+ * Skip command definition validation (useful in production where tests already verified).
1012
+ * A field declared in both `globalArgs` and a command's `args` is then not rejected, and
1013
+ * the command's value wins.
1014
+ */
962
1015
  skipValidation?: boolean;
963
1016
  /** Custom logger for output (default: console) */
964
1017
  logger?: Logger;
@@ -1041,7 +1094,11 @@ interface RunCommandOptions {
1041
1094
  debug?: boolean;
1042
1095
  /** Capture console and process.stdout/stderr output during execution (default: false) */
1043
1096
  captureLogs?: boolean;
1044
- /** Skip command definition validation (useful in production where tests already verified) */
1097
+ /**
1098
+ * Skip command definition validation (useful in production where tests already verified).
1099
+ * A field declared in both `globalArgs` and a command's `args` is then not rejected, and
1100
+ * the command's value wins.
1101
+ */
1045
1102
  skipValidation?: boolean;
1046
1103
  /** Custom logger for output (default: console) */
1047
1104
  logger?: Logger;
@@ -1131,5 +1188,4 @@ interface RunResultFailure {
1131
1188
  * Result of command execution (discriminated union)
1132
1189
  */
1133
1190
  type RunResult<T = unknown> = RunResultSuccess<T> | RunResultFailure;
1134
- //#endregion
1135
- export { DynamicCompletionCandidate as $, SubCommandsRecord as A, ArgFn as B, RunInvocation as C, RunnableCommand as D, RunResultSuccess as E, ExtractedFields as F, EffectContext as G, CompletionMeta as H, ResolvedFieldMeta as I, ValidateArgMeta as J, PromptMeta as K, UnknownKeysMode as L, LazyCommand as M, isLazyCommand as N, SetupContext as O, lazy as P, CompletionDirectiveMask as Q, toCamelCase as R, RunCommandOptions as S, RunResultFailure as T, CompletionType as U, ArgMeta as V, CustomCompletion as W, ExpandCompletion as X, ExpandCandidate as Y, ResolvedExpandCandidate as Z, LogStream as _, ArgsSchema as a, InferSchemaOutput as at, NonRunnableCommand as b, Command as c, GlobalArgs as d, DynamicCompletionContext as et, GlobalCleanupContext as f, LogLevel as g, LogEntry as h, ArgSource as i, loadPackage as it, UnknownSubcommandHandler as j, SubCommandValue as k, CommandBase as l, IsEmpty as m, AgentHelpContext as n, DynamicCompletionResult as nt, CleanupContext as o, SchemaLike as ot, GlobalSetupContext as p, PromptType as q, AnyCommand as r, PackageRequirement as rt, CollectedLogs as s, AgentHelp as t, DynamicCompletionResolver as tt, Example as u, Logger as v, RunResult as w, PromptResolver as x, MainOptions as y, toKebabCase as z };
1191
+ export { PromptType as $, SubCommandValue as A, toKebabCase as B, RunCommandOptions as C, RunResultSuccess as D, RunResultFailure as E, lazy as F, CompletionMeta as G, UnflattenOptions as H, ExtractedFields as I, EffectContext as J, CompletionType as K, ResolvedFieldMeta as L, UnknownSubcommandHandler as M, LazyCommand as N, RunnableCommand as O, isLazyCommand as P, PromptMeta as Q, UnknownKeysMode as R, PromptResolverContext as S, RunResult as T, ArgFn as U, Unflatten as V, ArgMeta as W, PromptChoicesContext as X, PromptChoices as Y, PromptChoicesResolver as Z, LogStream as _, ArgsSchema as a, DynamicCompletionCandidate as at, NonRunnableCommand as b, Command as c, DynamicCompletionResult as ct, GlobalArgs as d, InferSchemaOutput as dt, ValidateArgMeta as et, GlobalCleanupContext as f, SchemaLike as ft, LogLevel as g, LogEntry as h, ArgSource as i, CompletionDirectiveMask as it, SubCommandsRecord as j, SetupContext as k, CommandBase as l, PackageRequirement as lt, IsEmpty as m, AgentHelpContext as n, ExpandCompletion as nt, CleanupContext as o, DynamicCompletionContext as ot, GlobalSetupContext as p, CustomCompletion as q, AnyCommand as r, ResolvedExpandCandidate as rt, CollectedLogs as s, DynamicCompletionResolver as st, AgentHelp as t, ExpandCandidate as tt, Example as u, loadPackage as ut, Logger as v, RunInvocation as w, PromptResolver as x, MainOptions as y, toCamelCase as z };
@@ -1 +1 @@
1
- let e;function t(t){e=t}function n(){if(!e)throw Error('No validator adapter registered. Import politty through an adapter package (e.g. `import { defineCommand } from "@politty/zod"` or `from "politty"`) so the schema library integration is set up.');return e}const r=/* @__PURE__ */ new Set([`help`,`help-all`,`help-json`,`version`]);function i(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}function a(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function o(e){return!e.alias&&!e.hiddenAlias?[]:[...e.alias??[],...e.hiddenAlias??[]]}function s(e,t){let n=t.argMeta,a=n?.description??t.description,o=i(e),s=/^[A-Za-z0-9][A-Za-z0-9-]*$/,c=(t,n)=>{if(t==null)return;let r=(Array.isArray(t)?t:[t]).map(t=>{if(typeof t!=`string`)throw Error(`Invalid ${n} for field "${e}": expected string or string[], received ${typeof t}.`);let r=t.trim().replace(/^-+/,``);if(r.length===0||!s.test(r))throw Error(`Invalid ${n} "${t}" for field "${e}": aliases must match ${s}.`);return r}),i=Array.from(new Set(r));return i.length>0?i:void 0},l=c(n?.alias,`alias`),u=new Set(l??[]),d=c(n?.hiddenAlias,`hiddenAlias`)?.filter(e=>!u.has(e)),f=d&&d.length>0?d:void 0,p=t.type,m=n?.negation,h;if(m!=null){if(typeof m==`boolean`){if(p!==`boolean`)throw Error(`Invalid negation for field "${e}": negation can only be used on boolean fields.`);h=m}else{if(typeof m!=`string`)throw Error(`Invalid negation for field "${e}": expected string or boolean, received ${typeof m}.`);let t=m.trim().replace(/^-+/,``);if(t.length===0||!s.test(t))throw Error(`Invalid negation "${m}" for field "${e}": negation names must match ${s}.`);if(r.has(t))throw Error(`Invalid negation "${m}" for field "${e}": negation cannot use reserved built-in flag names (${[...r].map(e=>`--${e}`).join(`, `)}).`);if(p!==`boolean`)throw Error(`Invalid negation for field "${e}": negation can only be used on boolean fields.`);h=t}}let g=n?.negationDescription,_;if(g!=null){if(typeof g!=`string`)throw Error(`Invalid negationDescription for field "${e}": expected string, received ${typeof g}.`);if(h===!1)throw Error(`Invalid negationDescription for field "${e}": negationDescription cannot be used when negation is false.`);if(h===void 0)throw Error(`Invalid negationDescription for field "${e}": negationDescription requires \`negation\` to be set (string or true).`);let t=g.trim();if(t.length===0)throw Error(`Invalid negationDescription for field "${e}": negationDescription must be a non-empty string.`);_=t}let v=typeof h==`string`?h:h===!0?`no-${o}`:void 0,y=n?.positional,b={name:e,cliName:o,alias:l,hiddenAlias:f,description:a,positional:y!==void 0&&y!==!1,named:typeof y==`object`?y.named===!0:y!==!0,placeholder:n?.placeholder,env:n?.env,required:t.required,defaultValue:t.defaultValue,type:p,schema:t.schema,enumValues:t.enumValues,completion:n?.completion,prompt:n?.prompt,negation:h,negationDisplay:v,negationDescription:_,effect:n?.effect,requiredPackages:n?.requiredPackages};return n&&`overrideBuiltinAlias`in n&&n.overrideBuiltinAlias===!0&&(b.overrideBuiltinAlias=!0),b}export{i as a,a as i,o as n,n as o,s as r,t as s,r as t};
1
+ let e;function t(t){e=t}function n(){if(!e)throw Error('No validator adapter registered. Import politty through an adapter package (e.g. `import { defineCommand } from "@politty/zod"` or `from "politty"`) so the schema library integration is set up.');return e}const r=/* @__PURE__ */ new Set([`help`,`help-all`,`help-json`,`version`]);function i(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}function a(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function o(e){return!e.alias&&!e.hiddenAlias?[]:[...e.alias??[],...e.hiddenAlias??[]]}function s(e,t){let n=t.argMeta,a=n?.description??t.description,o=i(e),s=/^[A-Za-z0-9][A-Za-z0-9-]*$/,c=(t,n)=>{if(t==null)return;let r=(Array.isArray(t)?t:[t]).map(t=>{if(typeof t!=`string`)throw Error(`Invalid ${n} for field "${e}": expected string or string[], received ${typeof t}.`);let r=t.trim().replace(/^-+/,``);if(r.length===0||!s.test(r))throw Error(`Invalid ${n} "${t}" for field "${e}": aliases must match ${s}.`);return r}),i=Array.from(new Set(r));return i.length>0?i:void 0},l=c(n?.alias,`alias`),u=new Set(l??[]),d=c(n?.hiddenAlias,`hiddenAlias`)?.filter(e=>!u.has(e)),f=d&&d.length>0?d:void 0,p=t.type,m=n?.negation,h;if(m!=null){if(typeof m==`boolean`){if(p!==`boolean`)throw Error(`Invalid negation for field "${e}": negation can only be used on boolean fields.`);h=m}else{if(typeof m!=`string`)throw Error(`Invalid negation for field "${e}": expected string or boolean, received ${typeof m}.`);let t=m.trim().replace(/^-+/,``);if(t.length===0||!s.test(t))throw Error(`Invalid negation "${m}" for field "${e}": negation names must match ${s}.`);if(r.has(t))throw Error(`Invalid negation "${m}" for field "${e}": negation cannot use reserved built-in flag names (${[...r].map(e=>`--${e}`).join(`, `)}).`);if(p!==`boolean`)throw Error(`Invalid negation for field "${e}": negation can only be used on boolean fields.`);h=t}}let g=n?.negationDescription,_;if(g!=null){if(typeof g!=`string`)throw Error(`Invalid negationDescription for field "${e}": expected string, received ${typeof g}.`);if(h===!1)throw Error(`Invalid negationDescription for field "${e}": negationDescription cannot be used when negation is false.`);if(h===void 0)throw Error(`Invalid negationDescription for field "${e}": negationDescription requires \`negation\` to be set (string or true).`);let t=g.trim();if(t.length===0)throw Error(`Invalid negationDescription for field "${e}": negationDescription must be a non-empty string.`);_=t}let v=typeof h==`string`?h:h===!0?`no-${o}`:void 0,y=n?.positional,b={name:e,cliName:o,alias:l,hiddenAlias:f,description:a,positional:y!==void 0&&y!==!1,named:typeof y==`object`?y.named===!0:y!==!0,placeholder:n?.placeholder,env:n?.env,required:t.required,defaultValue:t.defaultValue,type:p,schema:t.schema,enumValues:t.enumValues,completion:n?.completion,prompt:n?.prompt,negation:h,negationDisplay:v,negationDescription:_,effect:n?.effect,requiredPackages:n?.requiredPackages};return n&&`overrideBuiltinAlias`in n&&n.overrideBuiltinAlias===!0&&(b.overrideBuiltinAlias=!0),b}function c(e,t,n){if(e.length<=n.length||!e.startsWith(n))return;if(t===`kebab`)return e[n.length]===`-`?e.slice(n.length+1):void 0;let r=e[n.length];return r===r.toLowerCase()?void 0:r.toLowerCase()+e.slice(n.length+1)}function l(e,t,n){if(t===`dot`){let t=e.indexOf(`.`);return t<0?void 0:[e.slice(0,t),e.slice(t+1)]}let r;for(let i of n)c(e,t,i)!==void 0&&(r===void 0||i.length<r.length)&&(r=i);return r===void 0?void 0:[r,c(e,t,r)]}function u(e,t,n){if(t===`dot`)return e.split(`.`);let r=[],i=e;for(let e=l(i,t,n);e;e=l(i,t,n)){let a=e[0];r.push(a),i=e[1],n=n.flatMap(e=>c(e,t,a)??[])}return r.push(i),r}function d(e={}){let t=e.style??`dot`,n=`prefixes`in e?e.prefixes:[];return e=>u(e,t,n)}function f(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}):e[t]=n}function p(e,t){let n={},r=/* @__PURE__ */ new Set,i=(e,t)=>({issues:[{message:`Cannot unflatten "${e}": "${t}" is both a value and a group`,path:[e]}]});for(let a of Object.keys(e)){let o=t(a),s=o.length-1,c=n;for(let e=0;e<s;e++){let t=o[e];if(Object.hasOwn(c,t)){let e=c[t];if(!r.has(e))return i(a,t);c=e}else{let e={};r.add(e),f(c,t,e),c=e}}let l=o[s];if(Object.hasOwn(c,l))return i(a,l);f(c,l,e[a])}return{value:n}}function m(e,t={}){let n=d(t),r=p(Object.fromEntries(e.map(e=>[e,void 0])),n);if(r.issues)throw TypeError(r.issues[0].message);let a=/* @__PURE__ */ new Map;for(let t of e){let e=n(t)[0],r=i(e),o=a.get(r);if(o!==void 0&&o!==e)throw TypeError(`Cannot unflatten "${t}": "${o}" and "${e}" are spellings of the same name. Spell the name the same way in every key.`);a.set(r,e)}}const h=/* @__PURE__ */ new WeakMap;function g(e,t={}){return h.set(e,t),e}function _(e){return h.get(e)}function v(e){if(h.has(e))throw Error(`An unflatten schema cannot be an option of a union: unflatten wraps one object schema, so the union cannot tell which option's groups its output nests. Unflatten the object that holds the union instead, or use a plain object for the option.`)}function y(e,t){if(!t.nested)return e[t.name];let n=e;for(let e of t.nested.path)n=typeof n==`object`&&n&&Object.hasOwn(n,e)?n[e]:void 0;return n}function b(e,t,n,r){let i=x(r),a=new Set([...x(n)].filter(e=>i.has(e))),o=(e,t,n)=>{let r={...e,...t};for(let i of Object.keys(t)){let s=[...n,i],c=Object.hasOwn(e,i)?e[i]:void 0,l=t[i];a.has(s.join(`\0`))&&S(c)&&S(l)&&f(r,i,o(c,l,s))}return r};return o(e,t,[])}function x(e){let t=/* @__PURE__ */ new Set;for(let{nested:n}of e){let e=n?.path??[];for(let n=1;n<e.length;n++)t.add(e.slice(0,n).join(`\0`))}return t}function S(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}export{d as a,p as c,s as d,a as f,t as h,b as i,r as l,n as m,y as n,g as o,i as p,_ as r,v as s,m as t,o as u};
@@ -1,5 +1,4 @@
1
- import { L as UnknownKeysMode, V as ArgMeta, Z as ResolvedExpandCandidate, a as ArgsSchema, r as AnyCommand, tt as DynamicCompletionResolver } from "./types-DtQ-Zt3n.js";
2
- //#region ../core/src/adapter/internal-args.d.ts
1
+ import { R as UnknownKeysMode, W as ArgMeta, a as ArgsSchema, r as AnyCommand, rt as ResolvedExpandCandidate, st as DynamicCompletionResolver } from "./types-dRfhGb8j.js";
3
2
  /** Runtime brand distinguishing internal descriptors from library schemas. */
4
3
  declare const INTERNAL_ARGS_BRAND = "__polittyInternalArgs";
5
4
  type InternalFieldKind = "string" | "boolean" | "enum" | "string-array";
@@ -37,8 +36,6 @@ type InternalArgsSchema<TOut extends Record<string, unknown> = Record<string, un
37
36
  type InferInternalArgs<S> = S extends {
38
37
  readonly __out?: infer TOut;
39
38
  } ? NonNullable<TOut> : never;
40
- //#endregion
41
- //#region ../core/src/completion/types.d.ts
42
39
  /**
43
40
  * A single resolved entry in an "expand" lookup table.
44
41
  *
@@ -305,8 +302,6 @@ interface CompletionResult {
305
302
  * Generator function type for shell completions
306
303
  */
307
304
  type CompletionGenerator = (command: AnyCommand, options: CompletionOptions) => CompletionResult;
308
- //#endregion
309
- //#region ../core/src/completion/bundled-worker.d.ts
310
305
  interface GenerateBundledCompletionWorkerOptions {
311
306
  /** CLI binary or built JS entry file to invoke. */
312
307
  bin: string;
@@ -337,8 +332,6 @@ declare function bundledWorkerShellExtension(shell: ShellType): string;
337
332
  declare function defaultBundledWorkerOutputPath(shell: ShellType): string;
338
333
  declare function validateBundledWorkerFile(path: string, programName: string, shell: ShellType): void;
339
334
  declare function generateBundledCompletionWorker(options: GenerateBundledCompletionWorkerOptions): Promise<GenerateBundledCompletionWorkerResult>;
340
- //#endregion
341
- //#region ../core/src/completion/with-completion-command.d.ts
342
335
  /**
343
336
  * Options for withCompletionCommand
344
337
  */
@@ -380,5 +373,4 @@ interface WithCompletionOptions {
380
373
  * ```
381
374
  */
382
375
  declare function withCompletionCommand<T extends AnyCommand>(command: T, options?: string | WithCompletionOptions): T;
383
- //#endregion
384
376
  export { CompletionResult as _, bundledWorkerShellExtension as a, InferInternalArgs as b, validateBundledWorkerFile as c, CompletablePositional as d, CompletableSubcommand as f, CompletionOptions as g, CompletionMode as h, GenerateBundledCompletionWorkerResult as i, BundledWorkerOptions as l, CompletionGenerator as m, withCompletionCommand as n, defaultBundledWorkerOutputPath as o, CompletionData as p, GenerateBundledCompletionWorkerOptions as r, generateBundledCompletionWorker as s, WithCompletionOptions as t, CompletableOption as u, ShellType as v, InternalArgsSchema as x, ValueCompletion as y };
@@ -1,3 +1,3 @@
1
- import{d as e,u as t}from"./schema-extractor-lB6-WHOF.js";import{n}from"./command-BXsTrIgI.js";import{s as r}from"./subcommand-router-40vA6Mka.js";import{t as i}from"./schema-C20skX3E.js";import{existsSync as a,readFileSync as o}from"node:fs";import{join as s}from"node:path";import{spawn as c}from"node:child_process";function l(){let e=(process.env.SHELL||``).split(`/`).pop()?.toLowerCase()||``;return e.includes(`bash`)?`bash`:e.includes(`zsh`)?`zsh`:e.includes(`fish`)?`fish`:null}function u(e){return`${process.env.XDG_CACHE_HOME??`${process.env.HOME??``}/.cache`}/${e}`}function d(e,t,n){if(t===`fish`){let t=process.env.XDG_CONFIG_HOME??`${process.env.HOME??``}/.config`;return s(t,`fish`,`completions`,`${e}.fish`)}let r=n??u(e);return s(r,`completion.${t}`)}function f(e){try{if(!a(e))return null;let t=o(e,`utf8`).split(`
1
+ import{d as e,f as t}from"./schema-extractor-DL8vjWso.js";import{n}from"./command-BXsTrIgI.js";import{s as r}from"./subcommand-router-40vA6Mka.js";import{t as i}from"./schema-C2QqQGOQ.js";import{existsSync as a,readFileSync as o}from"node:fs";import{join as s}from"node:path";import{spawn as c}from"node:child_process";function l(){let e=(process.env.SHELL||``).split(`/`).pop()?.toLowerCase()||``;return e.includes(`bash`)?`bash`:e.includes(`zsh`)?`zsh`:e.includes(`fish`)?`fish`:null}function u(e){return`${process.env.XDG_CACHE_HOME??`${process.env.HOME??``}/.cache`}/${e}`}function d(e,t,n){if(t===`fish`){let t=process.env.XDG_CONFIG_HOME??`${process.env.HOME??``}/.config`;return s(t,`fish`,`completions`,`${e}.fish`)}let r=n??u(e);return s(r,`completion.${t}`)}function f(e){try{if(!a(e))return null;let t=o(e,`utf8`).split(`
2
2
  `,6).join(`
3
- `).match(/^# politty-bin-sig: (\S+)/m);return t?t[1]:null}catch{return null}}function p(e,t){return f(d(e.programName,t,e.cacheDir))!==null}function m(e,t){try{c(process.execPath,[e,`__refresh-completion`,t],{detached:!0,stdio:`ignore`}).unref()}catch{}}const h=t({shell:e.optionalEnum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell type (bash, zsh, or fish)`,placeholder:`SHELL`}),instructions:e.boolean({alias:`i`,description:`Show installation instructions`}),loader:e.boolean({description:`Print just the rc loader snippet (bash/zsh). Add it to ~/.bashrc or ~/.zshrc; it auto-regenerates the cache when the binary changes.`}),install:e.boolean({description:`Write the completion script to its on-disk cache (bash/zsh) or autoload location (fish) instead of printing it.`}),static:e.boolean({description:`Generate the legacy static completion script with command metadata baked in.`}),dispatcher:e.boolean({description:`Generate the runtime dispatcher completion script. This is the default.`}),worker:e.boolean({description:`Generate an internal static worker artifact for dispatcher mode.`})}),g=t({shell:e.enum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell to refresh`,placeholder:`SHELL`}),target:e.optionalString({positional:!0,description:`Existing politty-generated completion file to refresh`,placeholder:`TARGET`}),static:e.boolean({description:`Refresh using the legacy static completion script mode.`}),worker:e.boolean({description:`Refresh an internal static worker completion script.`})}),_=t({shell:e.enum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell worker to locate`,placeholder:`SHELL`})});function v(e,t){let{programName:a,globalArgsSchema:o,cacheDir:s,programVersion:c,bundledWorker:l}=typeof t==`string`?{programName:t}:t??{},u=a??e.name,d={...s!==void 0&&{cacheDir:s},...c!==void 0&&{programVersion:c},...o!==void 0&&{globalArgsSchema:o},...l!==void 0&&{bundledWorker:l}},f={...e};return f.subCommands={...e.subCommands,completion:r(n({name:`completion`,description:`Generate shell completion script`,args:h,run(){}}),()=>import(`./completion-CmxAA8Op.js`).then(e=>e.createCompletionCommand(f,a,o,d))),__complete:r(n({name:`__complete`,args:i,run(){}}),()=>import(`./dynamic-BEW8hYW1.js`).then(e=>e.createDynamicCompleteCommand(f,a,o))),"__refresh-completion":r(n({name:`__refresh-completion`,description:`(internal) Refresh the on-disk completion cache if stale.`,args:g,run(){}}),()=>import(`./completion-CmxAA8Op.js`).then(e=>e.createRefreshCompletionCommand(f,u,d))),"__completion-worker-path":r(n({name:`__completion-worker-path`,description:`(internal) Print the bundled completion worker path when available.`,args:_,run(){}}),()=>import(`./completion-CmxAA8Op.js`).then(e=>e.createCompletionWorkerPathCommand(u,d)))},f.runMainHook=e=>{y(e,{programName:u,...s!==void 0&&{cacheDir:s}})},f}function y(e,t){if(process.env.POLITTY_NO_COMPLETION_REFRESH)return;let n=e.find(e=>!e.startsWith(`-`));if(n===`__complete`||n===`__refresh-completion`||n===`__completion-worker-path`||n===`completion`)return;let r=l();if(!r)return;let i=process.argv[1];i&&p(t,r)&&m(i,r)}export{d as a,_ as i,h as n,f as o,g as r,l as s,v as t};
3
+ `).match(/^# politty-bin-sig: (\S+)/m);return t?t[1]:null}catch{return null}}function p(e,t){return f(d(e.programName,t,e.cacheDir))!==null}function m(e,t){try{c(process.execPath,[e,`__refresh-completion`,t],{detached:!0,stdio:`ignore`}).unref()}catch{}}const h=e({shell:t.optionalEnum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell type (bash, zsh, or fish)`,placeholder:`SHELL`}),instructions:t.boolean({alias:`i`,description:`Show installation instructions`}),loader:t.boolean({description:`Print just the rc loader snippet (bash/zsh). Add it to ~/.bashrc or ~/.zshrc; it auto-regenerates the cache when the binary changes.`}),install:t.boolean({description:`Write the completion script to its on-disk cache (bash/zsh) or autoload location (fish) instead of printing it.`}),static:t.boolean({description:`Generate the legacy static completion script with command metadata baked in.`}),dispatcher:t.boolean({description:`Generate the runtime dispatcher completion script. This is the default.`}),worker:t.boolean({description:`Generate an internal static worker artifact for dispatcher mode.`})}),g=e({shell:t.enum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell to refresh`,placeholder:`SHELL`}),target:t.optionalString({positional:!0,description:`Existing politty-generated completion file to refresh`,placeholder:`TARGET`}),static:t.boolean({description:`Refresh using the legacy static completion script mode.`}),worker:t.boolean({description:`Refresh an internal static worker completion script.`})}),_=e({shell:t.enum([`bash`,`zsh`,`fish`],{positional:!0,description:`Shell worker to locate`,placeholder:`SHELL`})});function v(e,t){let{programName:a,globalArgsSchema:o,cacheDir:s,programVersion:c,bundledWorker:l}=typeof t==`string`?{programName:t}:t??{},u=a??e.name,d={...s!==void 0&&{cacheDir:s},...c!==void 0&&{programVersion:c},...o!==void 0&&{globalArgsSchema:o},...l!==void 0&&{bundledWorker:l}},f={...e};return f.subCommands={...e.subCommands,completion:r(n({name:`completion`,description:`Generate shell completion script`,args:h,run(){}}),()=>import(`./completion-B9wrL5rH.js`).then(e=>e.createCompletionCommand(f,a,o,d))),__complete:r(n({name:`__complete`,args:i,run(){}}),()=>import(`./dynamic-CxhC0uOL.js`).then(e=>e.createDynamicCompleteCommand(f,a,o))),"__refresh-completion":r(n({name:`__refresh-completion`,description:`(internal) Refresh the on-disk completion cache if stale.`,args:g,run(){}}),()=>import(`./completion-B9wrL5rH.js`).then(e=>e.createRefreshCompletionCommand(f,u,d))),"__completion-worker-path":r(n({name:`__completion-worker-path`,description:`(internal) Print the bundled completion worker path when available.`,args:_,run(){}}),()=>import(`./completion-B9wrL5rH.js`).then(e=>e.createCompletionWorkerPathCommand(u,d)))},f.runMainHook=e=>{y(e,{programName:u,...s!==void 0&&{cacheDir:s}})},f}function y(e,t){if(process.env.POLITTY_NO_COMPLETION_REFRESH)return;let n=e.find(e=>!e.startsWith(`-`));if(n===`__complete`||n===`__refresh-completion`||n===`__completion-worker-path`||n===`completion`)return;let r=l();if(!r)return;let i=process.argv[1];i&&p(t,r)&&m(i,r)}export{d as a,_ as i,h as n,f as o,g as r,l as s,v as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@politty/valibot",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "A lightweight CLI framework inspired by citty with valibot integration for type-safe metadata management",
5
5
  "keywords": [
6
6
  "argument-parser",
@@ -75,7 +75,7 @@
75
75
  },
76
76
  "devDependencies": {
77
77
  "@politty/core": "0.1.0",
78
- "@types/node": "25.9.9",
78
+ "@types/node": "26.6.5",
79
79
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
80
80
  "tsdown": "0.23.1",
81
81
  "typescript": "7.0.2",
@@ -1 +0,0 @@
1
- import{i as e,n as t}from"./field-meta-CEtC5Mir.js";const n=/* @__PURE__ */ new Set([`1`,`t`,`T`,`TRUE`,`true`,`True`]),r=/* @__PURE__ */ new Set([`0`,`f`,`F`,`FALSE`,`false`,`False`]);function i(e){return n.has(e)?!0:!r.has(e)&&e}function a(e,t){return t===`boolean`?i(e):e}function o(e){let t=e.indexOf(`=`);return t>=0?e.slice(2,t):e.slice(2)}function s(e,t){let n=o(e);if(!e.includes(`=`)){let e=t.negationMap.get(n);if(e&&t.booleanFlags.has(e))return{resolvedName:e,withoutDashes:n,isNegated:!0,isCustomNegation:!0,isSuppressedNegation:!1}}let r=e.includes(`=`);if(!r&&n.startsWith(`no-`)){let e=n.slice(3);if(e===e.toLowerCase()){let r=t.aliasMap.get(e)??e;if(t.booleanFlags.has(r)){let e=t.aliasMap.get(n)??n;if(!t.definedNames.has(e))return t.defaultNegationDisabledFields.has(r)?{resolvedName:r,withoutDashes:n,isNegated:!1,isCustomNegation:!1,isSuppressedNegation:!0}:{resolvedName:r,withoutDashes:n,isNegated:!0,isCustomNegation:!1,isSuppressedNegation:!1}}}}if(!r&&n.length>2&&n.startsWith(`no`)&&/[A-Z]/.test(n[2])){let e=n[2].toLowerCase()+n.slice(3),r=t.aliasMap.get(e)??e;if(t.booleanFlags.has(r)){let e=t.aliasMap.get(n)??n;if(!t.definedNames.has(e))return t.defaultNegationDisabledFields.has(r)?{resolvedName:r,withoutDashes:n,isNegated:!1,isCustomNegation:!1,isSuppressedNegation:!0}:{resolvedName:r,withoutDashes:n,isNegated:!0,isCustomNegation:!1,isSuppressedNegation:!1}}}return{resolvedName:t.aliasMap.get(n)??n,withoutDashes:n,isNegated:!1,isCustomNegation:!1,isSuppressedNegation:!1}}const c=/^-\.?\d/;function l(e){return!e.startsWith(`-`)||c.test(e)}function u(e){return e.startsWith(`-`)&&!e.startsWith(`--`)&&e.length>2&&!e.includes(`=`)}function d(e,t){let n=Array.from(e),r=n.findIndex(t);if(r===-1)return{flags:n,valueOption:void 0};let i=n.slice(r+1).join(``);return{flags:n.slice(0,r),valueOption:{name:n[r],value:i===``?void 0:i}}}function f(e,t={}){let{aliasMap:n=/* @__PURE__ */ new Map,booleanFlags:r=/* @__PURE__ */ new Set,arrayFlags:a=/* @__PURE__ */ new Set,valueFlags:o=/* @__PURE__ */ new Set,definedNames:c=/* @__PURE__ */ new Set,negationMap:u=/* @__PURE__ */ new Map,defaultNegationDisabledFields:f,unknownFlagsTakeNoValue:p=!1}=t,m=f??new Set(r),h=e=>r.has(e)||p&&!c.has(e),g={aliasMap:n,booleanFlags:r,definedNames:c,negationMap:u,defaultNegationDisabledFields:m},_={options:{},positionals:[],rest:[]},v=0,y=!1,b=(e,t)=>{let r=n.get(e)??e;if(a.has(r)){let e=_.options[r];Array.isArray(e)?e.push(t):e===void 0?_.options[r]=[t]:_.options[r]=[e,t]}else _.options[r]=t},x=t=>{let n=e[v+1];n!==void 0&&l(n)?(b(t,n),v+=2):(b(t,!0),v++)};for(;v<e.length;){let t=e[v];if(y)_.rest.push(t),v++;else if(t===`--`)y=!0,v++;else if(t.startsWith(`--`)){let e=t.slice(2),a=s(t,g);if(a.isSuppressedNegation){b(a.withoutDashes,!0),v++;continue}if(a.isNegated){b(a.resolvedName,!1),v++;continue}let o=e.indexOf(`=`);if(o!==-1){let t=e.slice(0,o),a=e.slice(o+1),s=n.get(t)??t;b(t,r.has(s)?i(a):a),v++}else{let t=e;h(n.get(t)??t)?(b(t,!0),v++):x(t)}}else if(t.startsWith(`-`)&&t.length>1&&!t.startsWith(`--`)){let e=t.slice(1),a=e.indexOf(`=`);if(a!==-1){let t=e.slice(0,a),o=e.slice(a+1),s=n.get(t)??t;b(t,r.has(s)?i(o):o),v++}else if(e.length===1){let t=e;h(n.get(t)??t)?(b(t,!0),v++):x(t)}else{let{flags:t,valueOption:r}=d(e,e=>o.has(n.get(e)??e));for(let e of t)b(e,!0);r?r.value===void 0?x(r.name):(b(r.name,r.value),v++):v++}}else _.positionals.push(t),v++}return _}function p(n){let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set;for(let e of n.fields)s.add(e.name);for(let u of n.fields){if(!u.named)continue;u.cliName!==u.name&&r.set(u.cliName,u.name);for(let n of t(u))if(r.set(n,u.name),n.length>1&&n.includes(`-`)){let t=e(n);t!==n&&!s.has(t)&&!r.has(t)&&r.set(t,u.name)}let n=e(u.name);if(n!==u.name&&!s.has(n)&&!r.has(n)&&r.set(n,u.name),u.type===`boolean`?i.add(u.name):o.add(u.name),u.type===`array`&&a.add(u.name),u.type===`boolean`&&u.negation!==!0&&(l.add(u.name),typeof u.negation==`string`&&(c.set(u.negation,u.name),u.negation.includes(`-`)))){let t=e(u.negation);t!==u.negation&&c.set(t,u.name)}}return{aliasMap:r,booleanFlags:i,arrayFlags:a,valueFlags:o,definedNames:s,negationMap:c,defaultNegationDisabledFields:l}}function m(e,t){return e.fields.filter(e=>e.positional&&!(e.named&&Object.hasOwn(t,e.name)))}function h(e,t){let n={...e.options},r=t.fields.filter(e=>e.positional),i=e.rest.length>0?[...e.positionals,...e.rest]:e.positionals;for(let e of r)e.named||delete n[e.name];let a=0;for(let r of m(t,e.options)){if(a>=i.length)break;if(r.type===`array`){n[r.name]=i.slice(a);break}n[r.name]=i[a],a++}return n}export{f as a,o as c,a as d,h as i,s as l,l as n,m as o,u as r,d as s,p as t,i as u};
@@ -1 +0,0 @@
1
- export{t as runPolittyCli}from"./cli-main-DblimvdD.js";
@@ -1 +0,0 @@
1
- import"./register-BtPBdvwq.js";const{runPolittyCli:e}=await import(`./cli-main-CykIbGzU.js`);await e(`@politty/valibot`);export{};
@@ -1 +0,0 @@
1
- import"./with-completion-command-CI1rxHay.js";import"./dynamic-DvdL7L96.js";export{t as createCompletionCommand,n as createCompletionWorkerPathCommand,r as createRefreshCompletionCommand,c as generateBundledCompletionWorker}from"./completion-NbQ2jmWx.js";
@@ -1 +0,0 @@
1
- export{t as createDynamicCompleteCommand}from"./dynamic-DvdL7L96.js";
@@ -1 +0,0 @@
1
- import{l as e}from"./schema-extractor-lB6-WHOF.js";function t(e){let t=e.prompt;if(!t||t.enabled===!1)return null;let n=t.message??e.description??e.name,a=r(e,t),o=i(e,t,a);return{field:e,type:a===`select`&&!o?`text`:a,message:n,...o&&{choices:o}}}function n(e){return e!==void 0&&e.length>0}function r(e,t){return t.type?t.type===`file`||t.type===`directory`?`text`:t.type:n(t.choices)?`select`:e.completion?.type===`file`||e.completion?.type===`directory`?`text`:n(e.enumValues)?`select`:e.type===`boolean`?`confirm`:`text`}function i(e,t,r){if(n(t.choices))return t.choices.map(e=>typeof e==`string`?{label:e,value:e}:e);if(r===`select`&&n(e.enumValues))return e.enumValues.map(e=>({label:e,value:e}))}function a(e,n){let r=[];for(let i of e){if(n[i.name]!==void 0||i.type===`array`)continue;let e=t(i);e&&r.push(e)}return r}function o(){return!(!process.stdin.isTTY||!process.stdout.isTTY||process.env.CI||process.env.POLITTY_NO_PROMPT)}async function s(e,t,n){if(!(n.interactive??o()))return e;let r=n.adapter,i={...e};return t.schemaType===`discriminatedUnion`&&t.discriminator&&t.variants?await c(r,i,t):t.schemaType===`union`||t.schemaType===`xor`||await u(r,i,t.fields),i}async function c(n,r,i){let{discriminator:a,variants:o}=i;if(!a||!o)return;if(r[a]===void 0){let e=l(i.fields,o,a),s=e?t(e):null;if(s){let e=o.map(e=>e.discriminatorValue).filter(Boolean);e.length>0&&(s.type=`select`,s.choices=e.map(e=>({label:e,value:e}))),await d(n,r,s)}}let s=e(i,()=>r);s!==i&&await u(n,r,s.fields.filter(e=>e.name!==a))}function l(e,t,n){let r=e.find(e=>e.name===n);if(r?.prompt)return r;for(let e of t){let t=e.fields.find(e=>e.name===n);if(t?.prompt)return t}}async function u(e,t,n){let r=a(n,t);for(let n of r)await d(e,t,n)}async function d(e,t,n){let{message:r}=n,i;switch(n.type){case`text`:i=await e.text({message:r,placeholder:n.field.placeholder});break;case`password`:i=await e.password({message:r});break;case`confirm`:i=await e.confirm({message:r});break;case`select`:i=await e.select({message:r,options:n.choices??[]})}if(e.isCancelled(i))throw Error(`Prompt cancelled by user`);t[n.field.name]=i}export{t as i,o as n,a as r,s as t};
@@ -1 +0,0 @@
1
- import{r as e,s as t}from"./field-meta-CEtC5Mir.js";import{safeParse as n}from"valibot";const r=/* @__PURE__ */ new WeakMap;function i(e,t){return t&&r.set(e,t),e}function a(e){return r.get(e)}function o(e){return e}const s=/* @__PURE__ */ new Set([`optional`,`exact_optional`,`nullish`,`undefinedable`]),c=/* @__PURE__ */ new Set([`optional`,`exact_optional`,`nullish`,`undefinedable`,`nullable`,`non_optional`,`non_nullable`,`non_nullish`]);function l(e){let t=e;for(;t.type&&c.has(t.type)&&t.wrapped;)t=t.wrapped;return t}function u(e){let t=l(e),n=h(t.type);return n===`unknown`?d(t)?`boolean`:t.type===`unknown`||t.type===`any`?f(e)??`unknown`:`unknown`:n}function d(e){return e.type===`boolean`?!0:e.type===`literal`?typeof e.literal==`boolean`:e.type!==`union`||!e.options?.length?!1:e.options.every(d)}function f(e){if(Array.isArray(e.pipe))for(let t of e.pipe){if(t.kind===`schema`){let e=h(t.type);if(e!==`unknown`)return e}if(t.kind===`validation`&&m(t))return`number`}if(e.type&&c.has(e.type)&&e.wrapped)return f(e.wrapped)}const p=/* @__PURE__ */ new Set([`integer`,`safe_integer`,`finite`]);function m(e){return e.type?p.has(e.type)?!0:e.type===`multiple_of`&&typeof e.requirement==`number`:!1}function h(e){switch(e){case`string`:case`picklist`:case`enum`:return`string`;case`number`:return`number`;case`boolean`:return`boolean`;case`array`:return`array`;default:return`unknown`}}function g(e){let t=l(o(e)),n=e=>e.length>0&&e.every(e=>typeof e==`string`);if(t.type===`picklist`&&Array.isArray(t.options))return n(t.options)?t.options:void 0;if(t.type===`enum`){let e=Array.isArray(t.options)?t.options:t.enum&&typeof t.enum==`object`?Object.values(t.enum):[];return n(e)?e:void 0}if(t.type===`array`&&t.item)return g(t.item);if(t.type===`union`&&Array.isArray(t.options)){let e=[];for(let n of t.options){let t=o(n);t.type===`literal`&&typeof t.literal==`string`&&e.push(t.literal)}if(e.length===t.options.length&&e.length>0)return e}}function _(e){let t=e;for(;t.type&&c.has(t.type);){if(s.has(t.type))return!1;if(!t.wrapped)break;t=t.wrapped}return!0}function v(e){let t=e;for(;t?.type&&c.has(t.type);){if(t.default!==void 0)return typeof t.default==`function`?t.default():t.default;t=t.wrapped}}function y(e){if(Array.isArray(e.pipe)){let t;for(let n of e.pipe)n.kind===`metadata`&&n.type===`description`&&typeof n.description==`string`&&(t=n.description);if(t!==void 0)return t}if(e.type&&c.has(e.type)&&e.wrapped)return y(e.wrapped)}function b(e){let t;if(e.type&&c.has(e.type)&&e.wrapped&&(t=b(e.wrapped)),Array.isArray(e.pipe))for(let n of e.pipe)n.kind===`metadata`&&n.type===`metadata`&&n.metadata&&(t={...t,...n.metadata});return t}function x(e,t){if(t.has(e))return;t.add(e);let n=a(e);if(n)return n;if(Array.isArray(e.pipe)){for(let n of e.pipe)if(n&&n.kind===`schema`){let e=x(n,t);if(e)return e}}if(e.wrapped)return x(e.wrapped,t)}function S(e){let t=x(e,/* @__PURE__ */ new Set);if(t)return t;let n=b(e);if(n)return n}function C(t,n){let r=o(n);return e(t,{argMeta:S(r),description:y(r),required:_(r),defaultValue:v(r),type:u(r),enumValues:g(r),schema:n})}function w(e){switch(l(o(e)).type){case`strict_object`:return`strict`;case`loose_object`:case`object_with_rest`:return`passthrough`;default:return`strip`}}function T(e){let t=e.entries??{};return Object.entries(t).map(([e,t])=>C(e,t))}function E(e,t){let n=e.entries?.[t];if(!n)return``;let r=l(n);if(r.type===`literal`&&r.literal!==void 0)return String(r.literal);let i=g(r);return i&&i.length===1?i[0]:``}function D(e){let t=e.key??``,n=e.options??[],r=/* @__PURE__ */ new Map,i=[];for(let e of n){let n=o(e),a=[];for(let[e,t]of Object.entries(n.entries??{})){let n=C(e,t);a.push(n),r.has(e)||r.set(e,n)}let s=y(n);i.push({discriminatorValue:E(n,t),fields:a,...s?{description:s}:{}})}let a=y(e);return{fields:Array.from(r.values()),schema:e,schemaType:`discriminatedUnion`,unknownKeysMode:w(e),discriminator:t,variants:i,...a?{description:a}:{}}}function O(e){let t=e.options??[],n=/* @__PURE__ */ new Map,r=[];for(let e of t){let t=j(e);r.push(t);for(let e of t.fields)n.has(e.name)||n.set(e.name,e)}let i=y(e);return{fields:Array.from(n.values()),schema:e,schemaType:`union`,unknownKeysMode:w(e),unionOptions:r,...i?{description:i}:{}}}function k(e){let t=/* @__PURE__ */ new Map;for(let n of e.options??[]){let e=j(n);for(let n of e.fields)t.has(n.name)||t.set(n.name,n)}let n=y(e);return{fields:Array.from(t.values()),schema:e,schemaType:`intersection`,unknownKeysMode:w(e),...n?{description:n}:{}}}const A=/* @__PURE__ */ new WeakMap;function j(e){let t=A.get(e);if(t)return t;let n=l(o(e)),r;switch(n.type){case`object`:case`strict_object`:case`loose_object`:case`object_with_rest`:{let t=y(o(e));r={fields:T(n),schema:e,schemaType:`object`,unknownKeysMode:w(n),...t?{description:t}:{}};break}case`variant`:r={...D(n),schema:e};break;case`union`:r={...O(n),schema:e};break;case`intersect`:r={...k(n),schema:e};break;default:{let t=y(o(e));r={fields:[],schema:e,schemaType:`object`,unknownKeysMode:w(n),...t?{description:t}:{}};break}}return A.set(e,r),r}function M(e,t){return{path:t,message:e.message,code:e.type,received:e.input,expected:e.expected??void 0}}function N(e){if(e.kind!==`schema`||e.path?.length!==1)return;let[t]=e.path;return t?.origin===`key`?String(t.key):void 0}function P(e,t){let n=j(e).fields.find(e=>e.name===t);return n?.positional?`Missing required argument <${t}>`:`Missing required option --${n?.cliName??t}`}function F(e,t){return e.map(e=>{let n=e,r=n.path?.map(e=>String(e.key))??[],i=N(n);return i!==void 0&&n.message===`Invalid key: Expected "${i}" but received undefined`?M({...n,message:P(t,i)},r):M(n,r)})}function I(e,t){let r=n(t,e);return r.success?{success:!0,data:r.output}:{success:!1,errors:F(r.issues,t)}}t({vendor:`valibot`,extractFields:j,resolveFieldMeta:C,getUnknownKeysMode:w,validate:I});export{i as t};
@@ -1 +0,0 @@
1
- export{t as runCommand}from"./runner-BsHTbOwS.js";