@inkeep/open-knowledge 0.5.0-beta.14 → 0.5.0-beta.16

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.
@@ -3,7 +3,7 @@ name: open-knowledge
3
3
  description: "MUST invoke when the project contains a .ok/ directory — before any read or edit of .md / .mdx files, any mcp__open-knowledge__ tool call, and any write_document / edit_document. Skip if no .ok/ — not an Open Knowledge project. Carries preview-attach (open preview browser at session start; one-shot on `action: attach-preview-once`), STOP rules for native Read/Grep/Edit on in-scope markdown, grounding rules (every factual claim needs a source), standard markdown linking with get_dead_links verification, image sourcing + alt-text + source-citation rules, folder-first organization with opt-in nested .ok/ frontmatter + templates, and the anti-pattern table. Authoritative — MCP server instructions and AGENTS.md overlap but do not substitute for the full attach rule, grounding rule, media rules, dead-link verification, and failure-mode guidance carried only here."
4
4
  compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires Open Knowledge MCP server + code execution."
5
5
  metadata:
6
- version: "0.5.0-beta.14"
6
+ version: "0.5.0-beta.16"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
@@ -149,6 +149,8 @@ Before creating or editing docs in a folder, **always** call `list_documents(<fo
149
149
 
150
150
  Pre-write checklist:
151
151
 
152
+ 0. **First-contact check.** If `list_documents(<folder>)` returns empty `frontmatter_defaults` AND empty `templates_available` AND `exec("ls")` shows substantial content elsewhere, the project hasn't been onboarded — STOP and invoke `discover` (see Workflow tools table) before writing. Skip this check on subsequent writes in the same session once you've confirmed the project is configured.
153
+
152
154
  1. **Read `frontmatter_defaults`** — the merged folder defaults (title shape, description, tags) that any new doc here will inherit. Surfaces nested `<folder>/.ok/frontmatter.yml` cascade walked root → leaf, leaf wins per-key. **Don't redeclare** keys the cascade already provides — let inheritance carry them. Override per-file only when the file truly differs.
153
155
  2. **Read `templates_available`** — the menu of starter shapes for `write_document({ template })`. Each entry has `name`, `title`, `description`, and `scope` (`local` / `inherited` / `user`). If an entry matches, prefer it over free-form markdown — see "When to use a template" and "When to create a template" below.
154
156
  3. **Read recent siblings** — `list_documents` enrichment shows recent edits and per-child frontmatter. New docs should match the shape of existing ones (filename pattern, frontmatter keys, body structure). Inconsistency is the enemy.
@@ -172,6 +174,7 @@ Skip the template only when (a) `templates_available` is empty, (b) no entry mat
172
174
 
173
175
  Templates are how a folder's structure becomes durable. Create them proactively, not just when asked:
174
176
 
177
+ - **You're onboarding an existing repo with 2+ siblings in a folder and no template yet.** Don't extract one folder at a time — invoke `discover` (Workflow tools table) for the multi-folder sweep. The bullets below apply during normal session work; `discover` is the bulk path.
175
178
  - **You're about to write a doc in a folder where no template fits, AND the shape you're about to use is reusable.** Save it as a template the same turn (`write_template` with the body you'd have hand-authored), then instantiate via `template:`. The first doc carries the same body either way; the difference is whether the next agent gets a menu entry or re-derives it from a sibling.
176
179
  - **You spot a sibling pattern in a folder that has no template.** Two or more docs sharing the same body skeleton (heading order, required sections, frontmatter shape) is enough — extract the skeleton via `write_template` so subsequent docs pick from `templates_available` instead of copying a sibling.
177
180
  - **You're scaffolding a new folder for a doc category.** Pair the folder rule (`set_folder_rule` for tags/title shape) with a template (`write_template` for body structure) in the same turn. Don't ship a folder-with-discipline-but-no-template — it leaves the next agent to invent the body each time.
@@ -185,6 +188,8 @@ If you find yourself writing the **same** frontmatter (tags, title prefix, descr
185
188
 
186
189
  Repetition is the smell; folder rules and templates are the fix. Don't accumulate ad-hoc per-file frontmatter when one folder rule would carry it.
187
190
 
191
+ **Bulk onboarding.** If most folders already have siblings but no frontmatter, invoke `discover` (Workflow tools table) for the multi-folder sweep instead of per-folder hand-application.
192
+
188
193
  ## Folder structure + metadata — nested `<folder>/.ok/`
189
194
 
190
195
  Folder defaults and templates live in opt-in nested `.ok/` directories — sparse, lazy-create, auto-clean. **Most folders have NO `.ok/`**. A folder gets one only when it declares its own frontmatter defaults or carries templates.
@@ -308,6 +313,7 @@ The skill carries the trigger ("KB content changed this turn — go look"). The
308
313
  | Add an image | empty alt `![](./x.png)` or generic alt `![image](./x)` | meaningful alt + source caption below |
309
314
  | Catalog folder contents | create `INDEX.md` hub file | `set_folder_rule({ rules: [{ match, frontmatter }] })` writes `<folder>/.ok/frontmatter.yml` |
310
315
  | Write a doc in an unfamiliar folder | go straight to `write_document` with hand-authored markdown | `list_documents(<folder>)` first — read `frontmatter_defaults` + `templates_available` before writing |
316
+ | Land in an existing repo without orienting | go straight to `write_document` or run the per-folder pre-write checklist ad-hoc when no folder frontmatter / templates exist | invoke `discover` once for the project — it extracts conventions from siblings, sets folder frontmatter, writes templates, and activates the link graph |
311
317
  | Author a doc when a matching template exists | `write_document({ markdown: "..." })` from scratch | `write_document({ template, position: "replace" })` — templates carry the folder's frontmatter + body discipline |
312
318
  | Repeat the same frontmatter on sibling docs | hand-set identical `tags` / `title` prefix on every new file | `set_folder_rule(...)` once — the cascade carries it to every child |
313
319
  | Re-derive the same body skeleton repeatedly | copy-paste the structure from a sibling each time | `write_template(...)` once, then pick from `templates_available` thereafter |
@@ -318,13 +324,14 @@ The skill carries the trigger ("KB content changed this turn — go look"). The
318
324
 
319
325
  ## Workflow tools — when to invoke them
320
326
 
321
- Three MCP tools build on the primitives above and correspond to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f):
327
+ Four MCP tools build on the primitives above. Three of them correspond to [Karpathy's three-layer knowledge-base pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) (`ingest` / `research` / `consolidate`); the fourth (`discover`) operates at the project-metadata layer and is the brownfield counterpart to the greenfield `ok seed` CLI:
322
328
 
323
329
  | Tool | Layer | When to invoke |
324
330
  | ------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
325
331
  | `ingest` | Raw sources (immutable) | User shares a URL/PDF/file to preserve verbatim, **OR you fetched a URL** (`WebFetch` / `WebSearch` / equivalent) to ground a claim that's about to land in the knowledge base. The KB is closed-loop — agent-initiated fetches are not exempt. No analysis in the file itself — takeaways go back to the user in chat. |
326
332
  | `research` | KB, provisional | User asks you to investigate, compare alternatives, or synthesize multiple sources. Produces a `status: provisional` article with a `sources:` list. Follows scan-first routing, a STOP scoping gate, 3P-external framing, and a validate checklist — the tool body enforces each step. |
327
333
  | `consolidate` | KB, canonical | Team has actually decided after research and wants the outcome committed as source-of-truth. Starts with a STOP gate confirming the decision exists; writes a `status: canonical` article with a `supersedes:` chain. |
334
+ | `discover` | Project metadata | First arrival at a repo with existing content AND no folder frontmatter / templates set. Extracts conventions from siblings; activates the link graph (orphans, hubs, untextualized mentions); proposes folder frontmatter + templates + `.okignore`; per-phase user confirmation. Requires `open-knowledge start` running (Phase 1 step 0 gates). Skip on empty repos (use `ok seed`). One-shot; idempotent on re-run. |
328
335
 
329
336
  Each tool returns a multi-step instructional body when invoked. The bodies enforce their own gates — follow the numbered steps in order, don't skip the STOP gates.
330
337
 
@@ -334,7 +341,7 @@ Typical day-2 flow: user shares a URL → `ingest` (preserve) → user asks "now
334
341
 
335
342
  **Do not chain silently.** After `ingest`, ask the user whether to proceed to `research`. After `research`, let the user decide whether the findings are ready to `consolidate`. Each tool completes on its own terms — the user drives the transitions.
336
343
 
337
- **Project scaffolding is a CLI operation (optional).** Users who want the Karpathy three-layer layout as their folder structure can run `ok seed` once from a terminal. That command scaffolds `external-sources/` + `research/` + `articles/`, seeds an append-only `log.md` at the project root, and registers per-layer folder defaults so agents see layer descriptions at every `list_documents(<folder>)` / `exec("ls <folder>")` call. It is **not required**: the three workflow tools above work against any folder structure the project already uses (`specs/`, `docs/`, `reports/`, or anything else). Only mention `ok seed` if the user explicitly asks for a starter layout or wants the Karpathy pattern specifically.
344
+ **Project scaffolding two paths.** **Empty repo:** run `ok seed` once from a terminal (scaffolds Karpathy three-layer + seeds `log.md` + registers folder defaults). **Existing content:** invoke `discover` (MCP tool, table above extracts conventions from siblings, sets folder frontmatter + templates, curates `.okignore`, activates link graph; per-phase confirmation gates). Neither is required; the four workflow tools work against any folder structure. Only mention each when explicitly relevant.
338
345
 
339
346
  ## Server lifecycle
340
347
 
@@ -345,3 +352,5 @@ If `write_document` or `edit_document` returns a "Hocuspocus server is not runni
345
352
  When MCP is connected, the server's `instructions` echo the **resolved** `content.dir` for this session — that's where Open Knowledge looks for documents. `.gitignore` and `.okignore` (at the project root and at any folder depth) define exclusions. Folder defaults + templates live in nested `<folder>/.ok/frontmatter.yml` + `<folder>/.ok/templates/` files — NOT in `.ok/config.yml`.
346
353
 
347
354
  Default mental model (no jargon): **every `.md` and `.mdx` under `content.dir`** not excluded by `.gitignore` or `.okignore` is an Open Knowledge document — including under `specs/`, `reports/`, `docs/`, etc. Read `.okignore` (and any nested `.okignore` files) once per turn to know what's excluded.
355
+
356
+ **First session in this project?** If `frontmatter_defaults` and `templates_available` are empty for substantial folders, the project hasn't been onboarded yet — invoke `discover` (Workflow tools table) before writing. Once onboarded, the cascade carries the discipline.
@@ -1,3 +1,3 @@
1
1
  import{a as e,i as t,n,t as r}from"./colors-BNufdynn.mjs";const i={single:{topLeft:`┌`,top:`─`,topRight:`┐`,right:`│`,bottomRight:`┘`,bottom:`─`,bottomLeft:`└`,left:`│`},double:{topLeft:`╔`,top:`═`,topRight:`╗`,right:`║`,bottomRight:`╝`,bottom:`═`,bottomLeft:`╚`,left:`║`},round:{topLeft:`╭`,top:`─`,topRight:`╮`,right:`│`,bottomRight:`╯`,bottom:`─`,bottomLeft:`╰`,left:`│`},bold:{topLeft:`┏`,top:`━`,topRight:`┓`,right:`┃`,bottomRight:`┛`,bottom:`━`,bottomLeft:`┗`,left:`┃`},singleDouble:{topLeft:`╓`,top:`─`,topRight:`╖`,right:`║`,bottomRight:`╜`,bottom:`─`,bottomLeft:`╙`,left:`║`},doubleSingle:{topLeft:`╒`,top:`═`,topRight:`╕`,right:`│`,bottomRight:`╛`,bottom:`═`,bottomLeft:`╘`,left:`│`},classic:{topLeft:`+`,top:`-`,topRight:`+`,right:`|`,bottomRight:`+`,bottom:`-`,bottomLeft:`+`,left:`|`},arrow:{topLeft:`↘`,top:`↓`,topRight:`↙`,right:`←`,bottomRight:`↖`,bottom:`↑`,bottomLeft:`↗`,left:`→`}}.round;function a(a){let o=[],s=`${a.name} v${a.version}`;o.push({plain:s,colored:r(s)}),o.push({plain:``,colored:``});let c=a.apiUrl?`Editor: `:`Local: `;if(o.push({plain:`${c}${a.localUrl}`,colored:`${c}${e(t(a.localUrl),a.localUrl)}`}),a.apiUrl){let t=`API: `;o.push({plain:`${t}${a.apiUrl}`,colored:`${t}${n(e(a.apiUrl,a.apiUrl))}`})}if(a.networkUrl){let n=`Network: `;o.push({plain:`${n}${a.networkUrl}`,colored:`${n}${e(t(a.networkUrl),a.networkUrl)}`})}o.push({plain:``,colored:``});let l=`Press Ctrl+C to stop`;o.push({plain:l,colored:n(l)});let u=Math.max(...o.map(e=>e.plain.length)),d=u+4,f=` ${i.topLeft}${i.top.repeat(d)}${i.topRight}`,p=` ${i.bottomLeft}${i.bottom.repeat(d)}${i.bottomRight}`;return[``,f,...o.map(e=>{let t=u-e.plain.length;return` ${i.left}${` `.repeat(2)}${e.colored}${` `.repeat(t+2)}${i.right}`}),p,``].join(`
