@0xkahi/llw 0.0.0-stage β†’ 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kahi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,228 @@
1
- # Temporary Holding Version
1
+ # llm-wiki (`llw`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > A persistent, agent-friendly knowledge base built on Obsidian, plus the CLI and agent skills to manage it.
4
+
5
+ `llw` is a CLI that turns an [Obsidian](https://obsidian.md) vault into a structured knowledge base that AI agents can read, write, and search reliably. Knowledge is stored as plain markdown with YAML frontmatter, following a variation of Google's **Open Knowledge Format (OKF)**. It is organized into:
6
+
7
+ - **Bundles**: folders that group related knowledge on one area. Each bundle has a `bundle.md` holding its metadata (title, description, triggers, parent).
8
+ - **Concepts**: individual notes inside a bundle (a schema, an API, a decision, a how-to…).
9
+
10
+ `llw` does not reimplement a markdown database. It builds on Obsidian:
11
+
12
+ - **Obsidian Bases** index every bundle in the vault, so lookups are fast and consistent.
13
+ - **Obsidian Templates** create bundles and concepts with the correct frontmatter.
14
+ - **The Obsidian CLI** is the only path `llw` uses to query and edit the vault.
15
+
16
+ On top of that, `llw` ships a suite of **agent skills** (installable with `npx skills`). They teach agents how to add, enrich, search, and sync knowledge without breaking the vault's structure.
17
+
18
+ ### Features
19
+
20
+ - πŸ“š **Bundle and concept management**: create, view, update, rename, and browse knowledge as a tree.
21
+ - πŸ”Ž **Semantic search** with [TypeSafe Jev](https://typesafe.ai) (optional): ask a question and get the bundles and concepts most likely to answer it, with probabilities.
22
+ - πŸ”„ **Bundle sync**: detect bundles whose contents changed so agents can refresh their `bundle.md` summaries.
23
+ - πŸ€– **Agent skills served by the CLI**: skill instructions always match the installed CLI version.
24
+ - πŸͺΆ **Token-efficient output**: data commands default to compact [TOON](https://github.com/toon-format/toon), with JSON available.
25
+
26
+ ---
27
+
28
+ ## Installation
29
+
30
+ ### Prerequisites
31
+
32
+ | Requirement | Why |
33
+ | --- | --- |
34
+ | [Bun](https://bun.sh) | `llw` runs on the Bun runtime. |
35
+ | [Obsidian](https://obsidian.md) desktop app, **running** | All vault operations go through the Obsidian CLI. |
36
+ | Obsidian CLI enabled | *Settings β†’ General β†’ Command line interface*. Check with `obsidian version`. |
37
+ | A vault named exactly **`llm-wiki`** | `llw` targets this vault by name. |
38
+ | Core plugins **Bases** and **Templates** enabled | *Settings β†’ Core plugins*. Used for indexing and note creation. |
39
+ | `TYPESAFE_API_KEY` *(optional)* | Only needed for the `llw jev` search commands. |
40
+
41
+ ### 1. Install the CLI
42
+
43
+ ```bash
44
+ bun add -g @0xkahi/llw
45
+ # or
46
+ npm install -g @0xkahi/llw # Bun must still be on your PATH
47
+ ```
48
+
49
+ Verify the install:
50
+
51
+ ```bash
52
+ llw --version
53
+ llw skills list
54
+ ```
55
+
56
+ ### 2. Install the agent skills
57
+
58
+ ```bash
59
+ npx skills add 0xKahi/llw
60
+ ```
61
+
62
+ This installs the `llm-wiki` discovery skill into your agent (Claude Code, Codex, Cursor, pi, …). The discovery skill is intentionally thin: it routes the agent to the full workflows, which are served by the installed CLI (`llw skills view <name>`). Install the CLI from step 1 as well.
63
+
64
+ ### 3. Set up the vault
65
+
66
+ Create a vault named `llm-wiki` in Obsidian and enable the **Bases** and **Templates** core plugins. Then let your agent do the rest:
67
+
68
+ > *"Set up my llm-wiki vault"*
69
+
70
+ The agent follows the `llw-vault-setup` skill. It copies the shipped base and templates into the vault, configures the Templates plugin, creates the `bundles/` folder, and verifies the result.
71
+
72
+ <details>
73
+ <summary>Manual setup</summary>
74
+
75
+ The files live in the package's `obsidian-setup/` folder:
76
+
77
+ ```bash
78
+ VAULT="$(obsidian vault=llm-wiki vault info=path)"
79
+ SETUP="$(llw skills view llw-vault-setup --path)/../../obsidian-setup"
80
+
81
+ mkdir -p "$VAULT/bases" "$VAULT/config/templates" "$VAULT/bundles"
82
+ cp "$SETUP/bases/bundles-index.base" "$VAULT/bases/"
83
+ cp "$SETUP/config/templates/bundle.md" "$VAULT/config/templates/"
84
+ cp "$SETUP/config/templates/concept.md" "$VAULT/config/templates/"
85
+ # Only if you have no existing Templates config. Otherwise set
86
+ # "folder": "config/templates" and "timeFormat": "HH:mm" by hand.
87
+ cp "$SETUP/.settings/templates.json" "$VAULT/.obsidian/templates.json"
88
+
89
+ obsidian vault=llm-wiki reload
90
+ llw bundle list --pretty # β†’ bundles: [] on a fresh vault
91
+ ```
92
+
93
+ </details>
94
+
95
+ ### 4. (Optional) Enable semantic search
96
+
97
+ ```bash
98
+ export TYPESAFE_API_KEY="<your key>"
99
+ llw jev status # β†’ available
100
+ ```
101
+
102
+ ### 5. (Optional) Web Clipper inbox
103
+
104
+ Import `obsidian-setup/config/web-clipper/llm-wiki-template.json` into the [Obsidian Web Clipper](https://obsidian.md/clipper) extension. Clipped pages then land in the vault's `raw/` folder. Ask your agent to *"parse raw"* to turn them into bundles and concepts.
105
+
106
+ ---
107
+
108
+ ## Usage
109
+
110
+ ### With an agent (recommended)
111
+
112
+ `llw` is designed to be driven by agents through its skills. Once the skills are installed, just talk to your agent:
113
+
114
+ | You say… | Skill used |
115
+ | --- | --- |
116
+ | *"Add what we learned about the payments DB schema to the wiki"* | `llw-okf` (core) |
117
+ | *"What does the wiki know about our deploy pipeline?"* | `llw-okf` (core) |
118
+ | *"Parse raw"* | `llw-okf` (core) |
119
+ | *"Sync the wiki"* / *"bundle sync"* | `llw-okf-sync` |
120
+ | *"Set up the llm-wiki vault"* | `llw-vault-setup` |
121
+
122
+ | Skill | Alias | Purpose |
123
+ | --- | --- | --- |
124
+ | `llw-okf` | `core` | Create, validate, enrich, and search bundles and concepts (default workflow). |
125
+ | `llw-okf-sync` | `bundle-sync` | Find out-of-sync bundles and refresh their `bundle.md` summaries. |
126
+ | `llw-vault-setup` | `setup` | Set up or repair the files `llw` needs inside the vault. |
127
+
128
+ Read any skill directly with `llw skills view <name|alias>`.
129
+
130
+ ### From the command line
131
+
132
+ ```bash
133
+ # Create a top-level bundle, a child bundle, and a concept
134
+ llw bundle create bundles/backend --description "Backend services" --triggers "api, services"
135
+ llw bundle create bundles/backend/database \
136
+ --description "Database schemas and migrations" \
137
+ --triggers "db, migrations, postgres" \
138
+ --parent bundles/backend
139
+ llw concept create users-table \
140
+ --bundle bundles/backend/database \
141
+ --type db-schema \
142
+ --description "Schema of the users table" \
143
+ --tags "postgres, sql"
144
+ # β†’ prints the full path of the new note, ready for its body to be written
145
+
146
+ # Browse
147
+ llw bundle tree --verbose
148
+ llw bundle view --bundle bundles/backend/database --pretty
149
+ llw vault info
150
+
151
+ # Search (requires TYPESAFE_API_KEY)
152
+ llw jev search -q "how are user ids generated?"
153
+ ```
154
+
155
+ ### Command reference
156
+
157
+ Commands marked with † accept `--format, -f <toon|json>` (default `toon`) and `--pretty` (indented output instead of compact).
158
+
159
+ #### `llw bundle`
160
+
161
+ | Command | Description |
162
+ | --- | --- |
163
+ | `bundle list` (`ls`) † | List every bundle in the vault. |
164
+ | `bundle tree [--verbose]` | Print the bundle hierarchy. `--verbose` adds paths, descriptions, and triggers. |
165
+ | `bundle view --bundle <folder>` † | Show a bundle with its concepts and direct child bundles. |
166
+ | `bundle create <folder> --description <d> [--triggers <csv>] [--parent <folder>]` | Create a bundle (folder + `bundle.md`) under `bundles/`. |
167
+ | `bundle update --bundle <folder> [--description] [--triggers] [--parent]` | Update bundle metadata. |
168
+ | `bundle rename --bundle <folder> --title <title>` | Rename a bundle and its folder. |
169
+ | `bundle sync [--reset]` | Generate a manifest of out-of-sync bundles in `cache/bundles/`. `--reset` discards a pending sync. |
170
+
171
+ #### `llw concept`
172
+
173
+ | Command | Description |
174
+ | --- | --- |
175
+ | `concept view <name> --bundle <folder>` † | Show a concept's properties and full path. |
176
+ | `concept create <name> --bundle <folder> --type <t> --description <d> [--resource <uri>] [--tags <csv>]` | Create a concept from the template. |
177
+ | `concept update <name> --bundle <folder> [--type] [--description] [--resource] [--tags] [--timestamp [YYYY-MM-DDTHH:mm]]` | Update concept properties. A bare `--timestamp` sets it to now. |
178
+ | `concept open <name> --bundle <folder>` | Open the concept in Obsidian. |
179
+
180
+ #### `llw jev` (requires `TYPESAFE_API_KEY`)
181
+
182
+ | Command | Description |
183
+ | --- | --- |
184
+ | `jev status` | Print `available` / `unavailable` (exits `1` when unavailable). |
185
+ | `jev bundle_search -q <question>` † | Rank bundles likely to cover a question. |
186
+ | `jev search -q <question>` † | Rank bundles **and** the concepts inside them that likely answer a question. |
187
+
188
+ > `jev search` sends the contents of your concept notes to the TypeSafe API for scoring.
189
+
190
+ #### `llw vault`
191
+
192
+ | Command | Description |
193
+ | --- | --- |
194
+ | `vault path` | Print the vault's absolute path. |
195
+ | `vault info` | Print a vault summary: bundle and concept counts plus the bundle tree. |
196
+ | `vault base` | Print the raw bundle index (Obsidian Bases query result) as JSON. |
197
+
198
+ #### `llw skills`
199
+
200
+ | Command | Description |
201
+ | --- | --- |
202
+ | `skills list` (`ls`) `[--json]` | List the bundled agent skills. |
203
+ | `skills view <name\|alias> [--path]` | Print a skill's instructions (or its folder path with `--path`). |
204
+
205
+ Run `llw <command> --help` for full details on any command. Errors are written to stderr and exit with code `1`, so stdout stays safe to parse.
206
+
207
+ ---
208
+
209
+ ## Documentation
210
+
211
+ - [**How bundles and the Obsidian Bases indexer work**](docs/bundles-and-indexing.md): the vault layout, bundle and concept schemas, how the index, templates, and sync work, and how this OKF variant differs from upstream OKF.
212
+ - [**Skill registry**](docs/skill-registry.md): how skills are authored, registered, and served by `llw skills` (for contributors).
213
+ - [**OKF v0.1 specification (vendored)**](skill-data/llw-okf/sk-references/spec-v01.md): the upstream format this project builds on.
214
+ - [**OKF examples**](skill-data/llw-okf/sk-references/okf-examples.md): example bundles and concepts.
215
+
216
+ ### Development
217
+
218
+ ```bash
219
+ bun install
220
+ bun run dev -- --help # run from source
221
+ bun test # run tests
222
+ bun run check # lint (biome) + type-check
223
+ bun run build # build to dist/
224
+ ```
225
+
226
+ ## License
227
+
228
+ [MIT](LICENSE) Β© 0xKahi
package/dist/index.js ADDED
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var Sn=Object.create;var{getPrototypeOf:vn,defineProperty:lt,getOwnPropertyNames:En}=Object;var ct=Object.prototype.hasOwnProperty;function $n(e){return this[e]}var xn,kn,An=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?xn??=new WeakMap:kn??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?Sn(vn(e)):{};let o=t||!e||!e.__esModule||!ct.call(e,"default")?lt(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of En(e))if(!ct.call(o,a))lt(o,a,{get:$n.bind(e,a),enumerable:!0})}if(r)i.set(e,o);return o};var Pn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var gn=Pn(function(tl,Ji){Ji.exports={name:"@0xkahi/llw",version:"0.0.0",description:"LLM-WIKI: skills, prompts, and a cli tool for agents to manage your knowledge base",author:"0xKahi",license:"MIT",type:"module",engines:{bun:">=1.4.0"},keywords:["agent-skills","cli","knowledge-base","okf"],repository:{type:"git",url:"git+https://github.com/0xKahi/llw.git"},files:["dist","skill-data","obsidian-setup"],bin:{llw:"./dist/index.js"},scripts:{dev:"bun run src/index.ts",start:"bun run dist/index.js",biome:"biome check ./src",lint:"bun biome","lint:fix":"bun biome --write","type-check":"tsc --noEmit",check:"bun run lint:fix && bun run type-check",build:"bun build src/index.ts --outdir dist --target bun --minify",test:"bun test",prepack:"bun run build",release:"changeset publish",version:"changeset version",changeset:"changeset"},devDependencies:{"@biomejs/biome":"^2.5.5","@changesets/cli":"^3.0.3","@types/bun":"latest","@types/node":"^24.0.0","bun-types":"latest",typescript:"^7"},dependencies:{"@0xkahi/cli-dye":"^1.1.0","@clack/prompts":"^1.5.1","@toon-format/toon":"^2.3.0","@typesafe-ai/sdk":"^0.7.0",commander:"^15.0.0"}}});var Tn={"test-skill":{description:"A test skill for demonstration purposes.",testOnly:!0},"llw-okf":{alias:"core",description:"the core llm-wiki skill to update, create, enrich, bundles and concepts based on the OKF standard"},"llw-vault-setup":{alias:"setup",description:"set up the files (base, templates, templates config, bundles folder) llw needs inside an existing llm-wiki obsidian vault"},"llw-okf-sync":{alias:"bundle-sync",description:"sync all knowledge bundles in the vault, get outdated bundle.md files for agents to update with directory of contents"}};function dt({testSkills:e}){return Object.entries(Tn).filter(([,t])=>e||!t.testOnly).map(([t,n])=>({skillName:t,entry:n}))}import{existsSync as X,readFileSync as ut,realpathSync as pt,statSync as _e}from"fs";import{dirname as ft,isAbsolute as Bn,join as Z,relative as Mn,resolve as Vn}from"path";import{fileURLToPath as Ln}from"url";var mt="@0xkahi/llw",ht="skill-data",gt="SKILL.md";var Nn=/\]\((sk-references\/[^)\s]+)\)/g;class ee{entries;aliases;skillsDataPathOverride;packageRoot;constructor(e,t={}){let n=new Map,r=new Map;for(let{skillName:i,entry:s}of e){if(n.has(i))throw Error(`Duplicate skill entry: ${i}`);n.set(i,s)}for(let{skillName:i,entry:s}of e){let o=s.alias;if(!o)continue;if(o===i)throw Error(`Skill alias must differ from its skill name: ${i}`);if(n.has(o))throw Error(`Skill alias collides with a skill name: ${o}`);let a=r.get(o);if(a!==void 0)throw Error(`Duplicate skill alias: ${o} (claimed by "${a}" and "${i}")`);r.set(o,i)}this.entries=n,this.aliases=r,this.skillsDataPathOverride=t.skillsDataPath}has(e){return this.entries.has(this.resolveSkillName(e))}getSkillsDataPath(){return this.skillsDataPathOverride??Z(this.getPackageRoot(),ht)}getSkillPath(e){let t=this.resolveSkillName(e);this.getEntry(t);let n=Z(this.getSkillsDataPath(),t);if(!X(n)||!_e(n).isDirectory())throw Error(`Skill folder not found: ${t}`);return n}getSkillFilePath(e){let t=this.resolveSkillName(e),n=Z(this.getSkillPath(t),gt);if(!X(n)||!_e(n).isFile())throw Error(`Skill file not found: ${t}/${gt}`);return n}getSkill(e){let t=this.resolveSkillName(e);this.getEntry(t);let n=this.getSkillPath(t);return ut(this.getSkillFilePath(t),"utf8").replace(Nn,(i,s)=>`](${this.resolveReferencePath(t,n,s)})`)}resolveReferencePath(e,t,n){let r=Vn(t,n);if(ee.assertPathWithinSkillFolder(r,t,n),!X(r)||!_e(r).isFile())throw Error(`Skill reference file not found for skill "${e}": ${n}`);let i=pt(t),s=pt(r);return ee.assertPathWithinSkillFolder(s,i,n),r}resolveSkillName(e){return this.aliases.get(e)??e}getEntry(e){let t=this.entries.get(e);if(!t)throw Error(`Unknown skill: ${e}`);return t}getPackageRoot(){if(this.packageRoot)return this.packageRoot;let e=ft(Ln(import.meta.url));while(!0){let t=Z(e,"package.json"),n=Z(e,ht);if(X(t)&&X(n)){if(JSON.parse(ut(t,"utf8")).name===mt)return this.packageRoot=e,e}let r=ft(e);if(r===e)break;e=r}throw Error(`Unable to locate ${mt} package root`)}static assertPathWithinSkillFolder(e,t,n){let r=Mn(t,e);if(r.startsWith("..")||Bn(r))throw Error(`Skill reference escapes the skill folder: ${n}`)}}var R=new ee(dt({testSkills:process.env.LLW_TEST_SKILLS==="1"})),te=["bundle","log","index"],ne="bases/bundles-index.base",re="bundles",yt="bundle",bt="concept",Se={blue:"#82aaff"},wt="cache";import{existsSync as jn}from"fs";import{homedir as Ot,userInfo as Rn}from"os";import In from"path";var Fn=/\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g;class I{static expandPath(e){let t=e;if(t=t.replace(Fn,(n,r,i)=>{let s=r??i;if(s==="HOME")return Ot();if(s==="USER")return Rn().username;return process.env[s]??n}),t==="~"||t.startsWith("~/")||t.startsWith("~\\"))t=In.join(Ot(),t.slice(1));return t}static findFile(e){if(jn(e))return{exists:!0,path:e};return{exists:!1,path:e}}}import{readdir as Hn}from"fs/promises";var{$:Dn}=globalThis.Bun;class ie{static parseBaseMeta(e){return{title:e.title,folder:e.folder,path:e.path,description:e.description,triggers:e.triggers?e.triggers.split(",").map((t)=>t.trim()):[],parent:e.parent,parentFolder:ie.parseParentFolder(e.parent)}}static parseBundleProps(e){return{...e,parentFolder:ie.parseParentFolder(e.parent)}}static parseParentTitle(e){if(!e)return null;return e.match(/\|([^\]]+)\]\]$/)?.[1]??null}static parseParentFolder(e){if(!e)return null;return e.match(/^\[\[(.+)\/bundle(?:\.md)?(?:\|[^\]]+)?\]\]$/)?.[1]??null}}class F{static getTasksStatusSymbol(e){switch(e){case"pending":return" ";case"completed":return"x";case"ignored":return"-";default:throw Error(`Unknown Obsidian task status: ${e}`)}}static parseInputToTagProperty(e){return`[${e.split(",").map((r)=>r.trim()).filter((r)=>r.length>0).map((r)=>`"${r}"`).join(",")}]`}}function Ct({fileName:e,extension:t}){if(e.endsWith(t))return e.slice(0,-t.length);return e}class p{static vaultBaseCli(e){let t=["vault=llm-wiki",...e];return Dn`obsidian ${t}`}static async getVaultPath(){return(await p.vaultBaseCli(["vault","info=path"]).text()).trim()}static async getTaskCount(e,t){let r=await p.vaultBaseCli(["tasks",`path=${e}`,`status=${F.getTasksStatusSymbol(t)}`,"total"]).text();return Number(r.trim())}static async getBundleFolders(){let e=p.vaultBaseCli(["base:query",`path=${ne}`,"format=paths"]),t=new Set;for await(let n of e.lines()){let r=n.trim();if(r)t.add(r.replace(/\/bundle\.md$/,""))}return t}static async getAllBundles(){return(await p.vaultBaseCli(["base:query",`path=${ne}`,"format=json"]).json()).map((n)=>ie.parseBaseMeta(n))}static async getBundleMap(){let e=new Map,t=await p.getAllBundles();for(let n of t)e.set(n.folder,n);return e}static async getBundleConcepts({bundle:e,vaultPath:t}){let n=`${t}/${e}`;return(await Hn(n,{withFileTypes:!0})).filter((s)=>s.isFile()&&s.name.endsWith(".md")).map((s)=>Ct({fileName:s.name,extension:".md"})).filter((s)=>!te.includes(s))}static async getConceptProperties({bundle:e,concept:t}){return await p.vaultBaseCli(["properties",`path=${e}/${t}.md`,"format=json"]).json()}static async getBundleProperties(e){return await p.vaultBaseCli(["properties",`path=${e}/bundle.md`,"format=json"]).json()}static async setProperties({path:e,name:t,value:n,type:r}){await p.vaultBaseCli(["property:set",`path=${e}`,`name=${t}`,`value=${n}`,`type=${r}`])}}var q={json:"json",toon:"toon"},k=[{flag:`--format -f <${Object.values(q).join("|")}>`,description:`output format (default: ${q.toon})`,default:q.toon},{flag:"--pretty",description:"pretty-print output (optional)"}];class ve{static validateOutputFormat(e){let t=Object.values(q).find((n)=>n===e);if(!t)return console.error(`Error: invalid output format "${e}", must be one of ${Object.values(q)}`),{valid:!1,format:"toon"};return{valid:!0,format:t}}}class h extends ve{static async isValidBundle(e,t){let n=await p.getBundleFolders();if(!n.has(e)){if(!t)console.error(`Error: bundle "${e}" path not a valid bundle`),console.error(`DEBUG: bundle "${e}" either has a missing bundle.md file or bundle dir does not exists`),console.error(`DEBUG: current available bundles "${Array.from(n)}"`);return!1}return!0}static isValidConceptName(e){if(e.endsWith(".md")===!0)return console.error("ERROR: DO NOT include the .md extension in the concept name, it will be handled by the script"),!1;if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))return console.error(`Error: invalid concept name "${e}", must be lowercase snake/kebab-case with no spaces`),!1;if(te.includes(e))return console.error(`Error: invalid concept name "${e}", it is a reserved file name`),console.error(`DEBUG: reserved file names "${te}"`),!1;return!0}static async isValidConcept({bundle:e,concept:t}){let n=await p.getVaultPath(),r=`${e}/${t}.md`,i=`${n}/${r}`;if(I.findFile(i).exists)return{valid:!0,fullConceptPath:i};return{valid:!1,fullConceptPath:i}}static async validateBundleAndGetChildren(e){let t=await p.getAllBundles(),n=t.find((i)=>i.folder===e);if(!n)return console.error(`Error: bundle "${e}" path not a valid bundle`),console.error(`DEBUG: bundle "${e}" either has a missing bundle.md file or bundle dir does not exists`),console.error(`DEBUG: current available bundles "${t.map((i)=>i.folder)}"`),{children:[]};let r=t.filter((i)=>i.parentFolder===n.folder);return{validBundle:n,children:r}}}var Un=/^[a-z0-9][a-z0-9_-]*$/;class Ee{config={name:"create",description:"Create a new bundle.md file and set its properties",args:[{name:"<bundle_folder>",description:"bundle folder path"}],options:[{flag:"--description <description>",description:"bundle description",required:!0},{flag:"--triggers [triggers]",description:"comma separated bundle triggers (optional)"},{flag:"--parent [parent_bundle_folder]",description:"parent bundle folder path (optional)"}]};async execute(e,t){let{description:n,triggers:r,parent:i}=t,s=e.split("/");if(s[0]!==re)console.error(`Error: bundle must be created in the "${re}" folder`),process.exit(1);if(s.length<2)console.error(`Error: cannot create a bundle at the root of the "${re}" folder, provide a bundle name (e.g. "${re}/my-bundle")`),process.exit(1);if(!s.slice(1).every((l)=>Un.test(l)))console.error(`Error: invalid bundle path "${e}", folder names must be lowercase snake/kebab-case (no spaces, no empty segments, no trailing slash)`),process.exit(1);if(i){if(!await h.isValidBundle(i))console.error(`Error: parent bundle "${i}" not a valid bundle`),process.exit(1)}if(await h.isValidBundle(e,!0))console.error(`Error: bundle "${e}" bundle.md already exists`),process.exit(1);await p.vaultBaseCli(["create","name=bundle",`path=${e}`,`template=${yt}`]);let a=`${e}/bundle.md`,d=e.split("/").pop()||"";if(await p.setProperties({path:a,name:"title",value:d,type:"text"}),await p.setProperties({path:a,name:"description",value:n,type:"text"}),r)await p.setProperties({path:a,name:"triggers",value:r,type:"list"});if(i){let l=i.split("/").pop()||"";await p.setProperties({path:a,name:"parent",value:`[[${i}/bundle|${l}]]`,type:"text"})}}}var qn={comma:",",tab:"\t",pipe:"|"},ae=qn.comma;function St(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001F]/g,(t)=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function Gn(e){return e==="true"||e==="false"||e==="null"}function vt(e,t,n){if(t==="__proto__"){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function T(e){if(e===null)return null;if(typeof e==="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON==="function"){let t=e.toJSON();if(t!==e)return T(t)}if(typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number"){if(Object.is(e,-0))return 0;if(!Number.isFinite(e))return null;return e}if(typeof e==="bigint"){if(e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER)return Number(e);return e.toString()}if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(T);if(e instanceof Set)return Array.from(e).map(T);if(e instanceof Map)return Object.fromEntries(Array.from(e,([t,n])=>[String(t),T(n)]));if(Wn(e)){let t={};for(let n in e)if(Object.hasOwn(e,n))vt(t,n,T(e[n]));return t}return null}function H(e){return e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function V(e){return Array.isArray(e)}function E(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function se(e){return Object.keys(e).length===0}function Wn(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function oe(e){return e.length===0||e.every((t)=>H(t))}function Kn(e){return e.length===0||e.every((t)=>V(t))}function Et(e){return e.length===0||e.every((t)=>E(t))}var zn=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Jn=/^0\d+$/;function Yn(e){return/^[A-Z_][\w.]*$/i.test(e)}function Qn(e){return/^[A-Z_]\w*$/i.test(e)}function Xn(e,t=ae){if(!e)return!1;if(e!==e.trim())return!1;if(Gn(e)||Zn(e))return!1;if(e.includes(":"))return!1;if(e.includes('"')||e.includes("\\"))return!1;if(/[[\]{}]/.test(e))return!1;if(/[\u0000-\u001F]/.test(e))return!1;if(e.includes(t))return!1;if(e.startsWith("-"))return!1;return!0}function Zn(e){return zn.test(e)||Jn.test(e)}var Is=Symbol("quotedKey");function er(e,t,n,r,i,s,o){if(r.keyFolding!=="safe")return;if(!E(t))return;let{segments:a,tail:d,leafValue:l}=tr(e,t,o??r.flattenDepth);if(a.length<2)return;if(!a.every((m)=>Qn(m)))return;let c=nr(a),u=s?`${s}.${c}`:c;if(n.includes(c))return;if(i&&i.has(u))return;return{foldedKey:c,remainder:d,leafValue:l,segmentCount:a.length}}function tr(e,t,n){let r=[e],i=t;while(r.length<n){if(!E(i))break;let s=Object.keys(i);if(s.length!==1)break;let o=s[0],a=i[o];r.push(o),i=a}if(!E(i)||se(i))return{segments:r,tail:void 0,leafValue:i};return{segments:r,tail:i,leafValue:i}}function nr(e){return e.join(".")}function W(e,t){if(e===null)return"null";if(typeof e==="boolean")return String(e);if(typeof e==="number")return String(e);return rr(e,t)}function rr(e,t=ae){if(Xn(e,t))return e;return`"${St(e)}"`}function K(e){if(Yn(e))return e;return`"${St(e)}"`}function $t(e,t=ae){return e.map((n)=>W(n,t)).join(t)}function D(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??",",s="";if(n!=null)s+=K(n);if(s+=`[${e}${i!==ae?i:""}]`,r){let o=r.map((a)=>K(a));s+=`{${o.join(i)}}`}return s+=":",s}function*ir(e,t,n){if(H(e)){let r=W(e,t.delimiter);if(r!=="")yield r;return}if(V(e))yield*$e(void 0,e,n,t);else if(E(e))yield*G(e,n,t)}function*G(e,t,n,r,i,s){let o=Object.keys(e);if(t===0&&!r)r=new Set(o.filter((d)=>d.includes(".")));let a=s??n.flattenDepth;for(let[d,l]of Object.entries(e))yield*sr(d,l,t,n,o,r,i,a)}function*sr(e,t,n,r,i,s,o,a){let d=o?`${o}.${e}`:e,l=a??r.flattenDepth;if(r.keyFolding==="safe"&&i){let u=er(e,t,i,r,s,o,l);if(u){let{foldedKey:m,remainder:g,leafValue:b,segmentCount:S}=u,M=K(m);if(g===void 0){if(H(b)){yield _(n,`${M}: ${W(b,r.delimiter)}`,r.indent);return}else if(V(b)){yield*$e(m,b,n,r);return}else if(E(b)&&se(b)){yield _(n,`${M}:`,r.indent);return}}if(E(g)){yield _(n,`${M}:`,r.indent);let Ce=l-S,j=o?`${o}.${m}`:m;yield*G(g,n+1,r,s,j,Ce);return}}}let c=K(e);if(H(t))yield _(n,`${c}: ${W(t,r.delimiter)}`,r.indent);else if(V(t))yield*$e(e,t,n,r);else if(E(t)){if(yield _(n,`${c}:`,r.indent),!se(t))yield*G(t,n+1,r,s,d,l)}}function*$e(e,t,n,r){if(t.length===0){yield _(n,e!=null?`${K(e)}: []`:"[]",r.indent);return}if(oe(t)){yield _(n,ue(t,r.delimiter,e),r.indent);return}if(Kn(t)){if(t.every((i)=>oe(i))){yield*or(e,t,n,r);return}}if(Et(t)){let i=xt(t);if(i)yield*ar(e,t,i,n,r);else yield*_t(e,t,n,r);return}yield*_t(e,t,n,r)}function*or(e,t,n,r){yield _(n,D(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let i of t)if(oe(i)){let s=ue(i,r.delimiter);yield A(n+1,s,r.indent)}}function ue(e,t,n){let r=D(e.length,{key:n,delimiter:t}),i=$t(e,t);if(e.length===0)return r;return`${r} ${i}`}function*ar(e,t,n,r,i){yield _(r,D(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*kt(t,n,r+1,i)}function xt(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length===0)return;if(lr(e,n))return n}function lr(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let r of t){if(!Object.hasOwn(n,r))return!1;if(!H(n[r]))return!1}}return!0}function*kt(e,t,n,r){for(let i of e)yield _(n,$t(t.map((s)=>i[s]),r.delimiter),r.indent)}function*_t(e,t,n,r){yield _(n,D(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let i of t)yield*xe(i,n+1,r)}function*cr(e,t,n){if(se(e)){yield _(t,"-",n.indent);return}let r=Object.entries(e),[i,s]=r[0],o=r.slice(1);if(V(s)&&Et(s)){let d=xt(s);if(d){if(yield A(t,D(s.length,{key:i,fields:d,delimiter:n.delimiter}),n.indent),yield*kt(s,d,t+2,n),o.length>0)yield*G(Object.fromEntries(o),t+1,n);return}}let a=K(i);if(H(s))yield A(t,`${a}: ${W(s,n.delimiter)}`,n.indent);else if(V(s))if(s.length===0)yield A(t,`${a}: []`,n.indent);else if(oe(s))yield A(t,`${a}${ue(s,n.delimiter)}`,n.indent);else{yield A(t,`${a}${D(s.length,{delimiter:n.delimiter})}`,n.indent);for(let d of s)yield*xe(d,t+2,n)}else if(E(s)){if(yield A(t,`${a}:`,n.indent),!se(s))yield*G(s,t+2,n)}if(o.length>0)yield*G(Object.fromEntries(o),t+1,n)}function*xe(e,t,n){if(H(e))yield A(t,W(e,n.delimiter),n.indent);else if(V(e))if(oe(e))yield A(t,ue(e,n.delimiter),n.indent);else{yield A(t,D(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*xe(r,t+1,n)}else if(E(e))yield*cr(e,t,n)}function _(e,t,n){return" ".repeat(n*e)+t}function A(e,t,n){return _(e,"- "+t,n)}function dr(e,t){let n=t("",e,[]);if(n===void 0)return de(e,t,[]);return de(T(n),t,[])}function de(e,t,n){if(E(e))return ur(e,t,n);if(V(e))return pr(e,t,n);return e}function ur(e,t,n){let r={};for(let[i,s]of Object.entries(e)){let o=[...n,i],a=t(i,s,o);if(a===void 0)continue;vt(r,i,de(T(a),t,o))}return r}function pr(e,t,n){let r=[];for(let i=0;i<e.length;i++){let s=e[i],o=[...n,i],a=t(String(i),s,o);if(a===void 0)continue;let d=T(a);r.push(de(d,t,o))}return r}function ke(e,t){return Array.from(fr(e,t)).join(`
4
+ `)}function fr(e,t){let n=T(e),r=mr(t);return ir(r.replacer?dr(n,r.replacer):n,r,0)}function mr(e){return{indent:e?.indent??2,delimiter:e?.delimiter??ae,keyFolding:e?.keyFolding??"off",flattenDepth:e?.flattenDepth??Number.POSITIVE_INFINITY,replacer:e?.replacer}}function v(e,t){switch(t.type){case"json":return gr(e,t.compact);case"toon":return hr(e,t)}}function hr(e,{compact:t,replacer:n}){if(t)return ke(e,{keyFolding:"safe",replacer:n??yr});return ke(e,n?{replacer:n}:void 0)}function gr(e,t){if(t)return JSON.stringify(e,null);return JSON.stringify(e,null,2)}function yr(e,t){if(Array.isArray(t)&&t.every((n)=>typeof n==="string"))return t.length>0?`arr(${t.length})<${t.join("|")}>`:null;return t}class Ae{config={name:"list",alias:"ls",description:"View all bundles in the Knowledge Base",options:[...k]};async execute(e){let{valid:t,format:n}=h.validateOutputFormat(e.format);if(!t)process.exit(1);let i={bundles:await p.getAllBundles()},s=v(i,{type:n,compact:!e.pretty});console.log(s)}}import{rename as br}from"fs/promises";class Pe{config={name:"rename",description:"Rename Bundle title and bundle folder",options:[{flag:"--bundle <bundle_folder>",description:"bundle folder path",required:!0},{flag:"--title <title>",description:"new bundle title",required:!0}]};async execute(e){let{bundle:t,title:n}=e;if(!await h.isValidBundle(t))process.exit(1);let o=`${t.split("/").slice(0,-1).join("/")}/${n}`;if(await h.isValidBundle(o,!0))console.error(`Error: bundle "${o}" already exists`),process.exit(1);let d=await p.getVaultPath(),l=`${t}/bundle.md`;await p.setProperties({path:l,name:"title",value:n,type:"text"});let c=`${d}/${t}`,u=`${d}/${o}`;await br(c,u);let m=["Bundle renamed successfully:",`- Old bundle path: ${c}`,`- New bundle path: ${u}`,`- bundle changed from ${t} -> ${o}`];console.log(m.join(`
5
+ `))}}import{createHash as Mr}from"crypto";import{mkdir as Vr,readFile as Lr,rm as jt,writeFile as Be}from"fs/promises";var O="\x1B[",wr=new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`,"g"),Or=/^#(?:[\da-f]{3}|[\da-f]{6})$/i,Bt=Symbol("dye.stylePlan"),Mt={reset:{id:"reset",open:`${O}0m`,close:`${O}0m`,cacheable:!0},bold:{id:"bold",open:`${O}1m`,close:`${O}22m`,cacheable:!0},dim:{id:"dim",open:`${O}2m`,close:`${O}22m`,cacheable:!0},italic:{id:"italic",open:`${O}3m`,close:`${O}23m`,cacheable:!0},underline:{id:"underline",open:`${O}4m`,close:`${O}24m`,cacheable:!0},inverse:{id:"inverse",open:`${O}7m`,close:`${O}27m`,cacheable:!0},hidden:{id:"hidden",open:`${O}8m`,close:`${O}28m`,cacheable:!0},strikethrough:{id:"strikethrough",open:`${O}9m`,close:`${O}29m`,cacheable:!0}},At={black:30,red:31,green:32,yellow:33,blue:34,magenta:35,cyan:36,white:37,gray:90,brightBlack:90,brightRed:91,brightGreen:92,brightYellow:93,brightBlue:94,brightMagenta:95,brightCyan:96,brightWhite:97};function Vt(e){let t={};for(let n of Object.keys(At)){let r=At[n]+(e?10:0),i=e?"bg":"fg";t[n]=Object.freeze({id:`${i}:${n}`,open:`${O}${r}m`,close:`${O}${e?49:39}m`,cacheable:!0})}return Object.freeze(t)}var Cr=Vt(!1),_r=Vt(!0);function Sr(){if(typeof process>"u"||!process?.env)return!1;let{env:e}=process;if("NO_COLOR"in e||e.TERM==="dumb")return!1;if("FORCE_COLOR"in e)return e.FORCE_COLOR!=="0";return Boolean(process.stdout?.isTTY)}var vr=Sr(),Pt;function pe(e,t){if(typeof e==="string")return t?_r[e]:Cr[e];return{id:t?"bg":"fg",open:`${O}${t?48:38};2;${e.r};${e.g};${e.b}m`,close:`${O}${t?49:39}m`,cacheable:!1}}function Er(e){let t="",n="",r=new Map,i=!0,s="";for(let o of e)t+=o.open,r.set(o.close,(r.get(o.close)??"")+o.open),i&&=o.cacheable,s+=`${o.id}|`;for(let o of[...e].reverse())n+=o.close;return Object.freeze({blocks:Object.freeze([...e]),open:t,close:n,restorations:Object.freeze([...r].map(([o,a])=>Object.freeze({close:o,reopen:a}))),cacheKey:i?s:void 0})}function $r(e,t){if(!f.enabled||t.blocks.length===0)return e;let n=e;if(n.includes("\x1B")){for(let r of t.restorations)if(n.includes(r.close))n=n.replaceAll(r.close,r.close+r.reopen)}return t.open+n+t.close}var Tt=new Map;function Lt(e,t,n){let r=e[Bt],i=Mt[t],s=r.blocks.some((o)=>o.id===i.id)?e:Te([...r.blocks,i]);return n===void 0?s:s(n)}var Nt={};for(let e of Object.keys(Mt))Nt[e]=function(t){return Lt(this,e,t)};function Te(e){let t="";for(let i of e){if(!i.cacheable){t="";break}t+=`${i.id}|`}if(e.length===0||t!==""){let i=Tt.get(t);if(i!==void 0)return i}let n=Er(e),r=(i)=>$r(i,n);if(Object.defineProperty(r,Bt,{value:n}),Object.assign(r,Nt),n.cacheKey!==void 0)Tt.set(n.cacheKey,r);return r}function xr(e){let t=[];if(e.fg!==void 0)t.push(pe(e.fg,!1));if(e.bg!==void 0)t.push(pe(e.bg,!0));return t}function kr(e){return Te(xr(e))}function Ar(e,t){if(!f.enabled||t.fg===void 0&&t.bg===void 0)return e;let n=t.fg===void 0?void 0:pe(t.fg,!1),r=t.bg===void 0?void 0:pe(t.bg,!0),i=e;if(i.includes("\x1B")){if(n!==void 0&&i.includes(n.close))i=i.replaceAll(n.close,n.close+n.open);if(r!==void 0&&i.includes(r.close))i=i.replaceAll(r.close,r.close+r.open)}return(n?.open??"")+(r?.open??"")+i+(r?.close??"")+(n?.close??"")}function Pr(e){if(!Or.test(e))throw TypeError(`Invalid hexadecimal color: ${e}`);let t=e.slice(1),n=t.length===3?[...t].map((r)=>r+r).join(""):t;return Object.freeze({r:Number.parseInt(n.slice(0,2),16),g:Number.parseInt(n.slice(2,4),16),b:Number.parseInt(n.slice(4,6),16)})}var Tr=Te([]);function Br(e={},t={}){return typeof e==="string"?Ar(e,t):kr(e)}function L(e){return(t)=>Lt(Tr,e,t)}var f={get enabled(){return Pt??vr},setEnabled(e){Pt=e},hex:Pr,strip(e){return e.replace(wr,"")},colorize:Br,reset:L("reset"),bold:L("bold"),dim:L("dim"),italic:L("italic"),underline:L("underline"),inverse:L("inverse"),hidden:L("hidden"),strikethrough:L("strikethrough")};var{$:Nr}=globalThis.Bun;class Me{config={name:"sync",description:"Sync All Knowledge Bundles And Generate A Hash Map",options:[{flag:"--reset",description:"remove the generated hash map and sync tasklist"}]};async execute({reset:e}){let t=await p.getVaultPath(),n=`${wt}/bundles`,r=`${t}/${n}`;await Vr(r,{recursive:!0});let i=I.findFile(`${r}/hash_map.json`);if(!i.exists)await Be(i.path,`${JSON.stringify({},null,2)}
6
+ `);let s=await p.getBundleFolders(),o=await this.getBundleHashMap(s),a=await this.getOutOfSyncBundles(i.path,o),d=e||a.length===0,l=I.findFile(`${r}/generated_hash_map.json`);if(!l.exists&&!d)await this.generateNewHashMap(l.path,o);let c=`${n}/task.md`,u=I.findFile(`${t}/${c}`);if(!u.exists&&!d)await this.generateSyncTasks(u.path,a);let m=0,g=0,b=0;if(e===!0)await Promise.all([jt(l.path,{force:!0}),jt(u.path,{force:!0})]);else if(u.exists)m=await p.getTaskCount(c,"pending"),g=await p.getTaskCount(c,"completed"),b=await p.getTaskCount(c,"ignored");else m=a.length;let M=[f.colorize({fg:"magenta"}).bold("Bundle Sync Manifest"),"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",f.bold("Summary:"),` ${f.colorize("\u25CF",{fg:"cyan"})} Knowledge Bundles: ${s.size} total, ${a.length} outOfSync`,` ${f.colorize("\u25CF",{fg:"yellow"})} Pending Tasks: ${m} in progress`,` ${f.colorize("\u25CF",{fg:"green"})} Completed Tasks: ${g}`,` ${f.colorize("\u25CF",{fg:"red"})} Ignored Tasks: ${b}`,"",f.colorize({fg:"brightBlue"}).bold("FilePaths"),"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",`currentHashMap: ${f.colorize(i.path,{fg:"brightCyan"})}`,`generatedHashMap: ${f.colorize(l.path,{fg:"brightCyan"})}${d?" (not generated)":""}`,`taskList: ${f.colorize(u.path,{fg:"brightCyan"})} ${d?" (not generated)":""}`,"","\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"].join(`
7
+ `);console.log(M)}async getOutOfSyncBundles(e,t){let n=Object.keys(t),r=await Lr(e,"utf-8"),s=JSON.parse(r)?.bundles;if(!s)return n;let o=[];for(let a of n){let d=s[a],l=t[a];if(d!==l)o.push(a)}return o}async generateSyncTasks(e,t){let n=["# Bundle Sync Tasks","","This file is generated by the sync command. and list potentially out of sync bundles","",...t.map((r,i)=>`${i+1}. [ ] ${r}`)];await Be(e,n.join(`
8
+ `))}async generateNewHashMap(e,t){let n={generatedTimestamp:new Date().toISOString(),bundles:t};await Be(e,`${JSON.stringify(n,null,2)}
9
+ `)}async getBundleHashMap(e){let t={};for(let n of e){let r=await this.getBundleViewText(n),i=Mr("md5").update(r).digest("hex");t[n]=i}return t}async getBundleViewText(e){return(await Nr`llw bundle view --bundle ${e}`.text()).trim()}}var jr=["path","folder","description","triggers"];class Ve{config={name:"tree",description:"View all bundles in the Knowledge Base as a tree structure",options:[{flag:"--verbose -V [value]",description:"return tree as verbose format"}]};async execute(e){let{verbose:t}=e,n=await p.getBundleMap(),r=this.buildHierarchy(n),i=["bundles"],s=r.get(null)??[];s.forEach((o,a)=>{this.renderNode({bundle:o,childrenByParent:r,lines:i,prefix:"",numberPath:`${a+1}`,isLast:a===s.length-1,verbose:t===!0})}),console.log(i.join(`
10
+ `))}buildHierarchy(e){let t=new Map;for(let n of e.values()){let r=n.parentFolder;if(r!==null&&!e.has(r))r=null;let i=t.get(r)??[];i.push(n),t.set(r,i)}for(let n of t.values())n.sort((r,i)=>r.title.localeCompare(i.title));return t}renderNode(e){let{bundle:t,childrenByParent:n,lines:r,prefix:i,numberPath:s,isLast:o,verbose:a}=e,d=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";r.push(`${i}${d}${s}. ${t.title}`);let l=i+(o?" ":"\u2502 "),c=n.get(t.folder)??[];if(a){let u=l+(c.length>0?"\u2502 ":" ");for(let m of jr){let g=t[m],b="null";if(typeof g==="string")b=`"${g}"`;if(Array.isArray(g))b=`[${g.map((S)=>`"${S}"`).join(", ")}]`;r.push(`${u}* ${m}: ${b}`)}}c.forEach((u,m)=>{this.renderNode({bundle:u,childrenByParent:n,lines:r,prefix:l,numberPath:`${s}.${m+1}`,isLast:m===c.length-1,verbose:a})})}}class Le{config={name:"update",description:"Update Bundle Metadata (only sets provided properties)",options:[{flag:"--bundle <bundle_folder>",description:"bundle folder path",required:!0},{flag:"--description [description]",description:"bundle description (optional)"},{flag:"--triggers [triggers]",description:"comma separated bundle triggers (optional)"},{flag:"--parent [parent_bundle_folder]",description:"parent bundle folder path (optional)"}]};async execute(e){let{bundle:t,description:n,triggers:r,parent:i}=e;if(!n&&!r&&!i)console.error("Error: no properties provided to update, provide at least one of --description, --triggers, --parent"),process.exit(1);if(!await h.isValidBundle(t))process.exit(1);if(i){if(!await h.isValidBundle(i))console.error(`Error: parent bundle "${i}" not a valid bundle`),process.exit(1)}let o=`${t}/bundle.md`;if(n)await p.setProperties({path:o,name:"description",value:n,type:"text"});if(r)await p.setProperties({path:o,name:"triggers",value:r,type:"list"});if(i){let a=i.split("/").pop()||"";await p.setProperties({path:o,name:"parent",value:`[[${i}/bundle|${a}]]`,type:"text"})}}}class Ne{config={name:"view",description:"View Bundle Metadata, Concept, Child Bundles",options:[{flag:"--bundle <bundle_folder>",description:"bundle folder path",required:!0},...k]};async execute(e){let{bundle:t}=e,{valid:n,format:r}=h.validateOutputFormat(e.format);if(!n)process.exit(1);let{validBundle:i,children:s}=await h.validateBundleAndGetChildren(t);if(!i)process.exit(1);let o=await p.getVaultPath(),a=await this.getBundleConcepts({bundle:t,vaultPath:o}),d={...i,concepts:a,childBundles:s},l=v(d,{type:r,compact:!e.pretty});console.log(l)}async getBundleConcepts({bundle:e,vaultPath:t}){let n=`${t}/${e}`,r=await p.getBundleConcepts({bundle:e,vaultPath:t}),i=[];for(let s of r){let o=await p.getConceptProperties({bundle:e,concept:s}),a=`${n}/${s}.md`;i.push({...o,fullpath:a})}return i}}class je{config={name:"bundle",description:"Knowledge Bundle Commands",subCommands:[new Ae,new Ve,new Ne,new Ee,new Le,new Me,new Pe]}}class Re{config={name:"create",description:"Create a new concept file and set its properties",args:[{name:"<concept_name>",description:"concept name (without .md extension)"}],options:[{flag:"--bundle <bundle_folder>",description:"bundle folder path",required:!0},{flag:"--type <type>",description:"concept type",required:!0},{flag:"--description <description>",description:"concept description",required:!0},{flag:"--resource [resource]",description:"concept resource (optional)"},{flag:"--tags [tags]",description:"comma separated concept tags (optional)"}]};async execute(e,t){let{bundle:n,type:r,description:i,resource:s,tags:o}=t;if(!await h.isValidBundle(n))process.exit(1);if(!h.isValidConceptName(e))process.exit(1);let{valid:d,fullConceptPath:l}=await h.isValidConcept({bundle:n,concept:e});if(d)console.error(`Error: concept "${e}" already exists at path "${l}"`),process.exit(1);await p.vaultBaseCli(["create",`name=${e}`,`path=${n}`,`template=${bt}`]);let c=`${n}/${e}.md`;if(await p.setProperties({path:c,name:"title",value:e,type:"text"}),await p.setProperties({path:c,name:"type",value:r,type:"text"}),await p.setProperties({path:c,name:"description",value:i,type:"text"}),s)await p.setProperties({path:c,name:"resource",value:s,type:"text"});if(o)await p.setProperties({path:c,name:"tags",value:F.parseInputToTagProperty(o),type:"tags"});console.info("INFO: Full path to concept file for writing content:",`'${l}'`)}}class Ie{config={name:"open",description:"Open a concept file in Obsidian",args:[{name:"<concept_name>",description:"concept name"}],options:[{flag:"--bundle <bundle_folder>",description:"bundle folder path",required:!0}]};async execute(e,t){let{bundle:n}=t;if(!await h.isValidBundle(n))process.exit(1);if(!h.isValidConceptName(e))process.exit(1);let{valid:i,fullConceptPath:s}=await h.isValidConcept({bundle:n,concept:e});if(!i)console.error(`Error: concept "${e}" does not exists at path "${s}"`),process.exit(1);await p.vaultBaseCli(["open",`path=${n}/${e}.md`])}}var Rr=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/;class Fe{config={name:"update",description:"Update Concept Metadata (only sets provided properties)",args:[{name:"<concept_name>",description:"concept name (without .md extension)"}],options:[{flag:"--bundle <bundle_folder>",description:"bundle folder path",required:!0},{flag:"--type [type]",description:"concept type (optional)"},{flag:"--description [description]",description:"concept description (optional)"},{flag:"--resource [resource]",description:"concept resource (optional)"},{flag:"--tags [tags]",description:"comma separated concept tags (optional)"},{flag:"--timestamp [timestamp]",description:"timestamp value (YYYY-MM-DDTHH:mm), pass without a value to use now (optional)"}]};async execute(e,t){let{bundle:n,type:r,description:i,resource:s,tags:o,timestamp:a}=t;if(!r&&!i&&!s&&!o&&!a)console.error("Error: no properties provided to update, provide at least one of --type, --description, --resource, --tags, --timestamp"),process.exit(1);if(typeof a==="string"&&!Rr.test(a))console.error(`Error: invalid timestamp value "${a}", expected format YYYY-MM-DDTHH:mm (e.g. 2026-07-02T03:37)`),process.exit(1);if(!await h.isValidBundle(n))process.exit(1);if(!h.isValidConceptName(e))process.exit(1);let{valid:l,fullConceptPath:c}=await h.isValidConcept({bundle:n,concept:e});if(!l)console.error(`Error: concept "${e}" does not exists at path "${c}"`),process.exit(1);let u=`${n}/${e}.md`;if(r)await p.setProperties({path:u,name:"type",value:r,type:"text"});if(i)await p.setProperties({path:u,name:"description",value:i,type:"text"});if(s)await p.setProperties({path:u,name:"resource",value:s,type:"text"});if(o)await p.setProperties({path:u,name:"tags",value:F.parseInputToTagProperty(o),type:"tags"});if(a){let m=new Date,g=(S)=>String(S).padStart(2,"0"),b=typeof a==="string"?a:`${m.getFullYear()}-${g(m.getMonth()+1)}-${g(m.getDate())}T${g(m.getHours())}:${g(m.getMinutes())}`;await p.setProperties({path:u,name:"timestamp",value:b,type:"datetime"})}console.info("INFO: Full path to concept file for writing content:",`'${c}'`)}}class He{config={name:"view",description:"View Concept Metadata",args:[{name:"<concept_name>",description:"concept name"}],options:[{flag:"--bundle <bundle_folder>",description:"bundle folder path",required:!0},...k]};async execute(e,t){let{bundle:n}=t,{valid:r,format:i}=h.validateOutputFormat(t.format);if(!r)process.exit(1);if(!await h.isValidBundle(n))process.exit(1);if(!h.isValidConceptName(e))process.exit(1);let{valid:o,fullConceptPath:a}=await h.isValidConcept({bundle:n,concept:e});if(!o)console.error(`Error: concept "${e}" does not exists at path "${a}"`),process.exit(1);let l={...await p.getConceptProperties({bundle:n,concept:e}),fullpath:a},c=v(l,{type:i,compact:!t.pretty});console.log(c)}}class De{config={name:"concept",description:"Knowledge Bundle Concept Commands",subCommands:[new He,new Re,new Fe,new Ie]}}var Ge=(e)=>e.get("x-typesafe-request-id")??void 0,Yt=class e extends Promise{#e;#r;#t;constructor(t,n){super((r)=>r(void 0));this.#e=t,this.#r=n}asResponse(){return this.#e}async withResponse(){let[t,n]=await Promise.all([this.#n(),this.#e]);return{data:t,response:n,requestId:Ge(n.headers)}}map(t){return new e(this.#e,()=>this.#n().then(t))}#n(){return this.#t??=this.#e.then(this.#r),this.#t}then(t,n){return this.#n().then(t,n)}catch(t){return this.#n().catch(t)}finally(t){return this.#n().finally(t)}},Ir=(e,t)=>Array.from({length:t-e},(n,r)=>e+r),ge={maxRetries:2,backoffInitialMs:500,backoffMaxMs:5000,backoffJitter:0.25,httpStatuses:new Set([408,429,...Ir(500,600)]),respectRetryAfter:!0,maxRetryAfterMs:60000,apiConnectionError:!0,apiTimeoutError:!0};ge.maxRetries;var Fr=(e,t=ge)=>t.httpStatuses.has(e),Qt=(e,t=Date.now())=>{let n=Number(e.get("retry-after-ms"));if(e.has("retry-after-ms")&&Number.isFinite(n)&&n>=0)return n;let r=e.get("retry-after");if(r===null)return;let i=Number(r);if(Number.isFinite(i))return i>=0?i*1000:void 0;let s=Date.parse(r);if(!Number.isNaN(s))return Math.max(0,s-t)},Hr=(e,t,n=ge,r=Math.random)=>{if(n.respectRetryAfter&&t!==void 0){let s=Qt(t);if(s!==void 0&&s<=n.maxRetryAfterMs)return s}let i=Math.min(n.backoffInitialMs*2**e,n.backoffMaxMs);return Math.round(i*(1-r()*n.backoffJitter))},Dr=(e,t)=>new Promise((n,r)=>{if(t?.aborted)return r(t.reason);let i=()=>{clearTimeout(s),r(t?.reason)},s=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);t?.addEventListener("abort",i,{once:!0})}),w=class extends Error{constructor(e,t){super(e,t);this.name=new.target.name}},he=(e)=>typeof e==="object"&&e!==null,Ur=(e)=>{if(typeof e==="string")return e||void 0;if(!he(e))return;let{error:t,message:n,detail:r}=e;if(typeof t==="string")return t;if(he(t)&&typeof t.message==="string")return t.message;if(typeof n==="string")return n;if(typeof r==="string")return r;if(he(r)&&typeof r.message==="string")return r.message;if(Array.isArray(r))return qr(r)},qr=(e)=>{let t=e.flatMap((n)=>{if(!he(n)||typeof n.msg!=="string")return[];let r=Array.isArray(n.loc)?n.loc.filter((i)=>i!=="body").join("."):"";return[r?`${r}: ${n.msg}`:n.msg]});return t.length>0?t.join("; "):void 0},Rt=200,N=class e extends w{status;headers;body;requestId;constructor(t,n,r,i){super(i??e.describe(t,n));this.status=t,this.body=n,this.headers=r,this.requestId=Ge(r)}static describe(t,n){let r=Ur(n);if(r)return`${t} ${r}`;if(n===void 0)return`${t} status code (no body)`;let i=typeof n==="string"?n:JSON.stringify(n);return`${t} ${i.length>Rt?`${i.slice(0,Rt)}\u2026`:i}`}static fromResponse(t,n,r){if(t===400)return new Gr(t,n,r);if(t===401)return new Wr(t,n,r);if(t===403)return new Kr(t,n,r);if(t===404)return new zr(t,n,r);if(t===422)return new Jr(t,n,r);if(t===429)return new Yr(t,n,r);if(t>=500)return new Qr(t,n,r);return new e(t,n,r)}},Gr=class extends N{},Wr=class extends N{},Kr=class extends N{},zr=class extends N{},Jr=class extends N{},Yr=class extends N{retryAfterMs=Qt(this.headers)},Qr=class extends N{},We=class extends w{constructor(e="Connection error.",t){super(e,t)}},Xt=class extends We{timeoutMs;constructor(e,t){super(`Request timed out after ${e}ms.`,t);this.timeoutMs=e}},le=class extends w{constructor(e="Request was aborted.",t){super(e,t)}},Xr=[["image/png",[137,80,78,71,13,10,26,10]],["image/jpeg",[255,216,255]]],Zt=/<image:[0-9a-f]{32}>/g,en=Symbol.for("@typesafe-ai/sdk/image"),tn=Symbol.for("@typesafe-ai/sdk/text-with-assets"),nn=()=>Array.from(crypto.getRandomValues(new Uint8Array(16)),(e)=>e.toString(16).padStart(2,"0")).join(""),rn=(e)=>(en in e),sn=(e)=>(tn in e),Zr=(e)=>{if(e===null)return"null";if(typeof e!=="object")return typeof e;return Object.prototype.toString.call(e).slice(8,-1)},ei=(e)=>{if(!ArrayBuffer.isView(e)&&Object.prototype.toString.call(e)!=="[object ArrayBuffer]")throw new w(`Image data must be file bytes or a Blob; got ${Zr(e)}.`);return ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)},ti=(e)=>{for(let[t,n]of Xr)if(n.every((r,i)=>e[i]===r))return t;return"application/octet-stream"},on=class e{type="image";data;#e=`<image:${nn()}>`;constructor(t){if(this.data=t instanceof Blob?t:ei(t),(this.data instanceof Blob?this.data.size:this.data.byteLength)===0)throw new w("Image data is empty.")}static fromBase64(t){let n;try{n=atob(t)}catch(r){throw new w("Image data must contain valid base64 text.",{cause:r})}return new e(Uint8Array.from(n,(r)=>r.charCodeAt(0)))}toString(){return this.#e}toJSON(){return this.#e}};Object.defineProperty(on.prototype,en,{value:!0});var an=class{text;assets;constructor(e,t){this.text=e,this.assets=t}toString(){return this.text}toJSON(){return this.text}};Object.defineProperty(an.prototype,tn,{value:!0});var It=(e,t)=>{let n=new Map;ln(t,n,new Set);let r=new Map;for(let[i]of e.matchAll(Zt)){let s=n.get(i);if(s!==void 0)r.set(i,s)}return new an(e,[...r.values()])},zo=Object.assign((e,...t)=>It(e.reduce((n,r,i)=>n+String(t[i-1])+r),t),{join:(e,t)=>It(e.join(t),e)}),ln=(e,t,n)=>{if(typeof e!=="object"||e===null||n.has(e))return;if(n.add(e),rn(e))t.set(String(e),e);else if(sn(e))for(let r of e.assets)t.set(String(r),r);else for(let r of Object.values(e))ln(r,t,n)},ni=(e,t={})=>{let n=new Map(Object.entries(t).map(([d,l])=>[l,d])),r=new Map(Object.values(t).map((d)=>[String(d),d])),i=JSON.stringify(e,function(d,l){if(typeof l==="number"&&!Number.isFinite(l))return String(l);let c=this[d];if(typeof c!=="object"||c===null)return l;if(rn(c)){let u=n.get(c);if(u!==void 0)return u;r.set(String(c),c)}else if(sn(c)){let u=c.text;for(let m of c.assets){let g=n.get(m);if(g===void 0)r.set(String(m),m);else u=u.replaceAll(String(m),g)}return u}return l}),s=Object.keys(t).filter((d)=>!i.includes(JSON.stringify(d).slice(1,-1)));if(s.length>0)throw new w(`Assets not referenced in the request: ${s.join(", ")}. Write each name in \`assets\` into \`state\`, question instructions, or criteria.`);let o=new Map(Object.entries(t)),a=new Set;for(let[d]of i.matchAll(Zt)){if(o.has(d))continue;let l=r.get(d);if(l===void 0)a.add(d);else o.set(d,l)}if(a.size>0)throw new w(`Image references without an attached image: ${[...a].join(", ")}. Tag template literals that interpolate images with \`withAssets\`.`);return{json:i,assets:o.size===0?void 0:Object.fromEntries(o)}},cn=class{payload;contentType;content;constructor(e,t){let n=nn(),r=[];for(let{name:i,contentType:s,content:o,filename:a}of[{name:"request",contentType:"application/json",content:JSON.stringify(e)},...t]){let d=a===void 0?`name="${i}"`:`name="${i}"; filename="${a}"`;r.push(`--${n}\r
11
+ Content-Disposition: form-data; ${d}\r
12
+ `,`Content-Type: ${s}\r
13
+ \r
14
+ `,o,`\r
15
+ `)}r.push(`--${n}--\r
16
+ `),this.payload=e,this.contentType=`multipart/form-data; boundary=${n}`,this.content=new Blob(r)}},ri=async(e,{data:t})=>{if(!(t instanceof Blob))return t;try{return new Uint8Array(await t.arrayBuffer())}catch(n){throw new w(`Asset "${e}" could not be read: ${n.message}`,{cause:n})}},ii=(e)=>e.buffer instanceof ArrayBuffer?e:e.slice(),si=(e)=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.data instanceof Uint8Array?new on(n.data.slice()):n])),oi=async(e,t)=>{let n=await Promise.all(Object.entries(t).map(async([s,o])=>[s,o,await ri(s,o)])),r=[],i=[];for(let[s,{type:o},a]of n){let d=`asset-${r.length}`;r.push({name:d,contentType:ti(a),content:ii(a),filename:d}),i.push([s,{type:o,part:d}])}return new cn({...e,assets:Object.fromEntries(i)},r)},ai=globalThis,dn=()=>{try{return ai.process?.getBuiltinModule?.("node:zlib")}catch{return}},Ft=()=>typeof dn()?.zstdCompress==="function",li=(e)=>{if(e===void 0)return Ft()?"zstd":!1;if(e===!1)return!1;if(e==="zstd"){if(!Ft())throw new w("zstd compression requires Node.js 22.15 or newer. Pass `compression: false` instead.");return e}throw new w(`\`compression\` must be "zstd" or false, got ${JSON.stringify(e)}.`)},ci=async(e)=>{let t=new Uint8Array(await e.arrayBuffer()),n=await new Promise((r,i)=>{dn()?.zstdCompress?.(t,(s,o)=>s?i(s):r(o))});return new Uint8Array(n)},di=(e)=>typeof e==="string"?new TextEncoder().encode(e).byteLength:e.size,ui=(e)=>ci(typeof e==="string"?new Blob([e]):e),z={apiKey:"TYPESAFE_API_KEY",baseURL:"TYPESAFE_BASE_URL",defaultModel:"TYPESAFE_DEFAULT_MODEL",logLevel:"TYPESAFE_LOG_LEVEL"},un=(e)=>{if(typeof process>"u"||!process.env)return;return process.env[e]?.trim()||void 0},Ue=(e,t)=>e??un(t),pn=["debug","info","warn","error","off"],pi="warn",fi=(e)=>pn.includes(e),Ht=(e,t)=>{if(fi(e))return e;throw new w(`Invalid log level "${e}" from ${t}. Expected one of: ${pn.join(", ")}.`)},fe="[typesafe-sdk]",mi={debug:(e,...t)=>console.debug(`${fe} ${e}`,...t),info:(e,...t)=>console.info(`${fe} ${e}`,...t),warn:(e,...t)=>console.warn(`${fe} ${e}`,...t),error:(e,...t)=>console.error(`${fe} ${e}`,...t)},Dt={debug:0,info:1,warn:2,error:3,off:4},me=()=>{},hi=(e,t)=>{let n=(r)=>Dt[r]>=Dt[t];return{debug:n("debug")?(r,...i)=>e.debug(r,...i):me,info:n("info")?(r,...i)=>e.info(r,...i):me,warn:n("warn")?(r,...i)=>e.warn(r,...i):me,error:n("error")?(r,...i)=>e.error(r,...i):me}},gi=new Set(["authorization","proxy-authorization","x-api-key"]),yi=new Set(["cookie","set-cookie"]),bi=(e)=>{let[t,n]=e.includes(" ")?e.split(/\s+/,2):[void 0,e],r=n&&n.length>8?n.slice(-4):"";return`${t?`${t} `:""}***${r}`},wi=(e,t)=>{let n=e.toLowerCase();if(gi.has(n))return bi(t);if(yi.has(n))return"***";return t},Oi=(e)=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,wi(t,n)])),J=(e=null,t)=>({type:"noul",instructions:e,criteria:t});var fn=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Ci=(e,{criteria:t})=>{if(!fn(t))throw new w(`Choice question "${e}" has criteria that are not a map; choice criteria must be a map of labels to descriptions.`);if(Object.keys(t).length===0)throw new w(`Choice question "${e}" has no criteria; at least one choice is required.`)},_i=(e,{instructions:t,criteria:n})=>{if(n!=null&&!fn(n))throw new w(`Noul question "${e}" criteria must be an object.`);if(t==null&&!Object.values(n??{}).some((r)=>r!=null))throw new w(`Noul question "${e}" has neither instructions nor criteria; at least one is required.`)},Si=(e)=>{if(Object.keys(e).length===0)throw new w("At least one question is required.");for(let[t,n]of Object.entries(e)){if(n.type==="choice")Ci(t,n);if(n.type==="noul")_i(t,n);if(n.type!=="score")continue;if(!Array.isArray(n.criteria))throw new w(`Score question "${t}" has criteria that are not a list; score criteria must be a list of descriptions indexed by score from zero.`);if(n.criteria.length<2)throw new w(`Score question "${t}" has ${n.criteria.length} criteria; at least two scores are required.`)}},vi=class{#e;constructor(e){this.#e=e}list(e={}){return this.#e.request("GET","/v1/models",e).map(Ei)}},Ei=(e)=>{if(Array.isArray(e?.models))return e.models;throw new w("Unexpected response shape from GET /v1/models; expected { models: [...] }.")},C=globalThis,mn=()=>typeof C.window<"u"&&typeof C.window.document<"u"&&typeof C.navigator<"u",$i=()=>{let e=C.process?.platform&&C.process?.arch?` (${C.process.platform}; ${C.process.arch})`:"";if(C.Bun?.version)return`bun/${C.Bun.version}${e}`;if(C.Deno?.version?.deno)return`deno/${C.Deno.version.deno}${e}`;if(C.EdgeRuntime!==void 0)return"vercel-edge";if(C.navigator?.userAgent==="Cloudflare-Workers")return"cloudflare-workers";if(C.process?.versions?.node)return`node/${C.process.versions.node}${e}`;if(mn())return"browser";return"unknown"},Ut="0.7.0",xi=()=>{throw new w(`No API key was provided. Pass \`apiKey\` to the TypeSafeClient constructor or set the ${z.apiKey} environment variable.`)},ki=()=>{throw new w("No global `fetch` is available in this runtime. Pass a `fetch` implementation to the TypeSafeClient constructor.")},Ai=()=>{throw new w("TypeSafeClient is running in a browser, which would expose your API key to anyone using the page. Call the API from a server instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.")},Pi=(e,t)=>globalThis.fetch(e,t),Ti=(e,t)=>{if(!Number.isInteger(t)||t<0)throw new w(`\`${e}\` must be a non-negative integer, got ${String(t)}.`);return t},qt=(e,t)=>{if(!Number.isFinite(t)||t<=0)throw new w(`\`${e}\` must be a positive number of milliseconds, got ${String(t)}.`);return t},qe=(e,t)=>{if(!Number.isFinite(t)||t<0)throw new w(`\`${e}\` must be a non-negative number of milliseconds, got ${String(t)}.`);return t},Bi=(e,t)=>{if(!Number.isFinite(t)||t<0||t>1)throw new w(`\`${e}\` must be between 0 and 1, got ${String(t)}.`);return t},Mi=(e,t)=>{for(let n of t)if(!Number.isInteger(n)||n<100||n>999)throw new w(`\`${e}\` must contain HTTP status codes, got ${String(n)}.`);return t},Gt=(e,t)=>{let n=t??{};return{maxRetries:n.maxRetries===void 0?e.maxRetries:Ti("retry.maxRetries",n.maxRetries),backoffInitialMs:n.backoffInitialMs===void 0?e.backoffInitialMs:qe("retry.backoffInitialMs",n.backoffInitialMs),backoffMaxMs:n.backoffMaxMs===void 0?e.backoffMaxMs:qe("retry.backoffMaxMs",n.backoffMaxMs),backoffJitter:n.backoffJitter===void 0?e.backoffJitter:Bi("retry.backoffJitter",n.backoffJitter),httpStatuses:new Set(n.httpStatuses===void 0?e.httpStatuses:Mi("retry.httpStatuses",n.httpStatuses)),respectRetryAfter:n.respectRetryAfter??e.respectRetryAfter,maxRetryAfterMs:n.maxRetryAfterMs===void 0?e.maxRetryAfterMs:qe("retry.maxRetryAfterMs",n.maxRetryAfterMs),apiConnectionError:n.apiConnectionError??e.apiConnectionError,apiTimeoutError:n.apiTimeoutError??e.apiTimeoutError}},Vi=(e,t)=>{if(e instanceof Xt)return t.apiTimeoutError;if(e instanceof We)return t.apiConnectionError;return!1},Li=(e)=>{if(e!==void 0)return Ht(e,"the `logLevel` option");let t=un(z.logLevel);if(t!==void 0)return Ht(t,z.logLevel);return pi},Ni=(e)=>e.replace(/\/+$/,""),Wt=(...e)=>{let t=new Map;for(let n of e)for(let[r,i]of Object.entries(n))if(i===void 0)t.delete(r.toLowerCase());else t.set(r.toLowerCase(),[r,i]);return Object.fromEntries(t.values())},ji=async(e,t)=>{let n=e.clone().body?.getReader();if(!n)return;let r=e.body?.getReader(),i=()=>{n.cancel(t.reason).catch(()=>{}),r?.cancel(t.reason).catch(()=>{})};t.addEventListener("abort",i,{once:!0});try{if(t.aborted)i();t.throwIfAborted();while(!(await n.read()).done)t.throwIfAborted();t.throwIfAborted()}finally{t.removeEventListener("abort",i),n.releaseLock(),r?.releaseLock()}},Kt=(e,t)=>{if(t===void 0)return e();return new Promise((n,r)=>{if(t.aborted)return r(t.reason);let i=()=>r(t.reason);t.addEventListener("abort",i,{once:!0}),e().then((s)=>{t.removeEventListener("abort",i),n(s)},(s)=>{t.removeEventListener("abort",i),r(s)})})},Ri=$i(),zt=(e)=>{let t=Promise.reject(e);return new Yt(t,()=>t)},hn=class{#e;baseURL;defaultModel;logLevel;logger;retry;timeout;defaultHeaders;compression;fetch;models;#r=0;constructor(e={}){if(mn()&&!e.dangerouslyAllowBrowser)Ai();if(this.#e=Ue(e.apiKey,z.apiKey)??xi(),this.baseURL=Ni(Ue(e.baseURL,z.baseURL)??"https://api.typesafe.ai"),this.defaultModel=Ue(e.defaultModel,z.defaultModel)??"jev-latest",this.logLevel=Li(e.logLevel),this.logger=hi(e.logger??mi,this.logLevel),this.retry=Gt(ge,e.retry),this.timeout=qt("timeout",e.timeout??1e4),this.defaultHeaders={...e.defaultHeaders},this.compression=li(e.compression),e.fetch===void 0&&typeof globalThis.fetch!=="function")ki();this.fetch=e.fetch??Pi;let t={request:(n,r,i)=>this.#t(n,r,i),defaultModel:this.defaultModel};this.models=new vi(t)}systemOne(e,t={}){let n;try{if(e.state==null)throw new w("State is required.");Si(e.questions);let{assets:r,...i}=e,{json:s,assets:o}=ni({...i,model:e.model??this.defaultModel},r),a=JSON.parse(s),d=o===void 0?void 0:si(o);n=d===void 0?a:()=>oi(a,d)}catch(r){return zt(r)}return this.#t("POST","/v1/systemone",{...t,body:n})}#t(e,t,n={}){let r;try{r={method:e,path:t,body:n.body,headers:Wt(this.defaultHeaders,n.headers??{}),signal:n.signal,timeout:n.timeout===void 0?this.timeout:qt("timeout",n.timeout),retry:Gt(this.retry,n.retry)}}catch(s){return zt(s)}let i=`#${++this.#r} ${e} ${t}`;return new Yt(this.fetchWithRetries(i,r),async(s)=>{let o=await Jt(s);return this.logger.debug(`${i} <- body`,o),o})}async fetchWithRetries(e,t){let n=`${this.baseURL}${t.path}`,r=t.body;if(typeof r==="function")try{r=await Kt(r,t.signal)}catch(c){if(!t.signal?.aborted)throw c;throw this.logger.info(`${e} aborted by caller while reading assets`),new le(void 0,{cause:c})}let i=r instanceof cn?r:void 0,s=i===void 0?r:i.payload,o=i?.content??(s===void 0?void 0:JSON.stringify(s)),a=o===void 0||di(o)<1024?!1:this.compression,d=o;if(o!==void 0&&a!==!1)try{d=await Kt(()=>ui(o),t.signal)}catch(c){if(!t.signal?.aborted)throw c;throw this.logger.info(`${e} aborted by caller while compressing the body`),new le(void 0,{cause:c})}let l=Wt(t.headers,{Authorization:`Bearer ${this.#e}`,Accept:"application/json","User-Agent":`typesafe-sdk/${Ut}`,"X-TypeSafe-SDK":`typesafe-sdk/${Ut}`,"X-TypeSafe-Runtime":Ri,"Content-Type":i?.contentType??(d===void 0?void 0:"application/json"),"Content-Encoding":a===!1?void 0:a,"X-TypeSafe-Retry-Count":void 0});for(let c=0;;c++){let u=t.retry.maxRetries-c,m=c===0?l:{...l,"X-TypeSafe-Retry-Count":String(c)};this.logger.debug(`${e} -> ${n}`,{headers:Oi(m),body:s});let g=Date.now(),b;try{b=await this.attempt(e,n,{method:t.method,headers:m,body:d},t)}catch(j){if(j instanceof le||u<=0)throw j;if(!Vi(j,t.retry))throw j;await this.backOff(e,c,u,j.message,void 0,t);continue}let S=Ge(b.headers);if(this.logger.info(`${e} <- ${b.status} in ${Date.now()-g}ms${S?` (request ${S})`:""}`),b.ok)return b;let M=await Jt(b);this.logger.debug(`${e} <- error body`,M);let Ce=N.fromResponse(b.status,M,b.headers);if(u<=0||!Fr(b.status,t.retry))throw Ce;await this.backOff(e,c,u,`${b.status}`,b.headers,t)}}async attempt(e,t,n,{signal:r,timeout:i}){let s=new AbortController,o=()=>s.abort(r?.reason);if(r?.aborted)o();r?.addEventListener("abort",o,{once:!0});let a=!1,d=setTimeout(()=>{a=!0,s.abort()},i),l=Date.now(),c=()=>`${Date.now()-l}ms`;try{let u=await this.fetch(t,{...n,signal:s.signal});return await ji(u,s.signal),u}catch(u){if(r?.aborted)throw this.logger.info(`${e} aborted by caller after ${c()}`),new le(void 0,{cause:u});if(a)throw this.logger.info(`${e} timed out after ${c()}`),new Xt(i,{cause:u});throw this.logger.info(`${e} connection error after ${c()}`,u),new We(u instanceof Error?`Connection error: ${u.message}`:void 0,{cause:u})}finally{clearTimeout(d),r?.removeEventListener("abort",o)}}async backOff(e,t,n,r,i,{retry:s,signal:o}){let a=Hr(t,i,s),d=t+1,l=t+n;this.logger.info(`${e} retrying in ${a}ms (retry ${d}/${l}) after ${r}`);try{await Dr(a,o)}catch(c){throw this.logger.info(`${e} aborted by caller while waiting to retry`),new le(void 0,{cause:c})}}},Jt=async(e)=>{let t=await e.text();if(t.length===0)return;if((e.headers.get("content-type")??"").includes("application/json"))try{return JSON.parse(t)}catch{return t}try{return JSON.parse(t)}catch{return t}};var Ii=0.7,Fi=0.3,Hi={knowledge_base:"A personal knowledge base organized into bundles. Each bundle is a folder of notes on one area. Every question includes one bundle's folder, title, description, and trigger phrases (topics the bundle covers)."},Di={true:"The bundle's description or triggers cover the topic the question asks about.",false:"The bundle's description and triggers are about unrelated topics."};class x{static createJevClient(){return new hn({fetch:Ui})}static noulVerdict(e){if(e>Ii)return"yes";if(e<Fi)return"no";return"unsure"}static async searchBundles({bundleMap:e,question:t}){let n=Array.from(e.values());if(n.length===0)return[];let r=Object.fromEntries(n.map((o)=>[o.folder,J({question:t,bundle:{folder:o.folder,title:o.title,description:o.description,triggers:o.triggers}},Di)])),{answers:i}=await x.createJevClient().systemOne({state:Hi,questions:r}),s=[];for(let[o,a]of Object.entries(i)){let d=e.get(o);if(!d)continue;if(x.noulVerdict(a.noul)==="no")continue;s.push({...d,probability:Number(a.noul.toFixed(3))})}return s.sort((o,a)=>a.probability-o.probability)}}var Ui=async(e,t)=>{let n=await fetch(e,t),r=new Response(await n.arrayBuffer(),{status:n.status,statusText:n.statusText,headers:n.headers});return Object.defineProperty(r,"body",{value:null}),Object.defineProperty(r,"clone",{value:()=>r}),r};class Ke{config={name:"bundle_search",description:"Ask Jev which bundles are likely to contain information about a question",options:[{flag:"--query -q <query>",description:"question to ask about each bundle",required:!0},...k]};async execute(e){let{valid:t,format:n}=h.validateOutputFormat(e.format);if(!t)process.exit(1);let r=await p.getBundleMap(),i=await x.searchBundles({bundleMap:r,question:e.query});console.log(v({question:e.query,bundles:i},{type:n,compact:!e.pretty}))}}var qi={knowledge_base:"A personal knowledge base organized into bundles. Each bundle is a folder of notes (concepts) on one area. Every question includes one concept note's full markdown content (frontmatter and body)."},Gi={true:"The note contains information about the topic the question asks about.",false:"The note is about unrelated topics or only mentions the topic in passing."},Wi=60000,Ki=160000;class ze{config={name:"search",description:"Ask Jev which bundles and concepts are likely to contain information about a question",options:[{flag:"--query -q <query>",description:"question to search the knowledge base for",required:!0},...k]};async execute(e){let{valid:t,format:n}=h.validateOutputFormat(e.format);if(!t)process.exit(1);let[r,i]=await Promise.all([p.getBundleMap(),p.getVaultPath()]),s=await x.searchBundles({bundleMap:r,question:e.query}),a=(await Promise.all(s.map((d)=>this.searchBundle({question:e.query,bundle:d,vaultPath:i})))).filter((d)=>d!==null);console.log(v({question:e.query,bundles:a},{type:n,compact:!e.pretty}))}async searchBundle({question:e,bundle:t,vaultPath:n}){let r=await p.getBundleConcepts({bundle:t.folder,vaultPath:n});if(r.length===0)return null;let i=await Promise.all(r.map(async(l)=>{let c=`${n}/${t.folder}/${l}.md`,u=(await Bun.file(c).text()).slice(0,Wi);return{bundle:t.folder,concept:l,fullpath:c,content:u}})),s=new Map,o=await Promise.all(this.batch(i).map((l)=>this.askJev(e,l)));for(let l of o)for(let[c,u]of l)s.set(c,u);let a=i.filter((l)=>{let c=s.get(l.concept);return c!==void 0&&x.noulVerdict(c)!=="no"});if(a.length===0)return null;let d=await Promise.all(a.map(async(l)=>({...await p.getConceptProperties({bundle:l.bundle,concept:l.concept}),fullpath:l.fullpath,probability:Number((s.get(l.concept)??0).toFixed(3))})));return d.sort((l,c)=>c.probability-l.probability),{...t,concepts:d}}async askJev(e,t){let n=Object.fromEntries(t.map((i)=>[i.concept,J(this.instructions(e,i),Gi)])),{answers:r}=await x.createJevClient().systemOne({state:qi,questions:n});return Object.entries(r).map(([i,s])=>[i,s.noul])}batch(e){let t=[],n=[],r=0;for(let i of e){if(n.length>0&&r+i.content.length>Ki)t.push(n),n=[],r=0;n.push(i),r+=i.content.length}if(n.length>0)t.push(n);return t}instructions(e,t){return{question:e,content:t.content}}}var zi=5000;class Je{config={name:"status",description:"Check whether Jev is reachable and answering ('available' | 'unavailable')"};async execute(){let e=await this.probe();if(console.log(e),e==="unavailable")process.exitCode=1}async probe(){try{let{answers:e}=await x.createJevClient().systemOne({state:"ping",questions:{ping:J("Is `state` the word ping?")}},{timeout:zi,retry:{maxRetries:0}});return typeof e.ping?.noul==="number"?"available":"unavailable"}catch{return"unavailable"}}}class Ye{config={name:"jev",description:"Ask TypeSafe Jev questions about the Knowledge Base",subCommands:[new Ke,new ze,new Je]}}class Qe{config={name:"list",alias:"ls",description:"List all available skills",options:[{flag:"--json",description:"output skills list as json"}]};async execute(e){let{json:t}=e,n=[];for(let[s,o]of R.entries.entries())n.push({name:s,alias:o?.alias??null,description:o.description,path:R.getSkillPath(s)});if(t){let s=v({skills:n},{type:"json",compact:!1});console.log(s);return}let r=[];for(let s of n){let o=[f.colorize(s.name,{fg:"green"}),"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",`alias: ${f.colorize(s?.alias??"null",{fg:"yellow"})}`,`description: ${f.dim(s.description)}`,`path: ${f.colorize({fg:"cyan"}).underline(s.path)}`,""];r.push(...o)}let i=[f.colorize({fg:"magenta"}).bold("LLW SKILLS"),"",...r];console.log(i.join(`
17
+ `))}}class Xe{config={name:"view",description:"Output a bundled skill or its installed folder path",args:[{name:"<name>",description:"registered skill name or alias"}],options:[{flag:"--path",description:"output the absolute skill folder path"}]};execute(e,t){if(!R.has(e))throw Error(`Unknown skill: ${e}`);if(t.path){console.log(R.getSkillPath(e));return}process.stdout.write(R.getSkill(e))}}class Ze{config={name:"skills",description:"Bundled Agent Skill Commands",subCommands:[new Xe,new Qe]}}class et{config={name:"base",description:"View obsidian bundle base"};async execute(){await p.vaultBaseCli(["base:query",`path=${ne}`,"format=json"])}}class tt{config={name:"info",description:"View Vault Full Info"};async execute(){let e=await p.getBundleMap(),t=this.buildHierarchy(e),n=new Map,r=0,i=await p.getVaultPath();for(let d of e.values()){let l=await p.getBundleConcepts({bundle:d.folder,vaultPath:i});r+=l.length,n.set(d.folder,l.length)}let s=[f.colorize("bundles",{fg:f.hex(Se.blue)})],o=t.get(null)??[];o.forEach((d,l)=>{this.renderNode({bundle:d,childrenByParent:t,bundleConceptCountMap:n,lines:s,prefix:"",numberPath:`${l+1}`,isLast:l===o.length-1})});let a=[f.colorize({fg:"magenta"}).bold("LLM WIKI INFO"),`path: ${f.colorize({fg:"cyan"}).underline(i)}`,"",f.colorize({fg:"brightBlue"}).bold("Knowledge Bundles:"),"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",f.bold("Summary:"),` ${f.colorize("\u25CF",{fg:f.hex(Se.blue)})} Total Bundles: ${e.size}`,` ${f.colorize("\u25CF",{fg:"brightYellow"})} Total Concepts: ${r}`,"",...s,"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"];console.log(a.join(`
18
+ `))}buildHierarchy(e){let t=new Map;for(let n of e.values()){let r=n.parentFolder;if(r!==null&&!e.has(r))r=null;let i=t.get(r)??[];i.push(n),t.set(r,i)}for(let n of t.values())n.sort((r,i)=>r.title.localeCompare(i.title));return t}renderNode(e){let{bundle:t,childrenByParent:n,bundleConceptCountMap:r,lines:i,prefix:s,numberPath:o,isLast:a}=e,d=a?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",l=r.get(t.folder)??0,c=f.colorize(`${l}`,{fg:"brightYellow"}),u=l>0?c:f.dim(c);i.push(`${f.dim(s)}${f.dim(d)}${f.colorize(`${o}.`,{fg:"brightCyan"})} ${f.colorize(t.title,{fg:"brightGreen"})} ${u}`);let m=s+(a?" ":"\u2502 "),g=n.get(t.folder)??[];g.forEach((b,S)=>{this.renderNode({bundle:b,childrenByParent:n,bundleConceptCountMap:r,lines:i,prefix:m,numberPath:`${o}.${S+1}`,isLast:S===g.length-1})})}}class nt{config={name:"path",description:"View Full Path To The Vault"};async execute(){let e=await p.getVaultPath();console.log(e)}}class rt{config={name:"vault",description:"View Vault Info",subCommands:[new nt,new et,new tt]}}var{version:Yi}=await Promise.resolve().then(() => An(gn(),1)),yn=Yi;class U extends Error{constructor(e,t,n){super(n);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class Y extends U{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class ye{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Y(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,n);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function be(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}import{EventEmitter as es}from"events";import ot from"child_process";import B from"path";import Oe from"fs";import y from"process";import{stripVTControlCharacters as ts}from"util";import{stripVTControlCharacters as Qi}from"util";class we{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((r)=>!r._hidden),n=e._getHelpCommand();if(n&&!n._hidden)t.push(n);if(this.sortSubcommands)t.sort((r,i)=>r.name().localeCompare(i.name()));return t}compareOptions(e,t){let n=(r)=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter((r)=>!r.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);if(!r&&!i)t.push(n);else if(n.long&&!i)t.push(e.createOption(n.long,n.description));else if(n.short&&!r)t.push(e.createOption(n.short,n.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let r=n.options.filter((i)=>!i.hidden);t.push(...r)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((n)=>be(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(r)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(r)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,r)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(r)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let n="";for(let r=e.parent;r;r=r.parent)n=r.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((n)=>JSON.stringify(n)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let n=`(${t.join(", ")})`;if(e.description)return`${e.description} ${n}`;return n}return e.description}formatItemList(e,t,n){if(t.length===0)return[];return[n.styleTitle(e),...t,""]}groupItems(e,t,n){let r=new Map;return e.forEach((i)=>{let s=n(i);if(!r.has(s))r.set(s,[])}),t.forEach((i)=>{let s=n(i);if(!r.has(s))r.set(s,[]);r.get(s).push(i)}),r}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth??80;function i(c,u){return t.formatItem(c,n,u,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);if(o.length>0)s=s.concat([t.boxWrap(t.styleCommandDescription(o),r),""]);let a=t.visibleArguments(e).map((c)=>i(t.styleArgumentTerm(t.argumentTerm(c)),t.styleArgumentDescription(t.argumentDescription(c))));if(s=s.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(c)=>c.helpGroupHeading??"Options:").forEach((c,u)=>{let m=c.map((g)=>i(t.styleOptionTerm(t.optionTerm(g)),t.styleOptionDescription(t.optionDescription(g))));s=s.concat(this.formatItemList(u,m,t))}),t.showGlobalOptions){let c=t.visibleGlobalOptions(e).map((u)=>i(t.styleOptionTerm(t.optionTerm(u)),t.styleOptionDescription(t.optionDescription(u))));s=s.concat(this.formatItemList("Global Options:",c,t))}return this.groupItems(e.commands,t.visibleCommands(e),(c)=>c.helpGroup()||"Commands:").forEach((c,u)=>{let m=c.map((g)=>i(t.styleSubcommandTerm(t.subcommandTerm(g)),t.styleSubcommandDescription(t.subcommandDescription(g))));s=s.concat(this.formatItemList(u,m,t))}),s.join(`
19
+ `)}displayWidth(e){return Qi(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,r){let s=" ".repeat(2);if(!n)return s+e;let o=e.padEnd(t+e.length-r.displayWidth(e)),a=2,l=(this.helpWidth??80)-t-a-2,c;if(l<this.minWidthToWrap||r.preformatted(n))c=n;else c=r.boxWrap(n,l).replace(/\n/g,`
20
+ `+" ".repeat(t+a));return s+o+" ".repeat(a)+c.replace(/\n/g,`
21
+ ${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),r=/[\s]*[^\s]+/g,i=[];return n.forEach((s)=>{let o=s.match(r);if(o===null){i.push("");return}let a=[o.shift()],d=this.displayWidth(a[0]);o.forEach((l)=>{let c=this.displayWidth(l);if(d+c<=t){a.push(l),d+=c;return}i.push(a.join(""));let u=l.trimStart();a=[u],d=this.displayWidth(u)}),i.push(a.join(""))}),i.join(`
22
+ `)}}class ce{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Xi(e);if(this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;if(typeof e==="string")t={[e]:!0};return this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Y(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,n);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return bn(this.name().replace(/^no-/,""));return bn(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class it{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{if(this.positiveOptions.has(n))this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,i=r!==void 0?r:!1;return t.negate===(i===e)}}function bn(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function Xi(e){let t,n,r=/^-[^-]$/,i=/^--[^-]/,s=e.split(/[ |,]+/).concat("guard");if(r.test(s[0]))t=s.shift();if(i.test(s[0]))n=s.shift();if(!t&&r.test(s[0]))t=s.shift();if(!t&&i.test(s[0]))t=n,n=s.shift();if(s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${e}'`;if(/^-[^-][^-]/.test(o))throw Error(`${a}
23
+ - a short flag is a single dash and a single character
24
+ - either use a single dash and a single character (for a short flag)
25
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(r.test(o))throw Error(`${a}
26
+ - too many short flags`);if(i.test(o))throw Error(`${a}
27
+ - too many long flags`);throw Error(`${a}
28
+ - unrecognised flag format`)}if(t===void 0&&n===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:n}}function Zi(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let r=0;r<=e.length;r++)n[r]=[r];for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let i=1;i<=e.length;i++){let s;if(e[i-1]===t[r-1])s=0;else s=1;if(n[i][r]=Math.min(n[i-1][r]+1,n[i][r-1]+1,n[i-1][r-1]+s),i>1&&r>1&&e[i-1]===t[r-2]&&e[i-2]===t[r-1])n[i][r]=Math.min(n[i][r],n[i-2][r-2]+1)}return n[e.length][t.length]}function st(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");if(n)e=e.slice(2),t=t.map((o)=>o.slice(2));let r=[],i=3,s=0.4;if(t.forEach((o)=>{if(o.length<=1)return;let a=Zi(e,o),d=Math.max(e.length,o.length);if((d-a)/d>s){if(a<i)i=a,r=[o];else if(a===i)r.push(o)}}),r.sort((o,a)=>o.localeCompare(a)),n)r=r.map((o)=>`--${o}`);if(r.length>1)return`
29
+ (Did you mean one of ${r.join(", ")}?)`;if(r.length===1)return`
30
+ (Did you mean ${r[0]}?)`;return""}class Q extends es{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(t)=>y.stdout.write(t),writeErr:(t)=>y.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>y.stdout.isTTY?y.stdout.columns:void 0,getErrHelpWidth:()=>y.stderr.isTTY?y.stderr.columns:void 0,getOutHasColors:()=>On()??(y.stdout.isTTY&&y.stdout.hasColors?.()),getErrHasColors:()=>On()??(y.stderr.isTTY&&y.stderr.hasColors?.()),stripColor:(t)=>ts(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;if(typeof r==="object"&&r!==null)i=r,r=null;i=i||{};let[,s,o]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(s);if(r)a.description(r),a._executableHandler=!0;if(i.isDefault)this._defaultCommandName=a._name;if(a._hidden=!!(i.noHelp||i.hidden),a._executableFile=i.executableFile||null,o)a.arguments(o);if(this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),r)return this;return a}createCommand(e){return new Q(e)}createHelp(){return Object.assign(new we,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...e},this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
31
+ - specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new ye(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);if(typeof n==="function")i.default(r).argParser(n);else i.default(n);return this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==="boolean"){if(this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let n=e??"help [command]",[,r,i]=n.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(r);if(o.helpOption(!1),i)o.arguments(i);if(s)o.description(s);if(this._addImplicitHelpCommand=!0,this._helpCommand=o,e||t)this._initCommandGroup(o);return this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
32
+ Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,n){if(this._exitCallback)this._exitCallback(new U(e,t,n));y.exit(e)}action(e){let t=(n)=>{let r=this.registeredArguments.length,i=n.slice(0,r);if(this._storeOptionsAsProperties)i[r]=this;else i[r]=this.opts();return i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new ce(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let s=`${r} ${i.message}`;this.error(s,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
33
+ - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(r)=>[r.name()].concat(r.aliases()),n=t(e).find((r)=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.defaultValue!==void 0)this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(i,s,o)=>{if(i==null&&e.presetArg!==void 0)i=e.presetArg;let a=this.getOptionValue(n);if(i!==null&&e.parseArg)i=this._callParseArg(e,i,a,s);else if(i!==null&&e.variadic)i=e._collectValue(i,a);if(i==null)if(e.negate)i=!1;else if(e.isBoolean()||e.optional)i=!0;else i="";this.setOptionValueWithSource(n,i,o)};if(this.on("option:"+t,(i)=>{let s=`error: option '${e.flags}' argument '${i}' is invalid.`;r(i,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(i)=>{let s=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;r(i,s,"env")});return this}_optionEx(e,t,n,r,i){if(typeof t==="object"&&t instanceof ce)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,n);if(s.makeOptionMandatory(!!e.mandatory),typeof r==="function")s.default(i).argParser(r);else if(r instanceof RegExp){let o=r;r=(a,d)=>{let l=o.exec(a);return l?l[0]:d},s.default(i).argParser(r)}else s.default(r);return this.addOption(s)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((n)=>{if(n.getOptionValueSource(e)!==void 0)t=n.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(y.versions?.electron)t.from="electron";let r=y.execArgv??[];if(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))t.from="eval"}if(e===void 0)e=y.argv;this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":if(y.defaultApp)this._scriptPath=e[1],n=e.slice(2);else n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){if(this._savedState===null)this.options.filter((e)=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach((e)=>{let t=e.long.replace(/^--no-/,"--");if(!this._findOption(t))this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
34
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(Oe.existsSync(e))return;let r=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",i=`'${e}' does not exist
35
+ - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
36
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
37
+ - ${r}`;throw Error(i)}_executeSubCommand(e,t){t=t.slice();let n=[".js",".ts",".tsx",".mjs",".cjs"];function r(l,c){let u=B.resolve(l,c);if(Oe.existsSync(u))return u;if(n.includes(B.extname(c)))return;let m=n.find((g)=>Oe.existsSync(`${u}${g}`));if(m)return`${u}${m}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,s=this._executableDir||"";if(this._scriptPath){let l;try{l=Oe.realpathSync(this._scriptPath)}catch{l=this._scriptPath}s=B.resolve(B.dirname(l),s)}if(s){let l=r(s,i);if(!l&&!e._executableFile&&this._scriptPath){let c=B.basename(this._scriptPath,B.extname(this._scriptPath));if(c!==this._name)l=r(s,`${c}-${e._name}`)}i=l||i}let o=n.includes(B.extname(i)),a;if(y.platform!=="win32")if(o)t.unshift(i),t=wn(y.execArgv).concat(t),a=ot.spawn(y.argv[0],t,{stdio:"inherit"});else a=ot.spawn(i,t,{stdio:"inherit"});else this._checkForMissingExecutable(i,s,e._name),t.unshift(i),t=wn(y.execArgv).concat(t),a=ot.spawn(y.execPath,t,{stdio:"inherit"});if(!a.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((c)=>{y.on(c,()=>{if(a.killed===!1&&a.exitCode===null)a.kill(c)})});let d=this._exitCallback;a.on("close",(l)=>{if(l=l??1,!d)y.exit(l);else d(new U(l,"commander.executeSubCommandAsync","(close)"))}),a.on("error",(l)=>{if(l.code==="ENOENT")this._checkForMissingExecutable(i,s,e._name);else if(l.code==="EACCES")throw Error(`'${i}' not executable`);if(!d)y.exit(1);else{let c=new U(1,"commander.executeSubCommandAsync","(error)");c.nestedError=l,d(c)}}),this.runningCommand=a}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);if(!r)this.help({error:!0});r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,"preSubcommand"),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(n,r,i)=>{let s=r;if(r!==null&&n.parseArg){let o=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;s=this._callParseArg(n,r,i,o)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;if(n.variadic){if(r<this.args.length){if(i=this.args.slice(r),n.parseArg)i=i.reduce((s,o)=>e(n,o,s),n.defaultValue)}else if(i===void 0)i=[]}else if(r<this.args.length){if(i=this.args[r],n.parseArg)i=e(n,i,n.defaultValue)}t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let n=e,r=[];if(this._getCommandAndAncestors().reverse().filter((i)=>i._lifeCycleHooks[t]!==void 0).forEach((i)=>{i._lifeCycleHooks[t].forEach((s)=>{r.push({hookedCommand:i,callback:s})})}),t==="postAction")r.reverse();return r.forEach((i)=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;if(this._lifeCycleHooks[n]!==void 0)this._lifeCycleHooks[n].forEach((i)=>{r=this._chainOrCall(r,()=>i(this,t))});return r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{if(n.unknown.length>0)this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let s;if(s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent)s=this._chainOrCall(s,()=>{this.parent.emit(i,e,t)});return s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else r(),this._processArguments()}else if(this.commands.length)r(),this.help({error:!0});else r(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((n)=>{let r=n.attributeName();if(this.getOptionValue(r)===void 0)return!1;return this.getOptionValueSource(r)!=="default"});e.filter((n)=>n.conflictsWith.length>0).forEach((n)=>{let r=e.find((i)=>n.conflictsWith.includes(i.attributeName()));if(r)this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(l){return l.length>1&&l[0]==="-"}let s=(l)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(l))return!1;return!this._getCommandAndAncestors().some((c)=>c.options.map((u)=>u.short).some((u)=>/^-\d$/.test(u)))},o=null,a=null,d=0;while(d<e.length||a){let l=a??e[d++];if(a=null,l==="--"){if(r===n)r.push(l);r.push(...e.slice(d));break}if(o&&(!i(l)||s(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let c=this._findOption(l);if(c){if(c.required){let u=e[d++];if(u===void 0)this.optionMissingArgument(c);this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;if(d<e.length&&(!i(e[d])||s(e[d])))u=e[d++];this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);o=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){if(c.required||c.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${c.name()}`,l.slice(2));else this.emit(`option:${c.name()}`),a=`-${l.slice(2)}`;continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(c+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&s(l)))r=n;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(d));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(d));break}else if(this._defaultCommandName){n.push(l,...e.slice(d));break}}if(this._passThroughOptions){r.push(l,...e.slice(d));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
38
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
39
+ `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
40
+ `),this.outputHelp({error:!0});let n=t||{},r=n.exitCode||1,i=n.code||"commander.error";this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in y.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,y.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new it(this.options),t=(n)=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter((n)=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach((n)=>{Object.keys(n.implied).filter((r)=>!t(r)).forEach((r)=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=(s)=>{let o=s.attributeName(),a=this.getOptionValue(o),d=this.options.find((c)=>c.negate&&o===c.attributeName()),l=this.options.find((c)=>!c.negate&&o===c.attributeName());if(d&&(d.presetArg===void 0&&a===!1||d.presetArg!==void 0&&a===d.presetArg))return d;return l||s},r=(s)=>{let o=n(s),a=o.attributeName();if(this.getOptionValueSource(a)==="env")return`environment variable '${o.envVar}'`;return`option '${o.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],i=this;do{let s=i.createHelp().visibleOptions(i).filter((o)=>o.long).map((o)=>o.long);r=r.concat(s),i=i.parent}while(i&&!i._enablePositionalOptions);t=st(e,r)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",r=e.length,i=this.parent?` for '${this.name()}'`:"",s=e.join(", "),o=`error: too many arguments${i}. Expected ${t} argument${n} but got ${r}: ${s}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach((i)=>{if(r.push(i.name()),i.alias())r.push(i.alias())}),t=st(e,r)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
41
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((n)=>be(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=B.basename(e,B.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);if(n.hasColors)return r;return this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,n,r,i;if(t)n=(o)=>this._outputConfiguration.writeErr(o),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth();else n=(o)=>this._outputConfiguration.writeOut(o),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(o)=>{if(!r)o=this._outputConfiguration.stripColor(o);return n(o)},hasColors:r,helpWidth:i}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach((s)=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let i=this.helpInformation({error:n.error});if(t){if(i=t(i),typeof i!=="string"&&!Buffer.isBuffer(i))throw Error("outputHelp callback must return a string or a Buffer")}if(n.write(i),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",r),this._getCommandAndAncestors().forEach((s)=>s.emit("afterAllHelp",r))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(y.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
42
+ Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,(i)=>{let s;if(typeof t==="function")s=t({error:i.error,command:i.command});else s=t;if(s)i.write(`${s}
43
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function wn(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",i="9229",s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null)n=s[1];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(n=s[1],/^\d+$/.test(s[3]))i=s[3];else r=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)n=s[1],r=s[3],i=s[4];if(n&&i!=="0")return`${n}=${r}:${parseInt(i)+1}`;return t})}function On(){if(y.env.NO_COLOR||y.env.FORCE_COLOR==="0"||y.env.FORCE_COLOR==="false")return!1;if(y.env.FORCE_COLOR||y.env.CLICOLOR_FORCE!==void 0)return!0;return}var Al=new Q;var Cn={styleTitle:(e)=>f.bold(e),styleCommandText:(e)=>f.colorize(e,{fg:"green"}),styleCommandDescription:(e)=>f.colorize({fg:"cyan"}).bold(e),styleOptionText:(e)=>f.colorize(e,{fg:"white"}),styleArgumentText:(e)=>f.colorize(e,{fg:"yellow"}),styleSubcommandText:(e)=>f.colorize(e,{fg:"green"})};class _n{loaded=new WeakSet;load(e,t){if(this.loaded.has(e))throw Error(`Command strategy "${e.config.name}" has already been loaded. Use a new instance.`);if(this.loaded.add(e),t.configureHelp(Cn),t.description(e.config.description),e.config.alias)t.alias(e.config.alias);if(e.config.version)t.version(e.config.version);for(let n of e.config.args??[])t.argument(n.name,n.description);for(let n of e.config.options??[])if(n.required)t.requiredOption(n.flag,n.description,n?.default);else t.option(n.flag,n.description,n?.default);if(e.execute)t.action(this.wrapAction(e.execute.bind(e)));for(let n of e.config.subCommands??[])t.register(n)}wrapAction(e){return async(...t)=>{try{await e(...t)}catch(n){let r=n instanceof Error?n.message:String(n);console.error(r||"An unexpected error occurred"),process.exit(1)}}}}var at=new _n;class P extends Q{static assertNoDuplicateEntry(e,t,n){if(e.has(t))throw Error(`Command entry "${t}" is already registered on "${n}".`)}static assertUniqueAlias(e){let t=e.aliases();if(new Set(t).size!==t.length)throw Error(`Command "${e.name()}" has duplicate aliases.`)}static collectEntries(e){let t=[e.config.name];if(e.config.alias)t.push(e.config.alias);return t}use(e){let t=this.name();if(t&&t!==e.config.name)throw Error(`Cannot apply strategy "${e.config.name}" to command "${t}".`);if(!t)this.name(e.config.name);let n=this.commands.flatMap((s)=>[s.name(),...s.aliases()]),r=new Set(n),i=this.name()||"root";for(let s of P.collectEntries(e))P.assertNoDuplicateEntry(r,s,i);return at.load(e,this),this}register(e){let t=this.commands.flatMap((o)=>[o.name(),...o.aliases()]),n=new Set(t),r=this.name()||"root";for(let o of P.collectEntries(e))P.assertNoDuplicateEntry(n,o,r);let i=new P(e.config.name);at.load(e,i),P.assertUniqueAlias(i);let s=[i.name(),...i.aliases()];for(let o of s)P.assertNoDuplicateEntry(n,o,r);return this.addCommand(i)}}var ns={config:{name:"llw",description:"LLM Wiki CLI",version:yn,subCommands:[new je,new De,new Ye,new Ze,new rt]}};async function rs(){let e=new P;e.use(ns),await e.parseAsync(process.argv)}rs().catch((e)=>{let t=e instanceof Error?e.message:String(e);console.error(t),process.exit(1)});
@@ -0,0 +1,5 @@
1
+ {
2
+ "dateFormat": "",
3
+ "timeFormat": "HH:mm",
4
+ "folder": "config/templates"
5
+ }
@@ -0,0 +1,18 @@
1
+ views:
2
+ - type: cards
3
+ name: main
4
+ filters:
5
+ and:
6
+ - file.inFolder("bundles")
7
+ - file.name == "bundle"
8
+ order:
9
+ - title
10
+ - description
11
+ - triggers
12
+ - file.folder
13
+ - parent
14
+ columnSize:
15
+ note.trigger: 372
16
+ rowHeight: medium
17
+ cardSize: 220
18
+ imageAspectRatio: 1
@@ -0,0 +1,6 @@
1
+ ---
2
+ title: ""
3
+ description: ""
4
+ parent: ""
5
+ triggers: [ ]
6
+ ---
@@ -0,0 +1,8 @@
1
+ ---
2
+ type: ""
3
+ title: ""
4
+ tags: []
5
+ description: ""
6
+ resource: ""
7
+ timestamp: "{{date}}T{{time}}"
8
+ ---