2
2
  `)}export{a as renderBanner};
3
- //# sourceMappingURL=banner-4PRLiK-I.mjs.map
3
+ //# sourceMappingURL=banner-DdbR6AZr.mjs.map
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{$ as n,Ai as r,Bn as i,Ci as a,D as o,Di as s,E as c,Ei as l,G as u,Gr as d,H as f,Hr as p,Jr as m,Kn as h,Kr as g,Kt as ee,Lr as _,Oi as te,On as v,Si as y,Ti as b,Ur as ne,V as x,Vr as S,Wr as re,Yn as ie,Yr as ae,_i as oe,bi as se,cr as ce,fi as le,it as ue,ji as de,ki as fe,m as pe,ot as me,pn as he,wi as ge,xi as C,yi as _e}from"./dist-BFaejI07.mjs";import{n as ve,r as ye,t as w}from"./dist-bundle-BSdjl7Rj.mjs";import{C as be,E as xe,S as Se,T as Ce,_ as we,b as Te,g as Ee,r as De,u as Oe,v as ke,w as Ae,x as je,y as Me}from"./init-DoDYKuWt.mjs";import{c as Ne,f as Pe,l as Fe,n as Ie,s as T}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{i as Le}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{n as Re}from"./constants-BMZzAuZK.mjs";import{n as ze,t as Be}from"./loader-DwY1uRWB.mjs";import{d as Ve,f as He,l as Ue,m as We,p as Ge,s as Ke}from"./start-Bi19bmNy.mjs";import{c as qe,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-BNufdynn.mjs";import"./src-T_WN5ziD.mjs";import{execFileSync as Je,spawn as Ye,spawnSync as M}from"node:child_process";import Xe,{basename as Ze,dirname as Qe,isAbsolute as $e,join as N,relative as et,resolve as P}from"node:path";import{closeSync as tt,existsSync as F,mkdirSync as nt,mkdtempSync as rt,openSync as it,readFileSync as I,readdirSync as at,rmSync as ot,unlinkSync as st,writeFileSync as ct}from"node:fs";import lt from"node:process";import{homedir as ut,hostname as dt,tmpdir as ft}from"node:os";import{fileURLToPath as pt}from"node:url";import{AsyncLocalStorage as mt,AsyncResource as ht}from"node:async_hooks";import{stripVTControlCharacters as gt,styleText as L}from"node:util";import*as _t from"node:readline";import{randomUUID as vt}from"node:crypto";import{realpath as yt}from"node:fs/promises";import{setTimeout as bt}from"node:timers/promises";import{createInterface as xt}from"node:readline/promises";var St=de();const Ct=`open-knowledge`;var wt=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Ct,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(Ct,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(Ct,e).deletePassword()}catch{}}},Tt=class{backend=`file`;authFile;constructor(e){this.authFile=e??N(ut(),`.ok`,`auth.yml`)}read(){if(!F(this.authFile))return{};try{return(0,St.parse)(I(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=Qe(this.authFile);F(t)||nt(t,{recursive:!0,mode:448}),ct(this.authFile,(0,St.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Et(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Ct,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
2
+ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{$ as n,Ai as r,Bn as i,Ci as a,D as o,Di as s,E as c,Ei as l,G as u,Gr as d,H as f,Hr as p,Jr as m,Kn as h,Kr as g,Kt as ee,Lr as _,Oi as te,On as v,Si as y,Ti as b,Ur as ne,V as x,Vr as S,Wr as re,Yn as ie,Yr as ae,_i as oe,bi as se,cr as ce,fi as le,it as ue,ji as de,ki as fe,m as pe,ot as me,pn as he,wi as ge,xi as C,yi as _e}from"./dist-V31CRf7D.mjs";import{n as ve,r as ye,t as w}from"./dist-bundle-BSdjl7Rj.mjs";import{C as be,E as xe,S as Se,T as Ce,_ as we,b as Te,g as Ee,r as De,u as Oe,v as ke,w as Ae,x as je,y as Me}from"./init-Db-MJvF_.mjs";import{c as Ne,f as Pe,l as Fe,n as Ie,s as T}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{i as Le}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{n as Re}from"./constants-XCszYh-u.mjs";import{n as ze,t as Be}from"./loader-BF1HVIAE.mjs";import{d as Ve,f as He,l as Ue,m as We,p as Ge,s as Ke}from"./start-DivgyWbO.mjs";import{c as qe,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-BNufdynn.mjs";import"./src-DzWkP5Kf.mjs";import{execFileSync as Je,spawn as Ye,spawnSync as M}from"node:child_process";import Xe,{basename as Ze,dirname as Qe,isAbsolute as $e,join as N,relative as et,resolve as P}from"node:path";import{closeSync as tt,existsSync as F,mkdirSync as nt,mkdtempSync as rt,openSync as it,readFileSync as I,readdirSync as at,rmSync as ot,unlinkSync as st,writeFileSync as ct}from"node:fs";import lt from"node:process";import{homedir as ut,hostname as dt,tmpdir as ft}from"node:os";import{fileURLToPath as pt}from"node:url";import{AsyncLocalStorage as mt,AsyncResource as ht}from"node:async_hooks";import{stripVTControlCharacters as gt,styleText as L}from"node:util";import*as _t from"node:readline";import{randomUUID as vt}from"node:crypto";import{realpath as yt}from"node:fs/promises";import{setTimeout as bt}from"node:timers/promises";import{createInterface as xt}from"node:readline/promises";var St=de();const Ct=`open-knowledge`;var wt=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(Ct,e).getPassword();return n==null?null:JSON.parse(n)}catch{return null}}async set(e,t,n,r){let{Entry:i}=await import(`@napi-rs/keyring`),a=new i(Ct,e),o={login:t,token:n,...r};a.setPassword(JSON.stringify(o))}async clear(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{new t(Ct,e).deletePassword()}catch{}}},Tt=class{backend=`file`;authFile;constructor(e){this.authFile=e??N(ut(),`.ok`,`auth.yml`)}read(){if(!F(this.authFile))return{};try{return(0,St.parse)(I(this.authFile,`utf-8`))??{}}catch(e){let t=e instanceof Error?e.message:`unknown error`;return process.stderr.write(`[auth] Failed to parse ${this.authFile}: ${t}. Starting with empty credentials.\n`),{}}}write(e){let t=Qe(this.authFile);F(t)||nt(t,{recursive:!0,mode:448}),ct(this.authFile,(0,St.stringify)(e),{mode:384})}async get(e){return this.read()[e]??null}async set(e,t,n,r){let i=this.read();i[e]={login:t,token:n,...r},this.write(i)}async clear(e){let t=this.read();delete t[e],this.write(t)}};async function Et(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(Ct,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
3
3
  `),new wt}catch{return process.stderr.write(`[auth] token storage: file (~/.ok/auth.yml)
4
4
  `),new Tt(e)}}async function Dt(e,t,n){let r=Ot(await kt(e)).host??``;if(!r)return 1;let i=await n.get(r);if(i==null)return 1;let a=e=>e.replace(/[\r\n]/g,``);return t.write(`username=${a(i.login)}\npassword=${a(i.token)}\n`),0}function Ot(e){let t={};for(let n of e.split(`
5
5
  `)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function kt(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function At(e){let n=new t(`git-credential`);return n.description(`Git credential helper (git credential-helper protocol)`),n.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=await e(),n=await Dt(process.stdin,process.stdout,t);process.exit(n)}),n}function jt(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Mt(e,t,n){let r={baseUrl:jt(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new ve(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function Nt(e){let t=e.request||w,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Mt(t,`POST /login/device/code`,n)}async function Pt(e){let t=await Mt(e.request||w,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=Ft(e,t.data.expires_in),n.refreshTokenExpiresAt=Ft(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Ft(e,t){return new Date(e+t*1e3).toISOString()}async function It(e,t){let n=Lt(e,t.auth);if(n)return n;let{data:r}=await Nt({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await zt(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Lt(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)?n:!1}async function Rt(e){await new Promise(t=>setTimeout(t,e*1e3))}async function zt(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Pt({...i,clientType:`oauth-app`}):await Pt({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Rt(r.interval),zt(e,t,n,r);if(a===`slow_down`)return await Rt(r.interval+7),zt(e,t,n,r);throw i}}async function Bt(e,t){return It(e,{auth:t})}async function Vt(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await It(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Ht=`0.0.0-development`;function Ut(e){let t=e.request||w.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Ht} ${ye()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(Bt.bind(null,i),{hook:Vt.bind(null,i)})}async function Wt(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=Ut({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BmF5_Mcp.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}const Gt={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var Kt;(function(e){})(Kt||={});function qt(e){return fe(_e,e)}function Jt(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const Yt=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function Xt(e){let t=e.toLowerCase().replace(/:\d+$/,``);Yt.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function Zt(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Qt(e,t,n=Wt){let r=Jt(),{host:i,json:a}=e;Xt(i),a||process.stderr.write(`Logging in to ${i}\n`);let o=await n({clientId:r,host:i===`github.com`?void 0:i,onVerification:e=>{e.userCode,e.verificationUri,a?Zt(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),s=`unknown`,c,l;try{let e=i===`github.com`?`https://api.github.com`:`https://${i}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${o.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();s=e.login??s,c=e.name??void 0,l=e.email??void 0}}catch{}await t.set(i,s,o.token,{gitProtocol:`https`,name:c,email:l}),a?Zt(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function $t(e){return new t(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{await Qt(t,await e())})}const en=e=>e.name===`enter`||e.name===`return`;var tn=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},nn=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},rn=class extends Error{name=`ExitPromptError`},an=class extends Error{name=`HookError`},on=class extends Error{name=`ValidationError`};const sn=new mt;function cn(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function ln(e,t){let n=cn(e);return sn.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function R(){let e=sn.getStore();if(!e)throw new an(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function un(){return R().rl}function dn(e){return ht.bind((...t)=>{let n=R(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function fn(e){let t=R(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function pn(){R().handleChange()}const mn={queue(e){let t=R(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(un());if(r!=null&&typeof r!=`function`)throw new on(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=R();dn(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=R();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function hn(e){return typeof e==`function`}function z(e){return fn(t=>{let n=ht.bind(function(e){t.get()!==e&&(t.set(e),pn())});if(t.initialized)return[t.get(),n];let r=hn(e)?e():e;return t.set(r),[r,n]})}function gn(e,t){fn(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&mn.queue(e),n.set(t)})}const _n={prefix:{idle:L(`blue`,`?`),done:L(`green`,xe.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>L(`yellow`,e))},style:{answer:e=>L(`cyan`,e),message:e=>L(`bold`,e),error:e=>L(`red`,`> ${e}`),defaultAnswer:e=>L(`dim`,`(${e})`),help:e=>L(`dim`,e),highlight:e=>L(`cyan`,e),key:e=>L(`cyan`,L(`bold`,`<${e}>`))}};function vn(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function yn(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=vn(n)&&vn(r)?yn(n,r):r}return t}function bn(...e){return yn(_n,...e.filter(e=>e!=null))}function xn({status:e=`idle`,theme:t}){let[n,r]=z(!1),[i,a]=z(0),{prefix:o,spinner:s}=bn(t);return gn(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function Sn(e){return z({current:e})[0]}function Cn(e){let t=Sn(e);t.current=e,gn(e=>{let n=!1,r=dn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var wn=e(Ce(),1);function Tn(e,t){return e.split(`
@@ -17,10 +17,10 @@ import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";impor
17
17
  `),process.exit(1)}await t.set(r,c,a,{gitProtocol:`https`,name:l,email:u}),i?process.stdout.write(`${JSON.stringify({type:`complete`,host:r,login:c})}\n`):process.stderr.write(`✓ PAT stored for ${c} on ${r}\n`)}function Mr(e){return new t(`pat`).description(`Store a Personal Access Token`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await jr(t,await e())})}async function Nr(e,t){let{host:n,json:r}=e;Xt(n);let i=await t.get(n);i??(process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new Ar({auth:i.token,...a?{baseUrl:a}:{}}),s=[];for await(let e of o.paginate.iterator(o.repos.listForAuthenticatedUser,{per_page:100,sort:`updated`}))for(let t of e.data)s.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private});if(r)process.stdout.write(`${JSON.stringify({type:`repos`,host:n,repos:s})}\n`);else for(let e of s)process.stdout.write(`${e.full_name} ${e.clone_url}\n`)}function Pr(e){return new t(`repos`).description(`List accessible repositories`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Nr(t,await e())})}async function Fr(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function Ir(e){return new t(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await Fr(t,await e())})}async function Lr(e,t){let{host:n,json:r}=e;Xt(n);let i=await t.get(n);i??(r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!1})}\n`):process.stderr.write(`Not logged in to ${n}\n`),process.exit(1));let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=new Ar({auth:i.token,...a?{baseUrl:a}:{}});try{let{data:e}=await o.users.getAuthenticated();r?process.stdout.write(`${JSON.stringify({type:`status`,host:n,authenticated:!0,login:e.login,name:e.name,email:e.email})}\n`):process.stderr.write(`✓ Logged in as ${e.login} on ${n}\n`)}catch{r?process.stdout.write(JSON.stringify({type:`status`,host:n,authenticated:!1,error:`token invalid`})+`
18
18
  `):process.stderr.write(`✗ Token invalid for ${n}\n`),process.exit(1)}}function Rr(e){return new t(`status`).description(`Show authentication status`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Lr(t,await e())})}function zr(){let e=new t(`auth`);e.description(`GitHub authentication management`);let n=()=>Et();return e.addCommand($t(n)),e.addCommand(Rr(n)),e.addCommand(Pr(n)),e.addCommand(Ir(n)),e.addCommand(Mr(n)),e.addCommand(At(n)),e}function V(e,t,n={}){let r=Fe(e,t);if(!F(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(I(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!Ne(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??T)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};let o=n.host??dt();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Br(e,t){let n=[];for(let[r,i]of[[`server`,e],[`ui`,t]])(i.status===`dead-pid`||i.status===`corrupt`)&&n.push({name:r,lockPath:i.lockPath,reason:i.status});return{prune:n}}function Vr(e){let t=e.inspect??(t=>V(e.lockDir,t)),n=e.unlink??(e=>st(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Br(t(`server`),t(`ui`));if(a.prune.length===0)return r(`No stale locks.`),{pruned:[],failed:[]};let o=[],s=[];for(let e of a.prune)try{n(e.lockPath),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}if(o.length>0){let e=o.map(e=>`${e.name} (${e.reason})`).join(`, `);r(`Pruned ${o.length} stale lock${o.length===1?``:`s`}: ${e}`)}return s.length>0&&i(`Failed to prune: ${s.map(({target:e,error:t})=>`${e.name} (${e.lockPath}): ${t}`).join(`; `)}`),{pruned:o,failed:s}}function Hr(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),Vr({lockDir:ie(process.cwd())}).failed.length>0&&(process.exitCode=1)})}function Ur(){try{let e=Je(`gh`,[`auth`,`token`],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).trim();return e.length===0?{available:!1}:{available:!0,token:e}}catch{return{available:!1}}}async function Wr(e,t,n={},r=Ur){if(!n.skipGhDetect&&r().available)return{tier:`A`,credentialArgs:[`-c`,`credential.helper=!gh auth git-credential`]};let i=await t.get(e);return i==null?{tier:`none`,credentialArgs:[]}:{tier:i.gitProtocol===`ssh`?`C`:`B`,credentialArgs:[`-c`,`credential.helper=!open-knowledge auth git-credential`]}}function Gr(e){return e.replace(/:\d+$/,``)}function Kr(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:Gr(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:Gr(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:Gr(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}const qr=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function Jr(e){let t=/^([\w ]+):\s+(\d+)%/.exec(e.trim());if(!t)return null;let n=t[1].toLowerCase(),r=Number(t[2]);for(let[e,i,a]of qr)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function H(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Yr(e,t,n,r=process.cwd()){let i=Kr(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?P(r,t.dir):P(r,i.name);if(F(a)&&at(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await Et(),s=await Wr(i.hostname,o,{}),c=Le({baseDir:r,config:s.credentialArgs.length>=2?[s.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`}),l=-1;c.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
19
19
  `)){let n=Jr(e);n&&n.pct!==l&&(l=n.pct,H(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await c.clone(e,a,[`--progress`]),t.json||process.stderr.write(`
20
- `);try{let{runInit:e}=await import(`./init-DeafrQoL.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?H(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Xr(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Xr(e){let t=N(e,`.git`,`info`,`exclude`);if(!F(t))return`no-exclude`;let n=I(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
20
+ `);try{let{runInit:e}=await import(`./init-De5O5Atd.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?H(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{Xr(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?H(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function Xr(e){let t=N(e,`.git`,`info`,`exclude`);if(!F(t))return`no-exclude`;let n=I(t,`utf-8`),r=new Set([`.ok`,`.ok/`,`/.ok`,`/.ok/`]);return n.split(`
21
21
  `).map(e=>e.trim()).some(e=>r.has(e))?`already-present`:(ct(t,`${n}${n.length===0||n.endsWith(`
22
22
  `)?``:`
23
- `}.ok/\n`,`utf-8`),`appended`)}function Zr(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await Yr(t,{json:r.json,dir:n},i);if(r.json)H(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-CxJ_Uuo2.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?H(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const Qr=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function $r(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??ze;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function ei(e){let t=(0,St.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of Qr)t.hasIn(e)&&n.push(e.join(`.`));return n}function ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ni(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=ti(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function ri(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??ae,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:m(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:m(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!F(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ei(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),l=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:ni(Qr.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:le(s.error)}),l=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let u=c.some(e=>e.error!==void 0),d=c.reduce((e,t)=>e+t.found.length,0);if(d===0&&!u)t(`No deprecated fields found.`);else if(d>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:l}}function ii(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{$r({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await ri({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var U=e(qe(),1);const W=2e3,ai=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/];function oi(e){return ai.some(t=>t.test(e))}function si(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return $e(e)?e:null}catch{return null}}function ci(e){let t=[];for(let n of e.split(`
23
+ `}.ok/\n`,`utf-8`),`appended`)}function Zr(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).action(async(t,n,r)=>{let i=e();try{let a=await Yr(t,{json:r.json,dir:n},i);if(r.json)H(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-D6YbKWO-.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?H(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}const Qr=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function $r(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??ze;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function ei(e){let t=(0,St.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of Qr)t.hasIn(e)&&n.push(e.join(`.`));return n}function ti(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ni(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=ti(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function ri(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),o=e.writeConfigPatchFn??ae,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:m(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:m(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!F(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ei(n)}catch(e){let r=e instanceof Error?e.message:String(e);c.push({path:n,scope:t,found:[],removed:[],error:r}),l=!1;continue}if(r.length===0||i){c.push({path:n,scope:t,found:r,removed:[]});continue}let s=await o({cwd:a,scope:t,patch:ni(Qr.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:le(s.error)}),l=!1;continue}c.push({path:n,scope:t,found:r,removed:r})}for(let e of c)e.error&&n(`✗ ${e.path}: ${e.error}`);let u=c.some(e=>e.error!==void 0),d=c.reduce((e,t)=>e+t.found.length,0);if(d===0&&!u)t(`No deprecated fields found.`);else if(d>0)for(let e of c)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:c,ok:l}}function ii(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{$r({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields (sync.*, persistence.{debounceMs,maxDebounceMs}, server.port, content.{include,exclude}) idempotently`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await ri({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var U=e(qe(),1);const W=2e3,ai=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/];function oi(e){return ai.some(t=>t.test(e))}function si(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return $e(e)?e:null}catch{return null}}function ci(e){let t=[];for(let n of e.split(`
24
24
  `)){let e=n.trim();if(!e)continue;let r=e.indexOf(` `);if(r===-1)continue;let i=e.slice(0,r),a=e.slice(r+1),o=Number.parseInt(i,10);!Number.isNaN(o)&&oi(a)&&t.push({pid:o,command:a})}return t}function li(e){let t=[],n=e.split(`
25
25
  `);for(let e=1;e<n.length;e++){let r=n[e]?.trim();if(!r)continue;let i=r.indexOf(` `);if(i===-1)continue;let a=r.slice(0,i),o=r.slice(i+1).trim(),s=Number.parseInt(a,10);!Number.isNaN(s)&&oi(o)&&t.push({pid:s,command:o})}return t}async function ui(){let e=M(`pgrep`,[`-a`,`-f`,`cli\\.mjs|open-knowledge|--ok-lock-dir-b64=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`],{encoding:`utf-8`,timeout:W});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,n=ci(t);if(n.length>0||t.trim()===``)return n}let t=M(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?[]:li(t.stdout)}function di(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=Ze(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function fi(e){let t=M(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function pi(e){let t=M(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],{encoding:`utf-8`,timeout:W});if(t.error!=null||!t.stdout)return null;let[n,r]=t.stdout.trim().split(/\s+/),i=Number.parseFloat(n??``),a=Number.parseFloat(r??``);return Number.isNaN(i)||Number.isNaN(a)?null:{cpuPercent:i,memPercent:a}}async function mi(e){let t=M(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],{encoding:`utf-8`,timeout:W});if(t.error!=null)return null;let n=t.stdout??``;for(let e of n.split(`
26
26
  `))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function hi(e){let t=[],n=e.split(`
@@ -56,7 +56,7 @@ setTimeout(() => process.exit(2), ${t+1e4});
56
56
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function eo(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
57
57
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
58
58
  `&&r++}}return[t,n]}var to=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=$a({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const no={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Y=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},ro=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Bi(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??no}async _authThenStart(){if(!this._authProvider)throw new J(`No auth provider`);let e;try{e=await Aa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new J;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=zi(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new Y(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new to({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=p.parse(JSON.parse(e.data));g(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new J(`No auth provider`);if(await Aa(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new J(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:d(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Y(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=Pa(o);if(this._resourceMetadataUrl=t,this._scope=n,await Aa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new J;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=Pa(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Y(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await Aa(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new J;return this.send(e)}}throw new Y(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),re(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>p.parse(e)):[p.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Y(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Y(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};function io(e){return(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return globalThis.fetch(t,n);let r=new AbortController,i=setTimeout(()=>r.abort(Error(`MCP request timed out after ${e}ms`)),e),a=n?.signal instanceof AbortSignal?AbortSignal.any([n.signal,r.signal]):r.signal;return globalThis.fetch(t,{...n,signal:a}).finally(()=>clearTimeout(i))}}function ao(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function oo(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function so(e,t){return`http://${oo(e)}:${t}/mcp`}function co(e,t){return`ws://${oo(e)}:${t}`}function lo(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function uo(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function fo(e){return F(e)?I(e,`utf-8`).trim():``}function po(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function mo(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function ho(e){if(!e||typeof e!=`object`||!(`result`in e))return;let t=e.result;if(!t||typeof t!=`object`||!(`protocolVersion`in t))return;let n=t.protocolVersion;return typeof n==`string`?n:void 0}function go(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function _o(e){let t=e.readLock??(()=>Pe(e.lockDir)),n=e.isAlive??T,r=e.sleep??(e=>bt(e)),i=e.spawn??Ye,a=e.readErrorLog??fo,o=e.openErrorLog??(e=>it(e,`w`)),s=e.closeFd??tt,c=e.timeoutMs??5e3,l=e.pollIntervalMs??100;if(e.portOverride!==void 0){let t=Number.parseInt(e.portOverride,10);if(Number.isNaN(t)||t<=0)throw Error(`invalid --port value '${e.portOverride}' — HTTP MCP shim requires a positive port`);return so(`localhost`,t)}let u=uo(t(),n);if(u!==void 0)return so(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);F(e.lockDir)||nt(e.lockDir,{recursive:!0});let d=N(e.lockDir,`last-spawn-error.log`),f=o(d),p,m,h=Ve();try{try{p=i(h.command,[...h.prefixArgs,`start`],{detached:!0,stdio:[`ignore`,`ignore`,f],cwd:e.contentDir,env:{...process.env,OK_LOCK_KIND:`mcp-spawned`}}),p.on(`error`,e=>{m=e instanceof Error?e.message:String(e)}),p.unref()}catch(e){m=e instanceof Error?e.message:String(e)}}finally{try{s(f)}catch{}}let g=Date.now()+c;for(;Date.now()<g;){if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}await r(l);let e=uo(t(),n);if(e!==void 0)return so(`localhost`,e)}if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}throw Error(po(c,a(d)))}function vo(e,t){if(e.portOverride!==void 0)return lo(t);let n=e.readLock??(()=>Pe(e.lockDir)),r=e.isAlive??T,i=uo(n(),r);if(i!==void 0)return co(`localhost`,i)}async function yo(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Li(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new ro(new URL(e),{fetch:io(r),...t.connectionId===void 0?{}:{requestInit:{headers:{[c]:t.connectionId}}}}),o=!1,s=async()=>{o||(o=!0,t.onclose?.(),await Promise.allSettled([i.close(),a.close()]))};i.onerror=e=>{n.write(`[mcp-shim] stdio error: ${e.message}\n`)},a.onerror=e=>{n.write(`[mcp-shim] HTTP transport error: ${e.message}\n`)},i.onclose=()=>{s()},a.onclose=()=>{s()};let l=Promise.resolve();i.onmessage=e=>{l=l.then(async()=>{try{await a.send(e)}catch(t){let r=mo(e);if(r===void 0){n.write(`[mcp-shim] failed to forward stdio notification: ${t instanceof Error?t.message:String(t)}\n`);return}await i.send(go(r,t)).catch(e=>{n.write(`[mcp-shim] failed to write stdio error response: ${e instanceof Error?e.message:String(e)}\n`)})}}).catch(e=>{n.write(`[mcp-shim] unexpected stdio forwarding failure: ${e instanceof Error?e.message:String(e)}\n`)})},a.onmessage=e=>{let t=ho(e);t&&a.setProtocolVersion?.(t),i.send(e).catch(e=>{n.write(`[mcp-shim] failed to write stdio response: ${e instanceof Error?e.message:String(e)}\n`)})};try{await a.start(),await i.start()}catch(e){throw await s(),e}return{close:s}}async function bo(e){let t=e.stderr??process.stderr,n=e.bridgeFn??yo,r=await _o(e),i=e.createConnectionId?.()??vt(),a=!1,o=(e.startKeepalive??Ri)({connectionId:i,resolveWsUrl:async()=>vo(e,r),log:e=>t.write(`[mcp-shim] keepalive: ${e}\n`)});t.write(`[mcp-shim] proxying stdio to ${r}\n`);let s;try{s=await n(r,{stderr:t,connectionId:i,onclose:()=>{a||(o.close(),process.exit(0))}})}catch(e){throw o.close(),e}let c=()=>{a=!0,o.close(),s.close().finally(()=>{process.exit(0)})};process.once(`SIGINT`,c),process.once(`SIGTERM`,c)}function xo(e){let t=P(e);for(;;){if(he(t))return t;let n=Qe(t);if(n===t)throw Error(`No Open Knowledge project found at or above ${e}. Pass an explicit \`cwd\` argument that points inside an OK project (a directory with a \`${oe}\`).`);t=n}}function So(e){try{let t=new URL(e);return t.protocol===`file:`?pt(t):void 0}catch{return}}async function Co(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=So(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function wo(e,t){if(e!==void 0)return xo(e);let n=await t();if(n!==void 0)return xo(n);throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.")}async function To(e){let t=process.stderr,n=e.spawnTimeoutMs??ao(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,a=Be({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),s=new S({name:o,version:Ie},{instructions:me({dir:`.`})}),c=vt(),l={current:{connectionId:c,displayName:c,colorSeed:c}},u=new Map,d=e=>{if(u.has(e))return;let n=ee(e),r=l.current,i=Ri({connectionId:c,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>vo({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});u.set(e,i)},f=()=>Co({getClientCapabilities:()=>s.server.getClientCapabilities(),listRoots:()=>s.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),p=e=>wo(e,f),m=async e=>{let t;if(e===void 0){let e=await f();if(e===void 0)return;t=xo(e)}else t=xo(e);let i=await a(t),o=await _o({lockDir:ee(t),contentDir:h(i,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return d(t),o.replace(/\/mcp$/,``)};s.server.oninitialized=()=>{let e=s.server.getClientVersion(),t=ce(e?.name,c);l.current={connectionId:c,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},i(s,{serverUrl:m,resolveCwd:p,config:a,identityRef:l});let g=new Li,_=!1,te=async()=>{if(_)return;_=!0;for(let e of u.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}u.clear();let e=await Promise.allSettled([s.close(),g.close()]);for(let n of e)if(n.status===`rejected`){let e=n.reason;t.write(`[mcp] shutdown close error: ${e instanceof Error?e.message:String(e)}\n`)}};await s.connect(g),t.write(`[mcp] global stdio server ready (per-call project routing)
59
- `);let v=()=>{te().finally(()=>{process.exit(0)})};return process.once(`SIGINT`,v),process.once(`SIGTERM`,v),{close:te}}function Eo(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port`,void 0).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=ao(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await bo({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await To({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Do(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-DCoA7FqK.mjs`),r=e(),i=process.cwd(),a=h(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Oo(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function ko(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Ao(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:di(r),command:r,isDesktop:Oo(r)}}function jo(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Mo(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&jo(e)?`ui-orphan`:`stale`}const No=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Po(e){switch(e){case`running`:return U.default.green(e);case`desktop`:return U.default.blue(e);case`foreign`:return U.default.cyan(e);case`ui-orphan`:return U.default.magenta(e);case`stale`:return U.default.yellow(e)}}function Fo(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Io(e){return`${Fo(e.server.usage)} | ${Fo(e.ui?.usage??null)}`}function Lo(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Ro(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Mo(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Lo(e),Io(e),t,String(n),ko(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=Po(Mo(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=U.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
59
+ `);let v=()=>{te().finally(()=>{process.exit(0)})};return process.once(`SIGINT`,v),process.once(`SIGTERM`,v),{close:te}}function Eo(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port`,void 0).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=ao(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await bo({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await To({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Do(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-N6-E_vFx.mjs`),r=e(),i=process.cwd(),a=h(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Oo(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function ko(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Ao(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:di(r),command:r,isDesktop:Oo(r)}}function jo(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Mo(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&jo(e)?`ui-orphan`:`stale`}const No=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Po(e){switch(e){case`running`:return U.default.green(e);case`desktop`:return U.default.blue(e);case`foreign`:return U.default.cyan(e);case`ui-orphan`:return U.default.magenta(e);case`stale`:return U.default.yellow(e)}}function Fo(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Io(e){return`${Fo(e.server.usage)} | ${Fo(e.ui?.usage??null)}`}function Lo(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Ro(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=Mo(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Lo(e),Io(e),t,String(n),ko(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=Po(Mo(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=U.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
60
60
  `)}async function zo(e={}){let t=e.discover??gi,n=e.inspect??V,r=e.log??(e=>console.log(e)),i=e.resolveCommand??fi,a=e.resolveUsage??pi,o=await t(),s=[];for(let e of o){let t=n(e,`server`),r=n(e,`ui`),o=Ao(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:a(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:a(r.lock.pid));o!=null&&s.push(o)}if(e.json){let e=s.map(e=>({...e,displayStatus:Mo(e)}));r(JSON.stringify(e,null,2));return}r(Ro(e.all?s:s.filter(e=>No.has(Mo(e)))))}function Bo(){return new t(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await zo({all:t.all===!0||e===`all`,json:t.json===!0})})}function X(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Vo(e,t,n=process.cwd()){let r=e.op??`sync`,i=Pe(ie(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}X(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=Le({baseDir:n});if(r===`sync`||r===`pull`){X(e.json,{type:`step`,step:`pull`});let t=await a.pull();X(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(X(e.json,{type:`step`,step:`push`}),await a.push(),X(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
61
61
  `)),X(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Ho(e){return new t(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Vo({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function Uo(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Vo({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function Wo(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Vo({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}function Go(e){return typeof e==`string`&&f.includes(e)}async function Ko(e={}){let t=P(e.cwd??process.cwd()),r=e.pack??`knowledge-base`;if(!x[r])return{status:`failed`,message:`${k(`Error:`)} Unknown pack "${r}". Available: ${f.join(`, `)}`,exitCode:1};let i;try{i=await v({projectDir:t,rootDir:e.root,packId:r})}catch(e){return e instanceof u?{status:`prerequisite-missing`,message:`${k(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${k(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(i.created.length===0){let t=x[r].name;if(e.personalTemplates&&!e.dryRun){let e=_();if(e.errors.length>0){let n=e.errors.map(e=>` ${A(`!`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${O(`Your ${t} pack is already seeded.`)}`,`${A(`Personal templates: some writes failed:`)}`,...n].join(`
62
62
  `),plan:i,exitCode:1}}let n=e.written.length;if(n>0)return{status:`applied`,message:`${O(`Your ${t} pack is already seeded.`)}\n${O(`✓ Wrote ${n} personal template${n===1?``:`s`}`)} ${D(`to ~/.ok/templates/`)}`,plan:i,exitCode:0}}return{status:`no-op`,message:`${O(`Your ${t} pack is already seeded.`)}\n${D(`Nothing to do.`)}`,plan:i,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${j(`Plan (dry-run — no changes made):`)}\n\n${Jo(i,t)}`,plan:i,exitCode:0};if(!e.yes&&!await Yo(`${j(`Plan:`)}\n\n${Jo(i,t)}\n\n${j(`Apply?`)} ${D(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:D(`Cancelled.`),plan:i,exitCode:0};let a=await n(i,{projectDir:t,packId:r});if(a.errors.length>0){let e=a.errors.map(e=>` ${k(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${A(`Applied`)} ${a.applied} entries, ${A(String(a.errors.length))} error(s):`,...e].join(`
@@ -0,0 +1,2 @@
1
+ import"./dist-V31CRf7D.mjs";var e=`0.5.0-beta.16`;const t=`config.yml`,n=e;export{n,t};
2
+ //# sourceMappingURL=constants-XCszYh-u.mjs.map
@@ -1 +1 @@
1
- import{$ as e,$n as t,$t as n,A as r,An as i,Ar as a,At as o,B as s,Bn as c,Br as l,Bt as u,C as d,Cn as f,Cr as p,Ct as m,D as h,Dn as g,Dr as _,Dt as v,E as y,En as b,Er as x,Et as S,F as C,Fn as w,Fr as T,Ft as E,G as D,Gn as O,Gt as k,H as A,Hn as j,Ht as M,I as N,In as P,Ir as F,It as I,J as L,Jn as R,Jt as z,K as B,Kn as V,Kt as H,L as U,Ln as W,Lr as G,Lt as K,M as q,Mn as J,Mr as Y,Mt as X,N as Z,Nn as Q,Nr as $,Nt as ee,O as te,On as ne,Or as re,Ot as ie,P as ae,Pn as oe,Pr as se,Pt as ce,Q as le,Qn as ue,Qt as de,R as fe,Rn as pe,Rr as me,Rt as he,S as ge,Sn as _e,Sr as ve,St as ye,T as be,Tn as xe,Tr as Se,Tt as Ce,U as we,Un as Te,Ut as Ee,V as De,Vn as Oe,Vt as ke,W as Ae,Wn as je,Wt as Me,X as Ne,Xn as Pe,Xr as Fe,Xt as Ie,Y as Le,Yn as Re,Yt as ze,Z as Be,Zn as Ve,Zr as He,Zt as Ue,_ as We,_n as Ge,_r as Ke,_t as qe,a as Je,an as Ye,ar as Xe,at as Ze,b as Qe,bn as $e,br as et,bt as tt,c as nt,ci as rt,cn as it,cr as at,ct as ot,d as st,dn as ct,dr as lt,dt as ut,ei as dt,en as ft,er as pt,et as mt,f as ht,fn as gt,fr as _t,ft as vt,g as yt,gn as bt,gr as xt,gt as St,h as Ct,hn as wt,hr as Tt,ht as Et,i as Dt,in as Ot,ir as kt,it as At,j as jt,jn as Mt,jr as Nt,jt as Pt,k as Ft,kn as It,kr as Lt,kt as Rt,l as zt,li as Bt,ln as Vt,lr as Ht,lt as Ut,m as Wt,mi as Gt,mn as Kt,mr as qt,mt as Jt,n as Yt,nn as Xt,nr as Zt,nt as Qt,o as $t,oi as en,on as tn,or as nn,ot as rn,p as an,pi as on,pn as sn,pr as cn,pt as ln,q as un,qn as dn,qt as fn,r as pn,rn as mn,rr as hn,rt as gn,s as _n,sn as vn,sr as yn,st as bn,t as xn,tn as Sn,tr as Cn,tt as wn,u as Tn,ui as En,un as Dn,ur as On,ut as kn,v as An,vn as jn,vr as Mn,vt as Nn,w as Pn,wn as Fn,wr as In,wt as Ln,x as Rn,xn as zn,xr as Bn,xt as Vn,y as Hn,yn as Un,yr as Wn,yt as Gn,z as Kn,zn as qn,zr as Jn,zt as Yn}from"./dist-BFaejI07.mjs";import{_ as Xn,a as Zn,c as Qn,d as $n,f as er,g as tr,i as nr,l as rr,m as ir,n as ar,o as or,p as sr,r as cr,s as lr,t as ur,u as dr}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";export{xn as AGENT_ID_MAX_LEN,Yt as AGENT_ID_RE,pn as AGENT_WRITE_ORIGIN,Dt as AgentFocusBroadcaster,Je as AgentPresenceBroadcaster,$t as AgentSessionCapacityError,_n as AgentSessionManager,nt as BacklinkIndex,zt as CC1Broadcaster,dt as CC1_CONTRACT_VERSION,Tn as CONFLICT_MARKER_RE,st as CURSOR_BUNDLE_PATHS_BY_PLATFORM,ht as ConfigSchema,an as DEFAULT_CHECKPOINT_RETENTION,Wt as DEFAULT_PACK_ID,Ct as FILE_SYSTEM_WRITER,yt as FILE_WATCHER_ORIGIN,We as GIT_UPSTREAM_WRITER,Fe as GitDirAccessError,An as HOCUSPOCUS_AUTH_REJECTION_REASONS,Hn as HocuspocusAuthRejection,Qe as HocuspocusAuthTokenSchema,Rn as INSTALLED_AGENTS_SCHEMES,ge as LIVE_DERIVED_INDEX_DEBOUNCE_MS,d as LOG_MD_TEMPLATE,Pn as MANAGED_RENAME_ORIGIN,be as MAX_AGENT_SESSIONS,y as MCP_CONNECTION_ID_HEADER,h as MCP_SERVER_NAME,te as MISSING_OK_CONFIG_MESSAGE,He as MalformedGitPointerError,Ft as McpLogger,r as MissingOkConfigError,jt as OBSERVER_SYNC_ORIGIN,en as ORPHAN_MODES,q as PERSONAL_TEMPLATES,Z as PERSONAL_TEMPLATE_NAMES,ae as PinoLogger,ur as ProcessLockCollisionError,C as ProjectGitInitError,N as ROLLBACK_ORIGIN,ar as RUNTIME_VERSION,U as SERVICE_WRITER,fe as SKILL_INSTALL_EVENTS_FILE_REL,rt as SKILL_STATE_TARGETS,Kn as STARTER_FOLDERS,s as STARTER_FOLDER_FRONTMATTER_FILENAME,De as STARTER_PACKS,A as STARTER_PACK_IDS,we as STARTER_TEMPLATES,Ae as STATE_MANIFEST_FILENAME,cr as STATE_SCHEMA_VERSION,Bt as SYSTEM_DOC_NAME,D as SeedPrerequisiteError,B as SeedRootDirError,nr as ServerLockCollisionError,un as StateManifestError,L as TagIndex,Le as UiLockCollisionError,Zn as acquireProcessLock,or as acquireServerLock,Ne as acquireUiLock,Be as applyAgentMarkdownWrite,le as applyExternalChange,e as applySeed,mt as assertCompatibleStateManifest,wn as assertNeverDiskEvent,Qt as attachIdleShutdown,gn as bootServer,At as buildAndOpenSkill,Ze as buildExecResult,rn as buildInstructions,bn as buildReadResult,ot as buildSkillZip,Ut as buildStarterFolderFrontmatterYaml,kn as buildWipTree,ut as classifyEvents,vt as classifyFsPath,ln as clearContributors,Jt as coercePackId,En as colorFromSeed,Et as commitUpstreamImport,St as commitWip,qe as commitWipFromTree,Nn as containsConflictMarkers,Gn as contentHash,tt as contributorCount,Vn as createApiExtension,ye as createAssetServeMiddleware,m as createContentFilter,Ln as createContentFilterAsync,Ce as createExternalChangeHandler,S as createLiveDerivedIndexExtension,v as createMcpHttpHandler,ie as createOsProbe,Rt as createPersistenceExtension,o as createServer,Pt as createServerObserverExtension,X as createStreamingErrorWriter,ee as createTestLogger,ce as detectClaudeDesktopPresence,E as detectProjectShape,I as ensureProjectGit,K as errorResponse,he as evictStaleTrackerEntries,Yn as extractWikiLinksFromMarkdown,u as findEnclosingGitRoot,ke as findEnclosingProjectRoot,M as formatAuthRejectionWire,Ee as formatContributors,Me as gcCheckpointRefs,k as getCurrentMcpLogger,H as getLocalDir,fn as getLogger,z as getMeter,ze as getMetrics,Ie as getTracer,Ue as handleCollabSocketError,de as handleSpawnCursor,on as iconFromClientName,n as incrementCollabSocketFilteredError,ft as incrementServerObserverFire,Sn as initShadowRepo,Xt as initTelemetry,mn as installTestLoggers,Ot as installUserSkill,Ye as isAllowedApiOrigin,tn as isAllowedWorkspaceHostHeader,vn as isConfigDoc,it as isHocuspocusAuthRejectionReason,Vt as isKnownPackId,Dn as isLoopbackAddress,Gt as isOrphanMode,ct as isPairedWriteOrigin,gt as isPathWithinDir,lr as isProcessAlive,sn as isProjectRoot,Kt as isSelfWrite,wt as isSystemDoc,Qn as isValidLockPid,bt as lastKnownHash,Ge as listRescueCheckpoints,jn as listStarterPacks,Un as loadPrincipal,rr as lockFilePath,$e as loggerFactory,zn as mountMcpAndApi,_e as normalizeFsPath,f as parseAuthRejectionWire,Fn as parseHocuspocusAuthToken,xe as parseKeepaliveConnectionId,b as pathToDocName,g as planPersonalTemplates,ne as planSeed,It as readAllTargets,i as readBranchFromHead,dr as readProcessLock,$n as readProcessLockDetailed,er as readServerLock,Mt as readServerPackageVersion,J as readSkillInstallStateSnapshot,Q as readStateManifest,oe as readTargetRecordedAt,w as readTargetVersion,P as readUiLock,W as reconcile,pe as recordContributor,qn as recordSkillInstallEvent,c as registerAllTools,Oe as registerWrite,sr as releaseProcessLock,ir as releaseServerLock,j as releaseUiLock,Te as removeLastKnownHash,je as resetMetrics,O as resolveBundledSkillDir,V as resolveContentDir,dn as resolveCursorBinaryDefault,R as resolveCursorSpawnInvocation,Re as resolveLockDir,Pe as resolvePack,Ve as resolvePackageVersion,ue as rewriteMarkdownLinksForDocumentRename,t as rewriteWikiLinksForDocumentRename,pt as runAuthReposSubprocess,Cn as runAuthStatusSubprocess,Zt as runCloneSubprocess,hn as runDeviceFlowSubprocess,kt as runWithMcpLogger,Xe as safeContentPath,nn as safeSubdir,yn as safetyCheckpoint,at as sanitizeClientName,Ht as saveInMemoryCheckpoint,On as saveVersion,lt as seedBasenameIndex,_t as setActiveSpanAttributes,cn as shadowGit,qt as shutdownTelemetry,Tt as splitMarkdownBlocks,xt as startWatcher,Ke as streamingProblemEvent,Mn as toBroadcasterKey,Wn as tracedAppendFileSync,et as tracedLinkSync,Bn as tracedMkdir,ve as tracedMkdirSync,p as tracedRename,In as tracedRenameSync,Se as tracedRmSync,x as tracedRmdirSync,_ as tracedUnlinkSync,re as tracedWriteFile,Lt as tracedWriteFileSync,a as updateLastKnownHash,tr as updateProcessLockPort,Xn as updateServerLockPort,Nt as updateUiLockPort,Y as validateAgentId,$ as validateCloneInputs,se as validateSkillZip,T as withSpan,F as withSpanSync,G as writePersonalTemplates,me as writeStateManifest,Jn as writeTargetVersion,l as writeTracker};
1
+ import{$ as e,$n as t,$t as n,A as r,An as i,Ar as a,At as o,B as s,Bn as c,Br as l,Bt as u,C as d,Cn as f,Cr as p,Ct as m,D as h,Dn as g,Dr as _,Dt as v,E as y,En as b,Er as x,Et as S,F as C,Fn as w,Fr as T,Ft as E,G as D,Gn as O,Gt as k,H as A,Hn as j,Ht as M,I as N,In as P,Ir as F,It as I,J as L,Jn as R,Jt as z,K as B,Kn as V,Kt as H,L as U,Ln as W,Lr as G,Lt as K,M as q,Mn as J,Mr as Y,Mt as X,N as Z,Nn as Q,Nr as $,Nt as ee,O as te,On as ne,Or as re,Ot as ie,P as ae,Pn as oe,Pr as se,Pt as ce,Q as le,Qn as ue,Qt as de,R as fe,Rn as pe,Rr as me,Rt as he,S as ge,Sn as _e,Sr as ve,St as ye,T as be,Tn as xe,Tr as Se,Tt as Ce,U as we,Un as Te,Ut as Ee,V as De,Vn as Oe,Vt as ke,W as Ae,Wn as je,Wt as Me,X as Ne,Xn as Pe,Xr as Fe,Xt as Ie,Y as Le,Yn as Re,Yt as ze,Z as Be,Zn as Ve,Zr as He,Zt as Ue,_ as We,_n as Ge,_r as Ke,_t as qe,a as Je,an as Ye,ar as Xe,at as Ze,b as Qe,bn as $e,br as et,bt as tt,c as nt,ci as rt,cn as it,cr as at,ct as ot,d as st,dn as ct,dr as lt,dt as ut,ei as dt,en as ft,er as pt,et as mt,f as ht,fn as gt,fr as _t,ft as vt,g as yt,gn as bt,gr as xt,gt as St,h as Ct,hn as wt,hr as Tt,ht as Et,i as Dt,in as Ot,ir as kt,it as At,j as jt,jn as Mt,jr as Nt,jt as Pt,k as Ft,kn as It,kr as Lt,kt as Rt,l as zt,li as Bt,ln as Vt,lr as Ht,lt as Ut,m as Wt,mi as Gt,mn as Kt,mr as qt,mt as Jt,n as Yt,nn as Xt,nr as Zt,nt as Qt,o as $t,oi as en,on as tn,or as nn,ot as rn,p as an,pi as on,pn as sn,pr as cn,pt as ln,q as un,qn as dn,qt as fn,r as pn,rn as mn,rr as hn,rt as gn,s as _n,sn as vn,sr as yn,st as bn,t as xn,tn as Sn,tr as Cn,tt as wn,u as Tn,ui as En,un as Dn,ur as On,ut as kn,v as An,vn as jn,vr as Mn,vt as Nn,w as Pn,wn as Fn,wr as In,wt as Ln,x as Rn,xn as zn,xr as Bn,xt as Vn,y as Hn,yn as Un,yr as Wn,yt as Gn,z as Kn,zn as qn,zr as Jn,zt as Yn}from"./dist-V31CRf7D.mjs";import{_ as Xn,a as Zn,c as Qn,d as $n,f as er,g as tr,i as nr,l as rr,m as ir,n as ar,o as or,p as sr,r as cr,s as lr,t as ur,u as dr}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";export{xn as AGENT_ID_MAX_LEN,Yt as AGENT_ID_RE,pn as AGENT_WRITE_ORIGIN,Dt as AgentFocusBroadcaster,Je as AgentPresenceBroadcaster,$t as AgentSessionCapacityError,_n as AgentSessionManager,nt as BacklinkIndex,zt as CC1Broadcaster,dt as CC1_CONTRACT_VERSION,Tn as CONFLICT_MARKER_RE,st as CURSOR_BUNDLE_PATHS_BY_PLATFORM,ht as ConfigSchema,an as DEFAULT_CHECKPOINT_RETENTION,Wt as DEFAULT_PACK_ID,Ct as FILE_SYSTEM_WRITER,yt as FILE_WATCHER_ORIGIN,We as GIT_UPSTREAM_WRITER,Fe as GitDirAccessError,An as HOCUSPOCUS_AUTH_REJECTION_REASONS,Hn as HocuspocusAuthRejection,Qe as HocuspocusAuthTokenSchema,Rn as INSTALLED_AGENTS_SCHEMES,ge as LIVE_DERIVED_INDEX_DEBOUNCE_MS,d as LOG_MD_TEMPLATE,Pn as MANAGED_RENAME_ORIGIN,be as MAX_AGENT_SESSIONS,y as MCP_CONNECTION_ID_HEADER,h as MCP_SERVER_NAME,te as MISSING_OK_CONFIG_MESSAGE,He as MalformedGitPointerError,Ft as McpLogger,r as MissingOkConfigError,jt as OBSERVER_SYNC_ORIGIN,en as ORPHAN_MODES,q as PERSONAL_TEMPLATES,Z as PERSONAL_TEMPLATE_NAMES,ae as PinoLogger,ur as ProcessLockCollisionError,C as ProjectGitInitError,N as ROLLBACK_ORIGIN,ar as RUNTIME_VERSION,U as SERVICE_WRITER,fe as SKILL_INSTALL_EVENTS_FILE_REL,rt as SKILL_STATE_TARGETS,Kn as STARTER_FOLDERS,s as STARTER_FOLDER_FRONTMATTER_FILENAME,De as STARTER_PACKS,A as STARTER_PACK_IDS,we as STARTER_TEMPLATES,Ae as STATE_MANIFEST_FILENAME,cr as STATE_SCHEMA_VERSION,Bt as SYSTEM_DOC_NAME,D as SeedPrerequisiteError,B as SeedRootDirError,nr as ServerLockCollisionError,un as StateManifestError,L as TagIndex,Le as UiLockCollisionError,Zn as acquireProcessLock,or as acquireServerLock,Ne as acquireUiLock,Be as applyAgentMarkdownWrite,le as applyExternalChange,e as applySeed,mt as assertCompatibleStateManifest,wn as assertNeverDiskEvent,Qt as attachIdleShutdown,gn as bootServer,At as buildAndOpenSkill,Ze as buildExecResult,rn as buildInstructions,bn as buildReadResult,ot as buildSkillZip,Ut as buildStarterFolderFrontmatterYaml,kn as buildWipTree,ut as classifyEvents,vt as classifyFsPath,ln as clearContributors,Jt as coercePackId,En as colorFromSeed,Et as commitUpstreamImport,St as commitWip,qe as commitWipFromTree,Nn as containsConflictMarkers,Gn as contentHash,tt as contributorCount,Vn as createApiExtension,ye as createAssetServeMiddleware,m as createContentFilter,Ln as createContentFilterAsync,Ce as createExternalChangeHandler,S as createLiveDerivedIndexExtension,v as createMcpHttpHandler,ie as createOsProbe,Rt as createPersistenceExtension,o as createServer,Pt as createServerObserverExtension,X as createStreamingErrorWriter,ee as createTestLogger,ce as detectClaudeDesktopPresence,E as detectProjectShape,I as ensureProjectGit,K as errorResponse,he as evictStaleTrackerEntries,Yn as extractWikiLinksFromMarkdown,u as findEnclosingGitRoot,ke as findEnclosingProjectRoot,M as formatAuthRejectionWire,Ee as formatContributors,Me as gcCheckpointRefs,k as getCurrentMcpLogger,H as getLocalDir,fn as getLogger,z as getMeter,ze as getMetrics,Ie as getTracer,Ue as handleCollabSocketError,de as handleSpawnCursor,on as iconFromClientName,n as incrementCollabSocketFilteredError,ft as incrementServerObserverFire,Sn as initShadowRepo,Xt as initTelemetry,mn as installTestLoggers,Ot as installUserSkill,Ye as isAllowedApiOrigin,tn as isAllowedWorkspaceHostHeader,vn as isConfigDoc,it as isHocuspocusAuthRejectionReason,Vt as isKnownPackId,Dn as isLoopbackAddress,Gt as isOrphanMode,ct as isPairedWriteOrigin,gt as isPathWithinDir,lr as isProcessAlive,sn as isProjectRoot,Kt as isSelfWrite,wt as isSystemDoc,Qn as isValidLockPid,bt as lastKnownHash,Ge as listRescueCheckpoints,jn as listStarterPacks,Un as loadPrincipal,rr as lockFilePath,$e as loggerFactory,zn as mountMcpAndApi,_e as normalizeFsPath,f as parseAuthRejectionWire,Fn as parseHocuspocusAuthToken,xe as parseKeepaliveConnectionId,b as pathToDocName,g as planPersonalTemplates,ne as planSeed,It as readAllTargets,i as readBranchFromHead,dr as readProcessLock,$n as readProcessLockDetailed,er as readServerLock,Mt as readServerPackageVersion,J as readSkillInstallStateSnapshot,Q as readStateManifest,oe as readTargetRecordedAt,w as readTargetVersion,P as readUiLock,W as reconcile,pe as recordContributor,qn as recordSkillInstallEvent,c as registerAllTools,Oe as registerWrite,sr as releaseProcessLock,ir as releaseServerLock,j as releaseUiLock,Te as removeLastKnownHash,je as resetMetrics,O as resolveBundledSkillDir,V as resolveContentDir,dn as resolveCursorBinaryDefault,R as resolveCursorSpawnInvocation,Re as resolveLockDir,Pe as resolvePack,Ve as resolvePackageVersion,ue as rewriteMarkdownLinksForDocumentRename,t as rewriteWikiLinksForDocumentRename,pt as runAuthReposSubprocess,Cn as runAuthStatusSubprocess,Zt as runCloneSubprocess,hn as runDeviceFlowSubprocess,kt as runWithMcpLogger,Xe as safeContentPath,nn as safeSubdir,yn as safetyCheckpoint,at as sanitizeClientName,Ht as saveInMemoryCheckpoint,On as saveVersion,lt as seedBasenameIndex,_t as setActiveSpanAttributes,cn as shadowGit,qt as shutdownTelemetry,Tt as splitMarkdownBlocks,xt as startWatcher,Ke as streamingProblemEvent,Mn as toBroadcasterKey,Wn as tracedAppendFileSync,et as tracedLinkSync,Bn as tracedMkdir,ve as tracedMkdirSync,p as tracedRename,In as tracedRenameSync,Se as tracedRmSync,x as tracedRmdirSync,_ as tracedUnlinkSync,re as tracedWriteFile,Lt as tracedWriteFileSync,a as updateLastKnownHash,tr as updateProcessLockPort,Xn as updateServerLockPort,Nt as updateUiLockPort,Y as validateAgentId,$ as validateCloneInputs,se as validateSkillZip,T as withSpan,F as withSpanSync,G as writePersonalTemplates,me as writeStateManifest,Jn as writeTargetVersion,l as writeTracker};