@inkeep/open-knowledge 0.5.0-beta.40 → 0.5.0-beta.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/skills/open-knowledge/SKILL.md +43 -20
- package/dist/cli.mjs +4 -4
- package/dist/constants-VyouMKpv.mjs +2 -0
- package/dist/{dist-kgy3NArq.mjs → dist-Ck9KORwV.mjs} +1 -1
- package/dist/{dist-DjC84IgZ.mjs → dist-DhjzONr6.mjs} +35 -35
- package/dist/index.mjs +1 -1
- package/dist/{init-BH7ZH8Ug.mjs → init-0gV1KRRq.mjs} +4 -4
- package/dist/init-BFgpuKyQ.mjs +1 -0
- package/dist/loader-CnNSGf9d.mjs +1 -0
- package/dist/{loader-C2EgX1O-.mjs → loader-DDue_G5c.mjs} +2 -2
- package/dist/preview-DYWPTqvW.mjs +1 -0
- package/dist/{preview-Ctrbhc4r.mjs → preview-Xx-SUqAa.mjs} +2 -2
- package/dist/public/assets/SettingsDialogBody-ClSRatcR.js +11 -0
- package/dist/public/assets/config-validation-events-B6dxLseJ.js +10 -0
- package/dist/public/assets/index-BXbMiiLK.js +1918 -0
- package/dist/public/index.html +3 -3
- package/dist/{repair-launch-json-DKsMVH1M.mjs → repair-launch-json-Cj4bOBoE.mjs} +2 -2
- package/dist/{repair-mcp-configs-BQ5B5SEm.mjs → repair-mcp-configs-6gVTe06c.mjs} +2 -2
- package/dist/{src-p510n6xV.mjs → src-Bg6KNbde.mjs} +2 -2
- package/dist/start-D2xK_xJa.mjs +1 -0
- package/dist/{start--BCdrceO.mjs → start-Dzlec0zx.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-CQfcgXd1.mjs +0 -2
- package/dist/init-CBnvLBjl.mjs +0 -1
- package/dist/loader-B87qQn2P.mjs +0 -1
- package/dist/preview-CF4spOTa.mjs +0 -1
- package/dist/public/assets/SettingsDialogBody-DsD6fHwY.js +0 -11
- package/dist/public/assets/config-validation-events-C8srGpAi.js +0 -10
- package/dist/public/assets/index-BQdYAvoY.js +0 -1918
- package/dist/start-CbVIel-D.mjs +0 -1
|
@@ -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`; surface to user on `action: start-ui` when no UI is running), 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."
|
|
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.
|
|
6
|
+
version: "0.5.0-beta.41"
|
|
7
7
|
author: "Inkeep"
|
|
8
8
|
repository: "https://github.com/inkeep/open-knowledge"
|
|
9
9
|
---
|
|
@@ -18,12 +18,27 @@ Open Knowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. T
|
|
|
18
18
|
## TL;DR — the 90% case
|
|
19
19
|
|
|
20
20
|
1. **Reads:** `exec("cat …")` for a single doc, `exec("ls -A …")` for a directory, `search` for ranked, `grep` for literal. Native `Read` / `Grep` only on source code (`.ts` / `.py` / …), never on in-scope `.md` / `.mdx`.
|
|
21
|
-
2. **Writes:** `write_document` for new or full-replace, `edit_document` for body-only patches.
|
|
22
|
-
3. **Preview:**
|
|
21
|
+
2. **Writes:** `write_document` for new or full-replace, `edit_document` for body-only patches, `frontmatter_patch` for 1-2 frontmatter keys (preferred). Full frontmatter rewrites use `write_document({ position: "replace" })`. `edit_document` rejects frontmatter (HTTP 400).
|
|
22
|
+
3. **Preview:** every OK tool response carries the preview URL (`ui.baseUrl` on reads, `previewUrl` on writes). Navigate your in-app browser to it from the first response you see; refresh from later responses if Electron/UI restarted. Surface to the user on a `start-ui` warning (no UI running). Don't `preview_screenshot` after every edit.
|
|
23
23
|
4. **Workflow tools** (`ingest` / `research` / `consolidate` / `discover`) return procedural guides, not data. Use them when the work fits the layer; follow their numbered steps.
|
|
24
24
|
|
|
25
25
|
Everything below is depth. Read on demand.
|
|
26
26
|
|
|
27
|
+
## Tool index — by family
|
|
28
|
+
|
|
29
|
+
The full MCP surface, grouped by intent. Each family has one canonical instruction site later in this doc (linked). Reach for the family before the individual tool.
|
|
30
|
+
|
|
31
|
+
- **Read** — `exec` (primary; shell-style), `read_document` (typed; one doc), `search` (ranked, BM25 + recency), `grep` (literal, frontmatter-enriched), `list_documents` (folder + `frontmatter_defaults` + `templates_available` cascade). See *Reads — examples*.
|
|
32
|
+
- **Write / edit** — `write_document` (new or full-replace, incl. `template:` instantiation), `edit_document` (body-only find/replace), `frontmatter_patch` (JSON Merge Patch for 1-2 keys), `delete_document`. See *Writing* and *Frontmatter conventions*.
|
|
33
|
+
- **Restructure** — `rename_document` (single file; updates referrers), `rename_folder` (folder + descendants; updates referrers). Always prefer these over `delete_document` + re-write — they preserve history and rewrite incoming links.
|
|
34
|
+
- **Versioning** — `save_version` (named snapshot), `get_history` (versions for a doc), `rollback_to_version` (restore a snapshot). Call `save_version` before any 1-way operation (delete, large rewrite, folder rename) you may need to undo.
|
|
35
|
+
- **Link graph** — `get_dead_links` (verify after writes; strict-exact), `get_backlinks` (incoming), `get_forward_links` (outgoing), `get_orphans` (no incoming), `get_hubs` (high-incoming), `suggest_links` (untextualized mentions). See *Linking*.
|
|
36
|
+
- **Components** — `get_components` (fetch param schemas + literal `example` bytes). See *Components — prefer canonicals*.
|
|
37
|
+
- **Folder defaults + templates** — `set_folder_rule` (writes `<folder>/.ok/frontmatter.yml`), `write_template` / `delete_template` (writes `<folder>/.ok/templates/`), `get_config` (read resolved config). See *Folder structure + metadata*.
|
|
38
|
+
- **Workflow tools (return procedural guides, not data)** — `ingest`, `research`, `consolidate`, `discover`. See *Workflow tools — when to invoke them*.
|
|
39
|
+
|
|
40
|
+
Tools NOT in OK MCP (they belong to your agent host): `preview_start`, `preview_screenshot`, `WebFetch`, `WebSearch`, native `Read` / `Grep` / `Glob` / `Edit`. The STOP rule below governs which of those you may use on in-scope markdown.
|
|
41
|
+
|
|
27
42
|
## STOP — native tools on in-scope `.md` / `.mdx`
|
|
28
43
|
|
|
29
44
|
When this workspace has Open Knowledge MCP configured, do **not** use your host's native file tools on markdown paths inside the content directory. The ban covers every common rationalization:
|
|
@@ -51,32 +66,40 @@ Why: native tools skip frontmatter, backlinks, shadow-repo activity, and project
|
|
|
51
66
|
|
|
52
67
|
## Preview — open the browser at session start
|
|
53
68
|
|
|
54
|
-
**
|
|
69
|
+
**The invariant.** If OK Electron is open for this project OR `ok ui` is running for it, every OK tool response carries the preview URL — plain HTTP, no custom URL schemes, works in any browser including agent in-app browsers (Claude Desktop, Cursor, Codex, Cowork). Read tools (`exec`, `grep`, `search`, `list_documents`, `read_document`) carry it in `ui.baseUrl` (top-level) and per-doc `previewUrl` fields; write tools carry it in `previewUrl` + the optional `warning` shape. Never construct this URL; always read it from the latest tool response.
|
|
70
|
+
|
|
71
|
+
**The default agent move.** Make your first OK tool call (any read works — `list_documents`, `exec("ls -A")`, or `read_document` is enough). The response carries the preview URL. Navigate to it immediately, then proceed with your real work. The user watches edits land live; you can re-navigate later to verify a CRDT edit landed when a response looks ambiguous. Per host:
|
|
72
|
+
|
|
73
|
+
- **In-app browser hosts** (Claude Desktop, Cursor, Codex, Cowork): navigate the in-app browser to the `previewUrl`. Default.
|
|
74
|
+
- **Claude Code Desktop**: call `preview_start("open-knowledge-ui")` (host tool, not OK MCP).
|
|
75
|
+
- **Stdio-only hosts**: surface the URL in chat; `open <url>` (macOS) if the host can shell out.
|
|
76
|
+
|
|
77
|
+
**Four signals to check if it's already open** (you usually can't pre-check, so read these from each write response):
|
|
78
|
+
|
|
79
|
+
1. You opened/navigated earlier this session → don't reopen.
|
|
80
|
+
2. Write response has `previewUrl` (non-null) and NO `warning` → a browser is attached somewhere; do nothing.
|
|
81
|
+
3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot.
|
|
82
|
+
4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don't loop on retries.
|
|
55
83
|
|
|
56
|
-
|
|
57
|
-
- Cursor: use the host's open-URL tool with a `previewUrl` from any write response.
|
|
58
|
-
- Other hosts: use whatever command opens a URL (macOS: `open <url>`). On hosts with no preview tool (Codex, generic stdio), surface the URL in chat for the user to click.
|
|
84
|
+
Warnings fire at most once per session in the fresh-start case.
|
|
59
85
|
|
|
60
|
-
|
|
86
|
+
**`previewUrl: null` only means "no UI reachable" on the three attach-warning tools: `write_document` / `edit_document` / `frontmatter_patch`.** Workflow tools return prose and don't carry `previewUrl`. `delete_document` / `rename_document` / `rename_folder` emit `previousPreviewUrl` (different field, for closing stale tabs) and don't fire attach warnings.
|
|
61
87
|
|
|
62
|
-
|
|
63
|
-
2. A `write_document` / `edit_document` response returns `previewUrl` but NO `warning` → a browser is attached somewhere; do nothing.
|
|
64
|
-
3. A response DOES include `warning: { action: "attach-preview-once", previewUrl, message }` → a UI server is reachable but no browser is attached; open the URL immediately, one-shot.
|
|
65
|
-
4. A response includes `warning: { action: "start-ui", previewUrl: null, message }` → no UI is running anywhere for this project. Surface the message to the user (the in-band copy names the recovery options: `open-knowledge ui` in a terminal, `preview_start("open-knowledge-ui")` in Claude Code Desktop, or opening the project in OK Electron). Don't loop on retries — the user has to act.
|
|
88
|
+
**Always read `previewUrl` from the latest write response.** Don't cache the session-start value — Electron quit/reopen (or `ok ui` restart) can change the port; the resolver picks up the new port automatically.
|
|
66
89
|
|
|
67
|
-
|
|
90
|
+
If you see `"Hocuspocus server is not running"`, run `ok start` and retry. NEVER construct preview URLs by hand.
|
|
68
91
|
|
|
69
|
-
|
|
92
|
+
OK Electron and `ok ui` cannot serve the same project at once — they share `ui.lock`. A UI-lock collision means the other is running for that project (use that one, or quit it first).
|
|
70
93
|
|
|
71
|
-
|
|
94
|
+
**The preview is read-only for the agent.** Navigate to verify edits landed; you cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).
|
|
72
95
|
|
|
73
|
-
**No screenshots after
|
|
96
|
+
**No screenshots after every edit.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after every write. Trust the response. Screenshot only when (a) debugging a visual issue, (b) a response looks ambiguous, or (c) the user asks.
|
|
74
97
|
|
|
75
98
|
## Writing
|
|
76
99
|
|
|
77
100
|
Call `write_document` / `edit_document` as soon as you have content. Native `Edit` / `sed` / direct `Write` on in-scope markdown is forbidden — it bypasses the CRDT and loses agent attribution in the shadow repo.
|
|
78
101
|
|
|
79
|
-
To delete a doc, call `delete_document` — never `rm` / `unlink` / native `Bash` removal on in-scope markdown. The MCP path closes open agent sessions and unloads the doc from Hocuspocus before unlinking; native `rm` desynchronizes those. Deletion is irreversible from this tool — call `save_version` first if you may need to roll back, and `get_backlinks` first if you want to fix the referrers that will become redlinks.
|
|
102
|
+
To delete a doc, call `delete_document` — never `rm` / `unlink` / native `Bash` removal on in-scope markdown. The MCP path closes open agent sessions and unloads the doc from Hocuspocus before unlinking; native `rm` desynchronizes those. Deletion is irreversible from this tool — call `save_version` first if you may need to roll back (restore via `rollback_to_version`; list snapshots via `get_history`), and `get_backlinks` first if you want to fix the referrers that will become redlinks. To move or rename a doc instead of delete + rewrite, use `rename_document` (single file) or `rename_folder` (folder + descendants) — both rewrite incoming references atomically.
|
|
80
103
|
|
|
81
104
|
**If `edit_document` returns "Text not found" on text you can verify exists on disk** (via `exec("cat …")`), the MCP session is likely stale (e.g., after a folder rename or server restart). Treat this as the escape-hatch trigger from the STOP block: prefix your next user-visible sentence with `Open Knowledge MCP unavailable:` and report the inconsistency. Don't loop on retries — the symptom is structural, not transient.
|
|
82
105
|
|
|
@@ -133,7 +156,7 @@ Knowledge-base docs are factual artifacts — whether the project is a wiki, an
|
|
|
133
156
|
- **Internal cross-refs between OK docs** → `[text](./other-doc.md)` — link liberally to aid navigation.
|
|
134
157
|
- **Never wrap a link in backticks.** `` `[text](./foo.md)` `` is a bug — the backticks make it render as literal code rather than a link.
|
|
135
158
|
- **Never use HTML anchors** (`<a href="...">`). Markdown link syntax only.
|
|
136
|
-
- **Verify before walking away.** After writing a doc, call `get_dead_links({ sourceDocNames: ['your/doc'] })` to find broken references. Fix each redlink or explicitly accept it.
|
|
159
|
+
- **Verify before walking away.** After writing a doc, call `get_dead_links({ sourceDocNames: ['your/doc'] })` to find broken references. Fix each redlink or explicitly accept it. Companion link-graph reads (same family): `get_backlinks` (incoming), `get_forward_links` (outgoing), `get_orphans` (no incoming), `get_hubs` (high-incoming), `suggest_links` (untextualized mentions worth linking).
|
|
137
160
|
- **The editor's red-underline visual lies.** Its dead-link detection tolerates slug-fallback (e.g., `foo` may appear resolved because `foo.md` exists at root). `get_dead_links` is strict-exact — trust the tool, not the visual.
|
|
138
161
|
|
|
139
162
|
**Note on wiki-link syntax (`[[Page]]`):** the parser still handles it for legacy content, but it's NO LONGER the recommended default. Write new content with standard markdown links per above. Seed-pack templates (`ok seed --pack <name>`) may still emit `[[Page]]` placeholders inside template body text — those are legacy. When you instantiate a seed-pack template, replace the legacy placeholders with standard markdown links during the `{shape}`-fill pass.
|
|
@@ -365,7 +388,7 @@ The skill carries the trigger ("KB content changed this turn — go look"). The
|
|
|
365
388
|
| 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 |
|
|
366
389
|
| 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 |
|
|
367
390
|
| 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 |
|
|
368
|
-
| Change a doc's title / tags | `edit_document` to swap the YAML (rejected — HTTP 400 frontmatter-intersect) | `write_document({ position: "replace", markdown })`
|
|
391
|
+
| Change a doc's title / tags | `edit_document` to swap the YAML (rejected — HTTP 400 frontmatter-intersect) | `frontmatter_patch({ docName, patch })` for 1-2 keys; `write_document({ position: "replace", markdown })` for full rewrites |
|
|
369
392
|
| 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 |
|
|
370
393
|
| 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 |
|
|
371
394
|
| Scaffold a new folder for a doc category | `set_folder_rule` for frontmatter and stop there | pair `set_folder_rule` with `write_template` in the same turn — discipline + body shape |
|
|
@@ -384,7 +407,7 @@ Three correspond to [Karpathy's three-layer knowledge-base pattern](https://gist
|
|
|
384
407
|
| `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. |
|
|
385
408
|
| `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. |
|
|
386
409
|
| `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. |
|
|
387
|
-
| `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 `
|
|
410
|
+
| `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 `ok start` running (Phase 1 step 0 gates). Skip on empty repos (use `ok seed`). One-shot; idempotent on re-run. |
|
|
388
411
|
|
|
389
412
|
**These tools are your default move, not `write_document`.** When the work fits one of the three layers — preserving an external source, investigating/synthesizing, committing a decided outcome — invoke the corresponding tool instead of going straight to `write_document` / `edit_document`. The tool bodies enforce framing (sources, status, supersedes chains) that hand-written articles routinely miss. `write_document` is correct for everything that does **not** fit the three layers (specs, runbooks, scratch notes, project pages); for the three that do, lead with the tool. This is doubly true in projects that ran `ok seed` — a doc landing in `external-sources/` / `research/` / `articles/` should have come out of `ingest` / `research` / `consolidate`.
|
|
390
413
|
|
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{Ai as n,B as r,Ci as i,D as a,Di as o,Dn as s,E as c,Ei as l,Gn as u,Gr as d,Gt as f,Hr as p,Jn as m,Kr as h,Mi as g,Oi as _,Si as v,Ti as y,U as ee,Ur as b,Wr as x,Xr as te,Yr as ne,Z as re,bi as ie,cr as ae,it as oe,ji as se,ki as ce,m as le,nn as ue,nt as de,pi as fe,pn as pe,qr as me,vi as he,wi as ge,xi as _e,z as ve,zn as ye}from"./dist-
|
|
2
|
+
import{o as e}from"./chunk-FK9Q3tQk.mjs";import{t}from"./esm-CEs3LWY3.mjs";import{Ai as n,B as r,Ci as i,D as a,Di as o,Dn as s,E as c,Ei as l,Gn as u,Gr as d,Gt as f,Hr as p,Jn as m,Kr as h,Mi as g,Oi as _,Si as v,Ti as y,U as ee,Ur as b,Wr as x,Xr as te,Yr as ne,Z as re,bi as ie,cr as ae,it as oe,ji as se,ki as ce,m as le,nn as ue,nt as de,pi as fe,pn as pe,qr as me,vi as he,wi as ge,xi as _e,z as ve,zn as ye}from"./dist-DhjzONr6.mjs";import{n as be,r as xe,t as S}from"./dist-bundle-BSdjl7Rj.mjs";import{C as Se,D as Ce,E as we,O as Te,S as Ee,T as De,a as Oe,b as ke,f as Ae,k as je,v as Me,w as Ne,x as Pe,y as Fe}from"./init-0gV1KRRq.mjs";import{c as Ie,f as Le,l as Re,n as ze,s as C}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";import{i as Be}from"./git-handle-DwfYp_z--CfyPz4Dz.mjs";import{n as Ve}from"./constants-VyouMKpv.mjs";import{i as He}from"./src-Bg6KNbde.mjs";import{n as Ue,t as We}from"./loader-DDue_G5c.mjs";import{d as Ge,f as Ke,l as qe,m as Je,p as Ye,s as Xe}from"./start-Dzlec0zx.mjs";import{c as Ze,i as Qe,n as w,o as T,r as E,s as D,t as O}from"./colors-BtKMHmBX.mjs";import{execFileSync as $e,execSync as et,spawn as tt,spawnSync as k}from"node:child_process";import nt,{basename as rt,dirname as it,isAbsolute as at,join as A,relative as ot,resolve as j}from"node:path";import{closeSync as st,existsSync as M,mkdirSync as ct,mkdtempSync as lt,openSync as ut,readFileSync as N,readdirSync as dt,realpathSync as ft,rmSync as pt,statSync as mt,unlinkSync as ht,writeFileSync as gt}from"node:fs";import _t from"node:process";import{homedir as vt,hostname as yt,tmpdir as bt}from"node:os";import{fileURLToPath as xt}from"node:url";import{AsyncLocalStorage as St,AsyncResource as Ct}from"node:async_hooks";import{stripVTControlCharacters as wt,styleText as P}from"node:util";import*as Tt from"node:readline";import{randomUUID as Et}from"node:crypto";import{realpath as Dt}from"node:fs/promises";import{setTimeout as Ot}from"node:timers/promises";import{createInterface as kt}from"node:readline/promises";var At=g();const jt=`open-knowledge`;var Mt=class{backend=`keyring`;async get(e){let{Entry:t}=await import(`@napi-rs/keyring`);try{let n=new t(jt,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(jt,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(jt,e).deletePassword()}catch{}}},Nt=class{backend=`file`;authFile;constructor(e){this.authFile=e??A(vt(),`.ok`,`auth.yml`)}read(){if(!M(this.authFile))return{};try{return(0,At.parse)(N(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=it(this.authFile);M(t)||ct(t,{recursive:!0,mode:448}),gt(this.authFile,(0,At.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 Pt(e){try{let{Entry:e}=await import(`@napi-rs/keyring`);return new e(jt,`__probe__`),process.stderr.write(`[auth] token storage: OS keychain
|
|
3
3
|
`),new Mt}catch{return process.stderr.write(`[auth] token storage: file (~/.ok/auth.yml)
|
|
4
4
|
`),new Nt(e)}}async function Ft(e,t,n){let r=It(await Lt(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 It(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 Lt(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 Rt(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 Ft(process.stdin,process.stdout,t);process.exit(n)}),n}function zt(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function Bt(e,t,n){let r={baseUrl:zt(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new be(`${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 Vt(e){let t=e.request||S,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),Bt(t,`POST /login/device/code`,n)}async function Ht(e){let t=await Bt(e.request||S,`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=Ut(e,t.data.expires_in),n.refreshTokenExpiresAt=Ut(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Ut(e,t){return new Date(e+t*1e3).toISOString()}async function Wt(e,t){let n=Gt(e,t.auth);if(n)return n;let{data:r}=await Vt({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await qt(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Gt(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 Kt(e){await new Promise(t=>setTimeout(t,e*1e3))}async function qt(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Ht({...i,clientType:`oauth-app`}):await Ht({...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 Kt(r.interval),qt(e,t,n,r);if(a===`slow_down`)return await Kt(r.interval+7),qt(e,t,n,r);throw i}}async function Jt(e,t){return Wt(e,{auth:t})}async function Yt(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 Wt(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Xt=`0.0.0-development`;function Zt(e){let t=e.request||S.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Xt} ${xe()}`}}),{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(Jt.bind(null,i),{hook:Yt.bind(null,i)})}async function Qt(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=Zt({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 $t={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 en;(function(e){})(en||={});function tn(e){return n(ie,e)}function nn(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const rn=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function F(e){let t=e.toLowerCase().replace(/:\d+$/,``);rn.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 an(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function on(e,t,n=Qt){let r=nn(),{host:i,json:a}=e;F(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?an(!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?an(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function sn(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 on(t,await e())})}const cn=e=>e.name===`enter`||e.name===`return`;var ln=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},un=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},dn=class extends Error{name=`ExitPromptError`},fn=class extends Error{name=`HookError`},pn=class extends Error{name=`ValidationError`};const mn=new St;function hn(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function gn(e,t){let n=hn(e);return mn.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function I(){let e=mn.getStore();if(!e)throw new fn(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function _n(){return I().rl}function vn(e){return Ct.bind((...t)=>{let n=I(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function yn(e){let t=I(),{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 bn(){I().handleChange()}const L={queue(e){let t=I(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(_n());if(r!=null&&typeof r!=`function`)throw new pn(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=I();vn(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=I();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function xn(e){return typeof e==`function`}function R(e){return yn(t=>{let n=Ct.bind(function(e){t.get()!==e&&(t.set(e),bn())});if(t.initialized)return[t.get(),n];let r=xn(e)?e():e;return t.set(r),[r,n]})}function Sn(e,t){yn(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&L.queue(e),n.set(t)})}const Cn={prefix:{idle:P(`blue`,`?`),done:P(`green`,je.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>P(`yellow`,e))},style:{answer:e=>P(`cyan`,e),message:e=>P(`bold`,e),error:e=>P(`red`,`> ${e}`),defaultAnswer:e=>P(`dim`,`(${e})`),help:e=>P(`dim`,e),highlight:e=>P(`cyan`,e),key:e=>P(`cyan`,P(`bold`,`<${e}>`))}};function wn(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 Tn(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=wn(n)&&wn(r)?Tn(n,r):r}return t}function En(...e){return Tn(Cn,...e.filter(e=>e!=null))}function Dn({status:e=`idle`,theme:t}){let[n,r]=R(!1),[i,a]=R(0),{prefix:o,spinner:s}=En(t);return Sn(()=>{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 On(e){return R({current:e})[0]}function kn(e){let t=On(e);t.current=e,Sn(e=>{let n=!1,r=vn((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var An=e(Te(),1);function jn(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 Lr(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 Ir(t,await e())})}function Rr(e){try{let t=$e(`gh`,[`auth`,`token`,...e?[`--hostname`,e]:[]],{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}).trim();return t.length===0?{available:!1}:{available:!0,token:t}}catch{return{available:!1}}}async function zr(e,t,n=Rr){let r=n(e);return r.available&&r.token?r.token:(await t.get(e))?.token??null}async function Br(e,t){let{host:n,json:r}=e;F(n);let i=await zr(n,t);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 B({auth:i,...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 Vr(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 Br(t,await e())})}async function Hr(e,t){let{host:n}=e;await t.clear(n),process.stderr.write(`✓ Signed out from ${n}\n`)}function Ur(e){return new t(`signout`).description(`Remove stored credentials`).option(`--host <host>`,`GitHub hostname`,`github.com`).action(async t=>{await Hr(t,await e())})}async function Wr(e,t,n=Rr){let r=n(e);if(r.available&&r.token)return{tier:`A`,token:r.token};let i=await t.get(e);return i==null?{tier:`none`}:{tier:i.gitProtocol===`ssh`?`C`:`B`,token:i.token}}async function Gr(e,t){let{host:n,json:r}=e;F(n);let i=await Wr(n,t);i.tier===`none`&&(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 B({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,tier:i.tier,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 Kr(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 Gr(t,await e())})}function qr(){let e=new t(`auth`);e.description(`GitHub authentication management`);let n=()=>Pt();return e.addCommand(sn(n)),e.addCommand(Kr(n)),e.addCommand(Vr(n)),e.addCommand(Ur(n)),e.addCommand(Lr(n)),e.addCommand(Rt(n)),e}function V(e,t,n={}){let r=Re(e,t);if(!M(r))return{status:`missing`,lockPath:r};let i;try{i=JSON.parse(N(r,`utf-8`))}catch{return{status:`corrupt`,lockPath:r}}if(!i||typeof i!=`object`||!Ie(i.pid))return{status:`corrupt`,lockPath:r};let a=i;if(!(n.isAlive??C)(a.pid))return{status:`dead-pid`,lockPath:r,lock:a};let o=n.host??yt();return a.hostname===o?{status:`alive`,lockPath:r,lock:a}:{status:`foreign-host`,lockPath:r,lock:a}}function Jr(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 Yr(e){let t=e.inspect??(t=>V(e.lockDir,t)),n=e.unlink??(e=>ht(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Jr(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 Xr(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),Yr({lockDir:m(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function Zr(e,t,n={},r=Rr){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`]}}const Qr=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function $r(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 ei(e,t,n,r=process.cwd()){let i=He(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?j(r,t.dir):j(r,i.name);if(M(a)&&dt(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=await Pt(),s=await Zr(i.hostname,o,{}),c=Be({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=$r(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-
|
|
20
|
+
`);try{let{runInit:e}=await import(`./init-BFgpuKyQ.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{ti(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 ti(e){let t=A(e,`.git`,`info`,`exclude`);if(!M(t))return`no-exclude`;let n=N(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`:(gt(t,`${n}${n.length===0||n.endsWith(`
|
|
22
22
|
`)?``:`
|
|
23
|
-
`}.ok/\n`,`utf-8`),`appended`)}function ni(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 ei(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-
|
|
23
|
+
`}.ok/\n`,`utf-8`),`appended`)}function ni(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 ei(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-D2xK_xJa.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 ri=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],[`content`,`include`],[`content`,`exclude`]];function ii(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Ue;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 ai(e){let t=(0,At.parseDocument)(N(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 ri)t.hasIn(e)&&n.push(e.join(`.`));return n}function oi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function si(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=oi(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function ci(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??te,s=[];(r===`project`||r===`both`)&&s.push({scope:`project`,absPath:ne(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&s.push({scope:`user`,absPath:ne(`user`,a,e.homedirOverride)});let c=[],l=!0;for(let{scope:t,absPath:n}of s){if(!M(n)){c.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ai(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:si(ri.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!s.ok){c.push({path:n,scope:t,found:r,removed:[],error:fe(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 li(){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(()=>{ii({}).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 ci({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var U=e(Ze(),1);const W=2e3,ui=[/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 di(e){return ui.some(t=>t.test(e))}function fi(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 at(e)?e:null}catch{return null}}function pi(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)&&di(a)&&t.push({pid:o,command:a})}return t}function mi(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)&&di(o)&&t.push({pid:s,command:o})}return t}async function hi(){let e=k(`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=pi(t);if(n.length>0||t.trim()===``)return n}let t=k(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?[]:mi(t.stdout)}function gi(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=rt(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 _i(e){let t=k(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:W});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function vi(e){let t=k(`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 yi(e){let t=k(`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 bi(e){let t=[],n=e.split(`
|
|
@@ -57,7 +57,7 @@ setTimeout(() => process.exit(2), ${t+1e4});
|
|
|
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 lo=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=so({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 uo={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}},fo=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=Ji(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??uo}async _authThenStart(){if(!this._authProvider)throw new J(`No auth provider`);let e;try{e=await Ra(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=qi(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 lo({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=b.parse(JSON.parse(e.data));me(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 Ra(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:h(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}=Ha(o);if(this._resourceMetadataUrl=t,this._scope=n,await Ra(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}=Ha(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 Ra(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(),d(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=>b.parse(e)):[b.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 po(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 mo(e){if(e===void 0||e===``)return;let t=Number.parseInt(e,10);if(!(Number.isNaN(t)||t<=0))return t}function ho(e){return e===`0.0.0.0`||e===`::`?`localhost`:e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function go(e,t){return`http://${ho(e)}:${t}/mcp`}function _o(e,t){return`ws://${ho(e)}:${t}`}function vo(e){let t=new URL(e);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.pathname=``,t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}function yo(e,t){if(!(!e||e.port<=0)&&t(e.pid))return e.port}function bo(e){return M(e)?N(e,`utf-8`).trim():``}function xo(e,t){return`server did not start within ${e}ms${t?` stderr:\n${t}`:``}`}function So(e){if(e&&typeof e==`object`&&`method`in e&&`id`in e)return e.id}function Co(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 wo(e,t){return{jsonrpc:`2.0`,id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}async function To(e){let t=e.readLock??(()=>Le(e.lockDir)),n=e.isAlive??C,r=e.sleep??(e=>Ot(e)),i=e.spawn??tt,a=e.readErrorLog??bo,o=e.openErrorLog??(e=>ut(e,`w`)),s=e.closeFd??st,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 go(`localhost`,t)}let u=yo(t(),n);if(u!==void 0)return go(`localhost`,u);if(e.envAutoStart===`0`)throw Error(`Open Knowledge server is not running and OK_MCP_AUTOSTART=0 disables auto-start.`);M(e.lockDir)||ct(e.lockDir,{recursive:!0});let d=A(e.lockDir,`last-spawn-error.log`),f=o(d),p,m,h=Ge();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=yo(t(),n);if(e!==void 0)return go(`localhost`,e)}if(m){let e=a(d),t=e?` stderr:\n${e}`:``;throw Error(`spawn failed: ${m}${t}`)}throw Error(xo(c,a(d)))}function Eo(e,t){if(e.portOverride!==void 0)return vo(t);let n=e.readLock??(()=>Le(e.lockDir)),r=e.isAlive??C,i=yo(n(),r);if(i!==void 0)return _o(`localhost`,i)}async function Do(e,t={}){let n=t.stderr??process.stderr,r=t.requestTimeoutMs??12e4,i=t.createStdioTransport?t.createStdioTransport(t.stdin,t.stdout):new Hi(t.stdin,t.stdout),a=t.createHttpTransport?t.createHttpTransport(new URL(e)):new fo(new URL(e),{fetch:po(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=So(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(wo(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=Co(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 Oo(e){let t=e.stderr??process.stderr,n=e.bridgeFn??Do,r=await To(e),i=e.createConnectionId?.()??Et(),a=!1,o=(e.startKeepalive??Ki)({connectionId:i,resolveWsUrl:async()=>Eo(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)}const ko=xt(import.meta.url);function Ao(e){let t=j(e);for(;;){if(pe(t))return t;let n=it(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 \`${he}\`).`);t=n}}function jo(e){try{let t=new URL(e);return t.protocol===`file:`?xt(t):void 0}catch{return}}async function Mo(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=jo(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function No(e,t){if(e!==void 0)return Ao(e);let n=await t();if(n!==void 0)return Ao(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 Po(e){let t=process.stderr,n=e.spawnTimeoutMs??mo(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=We({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),o=new p({name:a,version:ze},{instructions:oe({dir:`.`})});ue(o);let s=Et(),c={current:{connectionId:s,displayName:s,colorSeed:s}},l=new Map,d=e=>{if(l.has(e))return;let n=f(e),r=c.current,i=Ki({connectionId:s,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>Eo({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});l.set(e,i)},m=()=>Mo({getClientCapabilities:()=>o.server.getClientCapabilities(),listRoots:()=>o.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),h=e=>No(e,m),g=async e=>{let t;if(e===void 0){let e=await m();if(e===void 0)return;t=Ao(e)}else t=Ao(e);let a=await i(t),o=await To({lockDir:f(t),contentDir:u(a,t),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return d(t),o.replace(/\/mcp$/,``)};o.server.oninitialized=()=>{let e=o.server.getClientVersion(),t=ae(e?.name,s);c.current={connectionId:s,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},ye(o,{serverUrl:g,resolveCwd:h,config:i,identityRef:c});let _=new Hi,v=!1,y,ee=async()=>{if(v)return;v=!0,y?.stop();for(let e of l.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}l.clear();let e=await Promise.allSettled([o.close(),_.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 o.connect(_),t.write(`[mcp] global stdio server ready (per-call project routing)
|
|
59
59
|
`);let b=!1,x=()=>{b||(b=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
|
|
60
|
-
`),process.exit(1)},5e3).unref(),ee().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,x),process.once(`SIGTERM`,x),process.platform===`darwin`){let e=Gi(ko,{realpathSync:ft,statInoSync:e=>mt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${ze}\n`);let{resolvedPath:n,inode:r}=e;y=Wi({detect:()=>Ui({bundleAnchorPath:ko,currentInode:r,platform:process.platform,realpath:ft,statInode:e=>mt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${ze} — exiting for host respawn\n`),x()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:ee}}function Fo(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=mo(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Oo({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await Po({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 Io(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-
|
|
60
|
+
`),process.exit(1)},5e3).unref(),ee().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,x),process.once(`SIGTERM`,x),process.platform===`darwin`){let e=Gi(ko,{realpathSync:ft,statInoSync:e=>mt(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${ze}\n`);let{resolvedPath:n,inode:r}=e;y=Wi({detect:()=>Ui({bundleAnchorPath:ko,currentInode:r,platform:process.platform,realpath:ft,statInode:e=>mt(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${ze} — exiting for host respawn\n`),x()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:ee}}function Fo(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=mo(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await Oo({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}await Po({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 Io(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-DYWPTqvW.mjs`),r=e(),i=process.cwd(),a=u(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 Lo(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function Ro(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 zo(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:gi(r),command:r,isDesktop:Lo(r)}}function Bo(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function Vo(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&Bo(e)?`ui-orphan`:`stale`}const Ho=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Uo(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 Wo(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function Go(e){return`${Wo(e.server.usage)} | ${Wo(e.ui?.usage??null)}`}function Ko(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function qo(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=Vo(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Ko(e),Go(e),t,String(n),Ro(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=Uo(Vo(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(`
|
|
61
61
|
`)}async function Jo(e={}){let t=e.discover??xi,n=e.inspect??V,r=e.log??(e=>console.log(e)),i=e.resolveCommand??_i,a=e.resolveUsage??vi,o=await t(),s=[];for(let e of o){let t=n(e,`server`),r=n(e,`ui`),o=zo(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:Vo(e)}));r(JSON.stringify(e,null,2));return}r(qo(e.all?s:s.filter(e=>Ho.has(Vo(e)))))}function Yo(){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 Jo({all:t.all===!0||e===`all`,json:t.json===!0})})}function X(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Xo(e,t,n=process.cwd()){let r=e.op??`sync`,i=Le(m(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=Be({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
|
|
62
62
|
`)),X(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Zo(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 Xo({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 Qo(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Xo({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 $o(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Xo({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 es(e){return typeof e==`string`&&r.includes(e)}async function ts(e={}){let t=j(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!ve[n])return{status:`failed`,message:`${E(`Error:`)} Unknown pack "${n}". Available: ${r.join(`, `)}`,exitCode:1};let i;try{i=await s({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof ee?{status:`prerequisite-missing`,message:`${E(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${E(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(i.created.length===0){let e=ve[n].name;return{status:`no-op`,message:`${T(`Your ${e} pack is already seeded.`)}\n${w(`Nothing to do.`)}`,plan:i,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${O(`Plan (dry-run — no changes made):`)}\n\n${rs(i,t)}`,plan:i,exitCode:0};if(!e.yes&&!await is(`${O(`Plan:`)}\n\n${rs(i,t)}\n\n${O(`Apply?`)} ${w(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:w(`Cancelled.`),plan:i,exitCode:0};let a=await re(i,{projectDir:t,packId:n});if(a.errors.length>0){let e=a.errors.map(e=>` ${E(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${D(`Applied`)} ${a.applied} entries, ${D(String(a.errors.length))} error(s):`,...e].join(`
|
|
63
63
|
`),plan:i,exitCode:1}}let o=ve[n].name;return{status:`applied`,message:`${T(`✓ Seeded ${o}`)} ${w(`(${a.applied} entries, ${a.durationMs}ms)`)}`,plan:i,exitCode:0}}function ns(){let e=[O(`Available packs:`)];for(let t of r){let n=ve[t];e.push(` ${T(t)} ${w(`—`)} ${n.name}: ${n.description}`)}return e.join(`
|
|
@@ -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,Qr as de,Qt as fe,R as pe,Rn as me,Rr as he,Rt as ge,S as _e,Sn as ve,Sr as ye,St as be,T as xe,Tn as Se,Tr as Ce,Tt as we,U as Te,Un as Ee,Ut as De,V as Oe,Vn as ke,Vr as Ae,Vt as je,W as Me,Wn as Ne,Wt as Pe,X as Fe,Xn as Ie,Xt as Le,Y as Re,Yn as ze,Yt as Be,Z as Ve,Zn as He,Zr as Ue,Zt as We,_ as Ge,_n as Ke,_r as qe,_t as Je,a as Ye,an as Xe,ar as Ze,at as Qe,b as $e,bn as et,br as tt,bt as nt,c as rt,cn as it,cr as at,ct as ot,d as st,di as ct,dn as lt,dr as ut,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,hi as wt,hn as Tt,hr as Et,ht as Dt,i as Ot,in as kt,ir as At,it as jt,j as Mt,jn as Nt,jr as Pt,jt as Ft,k as It,kn as Lt,kr as Rt,kt as zt,l as Bt,li as Vt,ln as Ht,lr as Ut,lt as Wt,m as Gt,mi as Kt,mn as qt,mr as Jt,mt as Yt,n as Xt,nn as Zt,nr as Qt,nt as $t,o as en,on as tn,or as nn,ot as rn,p as an,pn as on,pr as sn,pt as cn,q as ln,qn as un,qt as dn,r as fn,rn as pn,rr as mn,rt as hn,s as gn,si as _n,sn as vn,sr as yn,st as bn,t as xn,ti as Sn,tn as Cn,tr as wn,tt as Tn,u as En,ui as Dn,un as On,ur as kn,ut as An,v as jn,vn as Mn,vr as Nn,vt as Pn,w as Fn,wn as In,wr as Ln,wt as Rn,x as zn,xn as Bn,xr as Vn,xt as Hn,y as Un,yn as Wn,yr as Gn,yt as Kn,z as qn,zn as Jn,zr as Yn,zt as Xn}from"./dist-
|
|
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,Qr as de,Qt as fe,R as pe,Rn as me,Rr as he,Rt as ge,S as _e,Sn as ve,Sr as ye,St as be,T as xe,Tn as Se,Tr as Ce,Tt as we,U as Te,Un as Ee,Ut as De,V as Oe,Vn as ke,Vr as Ae,Vt as je,W as Me,Wn as Ne,Wt as Pe,X as Fe,Xn as Ie,Xt as Le,Y as Re,Yn as ze,Yt as Be,Z as Ve,Zn as He,Zr as Ue,Zt as We,_ as Ge,_n as Ke,_r as qe,_t as Je,a as Ye,an as Xe,ar as Ze,at as Qe,b as $e,bn as et,br as tt,bt as nt,c as rt,cn as it,cr as at,ct as ot,d as st,di as ct,dn as lt,dr as ut,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,hi as wt,hn as Tt,hr as Et,ht as Dt,i as Ot,in as kt,ir as At,it as jt,j as Mt,jn as Nt,jr as Pt,jt as Ft,k as It,kn as Lt,kr as Rt,kt as zt,l as Bt,li as Vt,ln as Ht,lr as Ut,lt as Wt,m as Gt,mi as Kt,mn as qt,mr as Jt,mt as Yt,n as Xt,nn as Zt,nr as Qt,nt as $t,o as en,on as tn,or as nn,ot as rn,p as an,pn as on,pr as sn,pt as cn,q as ln,qn as un,qt as dn,r as fn,rn as pn,rr as mn,rt as hn,s as gn,si as _n,sn as vn,sr as yn,st as bn,t as xn,ti as Sn,tn as Cn,tr as wn,tt as Tn,u as En,ui as Dn,un as On,ur as kn,ut as An,v as jn,vn as Mn,vr as Nn,vt as Pn,w as Fn,wn as In,wr as Ln,wt as Rn,x as zn,xn as Bn,xr as Vn,xt as Hn,y as Un,yn as Wn,yr as Gn,yt as Kn,z as qn,zn as Jn,zr as Yn,zt as Xn}from"./dist-DhjzONr6.mjs";import{_ as Zn,a as Qn,c as $n,d as er,f as tr,g as nr,i as rr,l as ir,m as ar,n as or,o as sr,p as cr,r as lr,s as ur,t as dr,u as fr}from"./server-lock-D7DXNVql-BRVVzA6T.mjs";export{xn as AGENT_ID_MAX_LEN,Xt as AGENT_ID_RE,fn as AGENT_WRITE_ORIGIN,Ot as AgentFocusBroadcaster,Ye as AgentPresenceBroadcaster,en as AgentSessionCapacityError,gn as AgentSessionManager,rt as BacklinkIndex,Bt as CC1Broadcaster,Sn as CC1_CONTRACT_VERSION,En as CONFLICT_MARKER_RE,st as CURSOR_BUNDLE_PATHS_BY_PLATFORM,ht as ConfigSchema,an as DEFAULT_CHECKPOINT_RETENTION,Gt as DEFAULT_PACK_ID,Ct as FILE_SYSTEM_WRITER,yt as FILE_WATCHER_ORIGIN,Ge as GIT_UPSTREAM_WRITER,Ue as GitDirAccessError,jn as HOCUSPOCUS_AUTH_REJECTION_REASONS,Un as HocuspocusAuthRejection,$e as HocuspocusAuthTokenSchema,zn as INSTALLED_AGENTS_SCHEMES,_e as LIVE_DERIVED_INDEX_DEBOUNCE_MS,d as LOG_MD_TEMPLATE,Fn as MANAGED_RENAME_ORIGIN,xe as MAX_AGENT_SESSIONS,y as MCP_CONNECTION_ID_HEADER,h as MCP_SERVER_NAME,te as MISSING_OK_CONFIG_MESSAGE,de as MalformedGitPointerError,It as McpLogger,r as MissingOkConfigError,Mt as OBSERVER_SYNC_ORIGIN,_n as ORPHAN_MODES,q as PinoLogger,dr as ProcessLockCollisionError,Z as ProjectGitInitError,ae as ROLLBACK_ORIGIN,or as RUNTIME_VERSION,C as SERVICE_WRITER,N as SKILL_INSTALL_EVENTS_FILE_REL,Vt as SKILL_STATE_TARGETS,U as STARTER_FOLDERS,pe as STARTER_FOLDER_FRONTMATTER_FILENAME,qn as STARTER_PACKS,s as STARTER_PACK_IDS,Oe as STARTER_TEMPLATES,A as STATE_MANIFEST_FILENAME,lr as STATE_SCHEMA_VERSION,Dn as SYSTEM_DOC_NAME,Te as SeedPrerequisiteError,Me as SeedRootDirError,rr as ServerLockCollisionError,D as StateManifestError,B as TagIndex,ln as UiLockCollisionError,Qn as acquireProcessLock,sr as acquireServerLock,L as acquireUiLock,Re as applyAgentMarkdownWrite,Fe as applyExternalChange,Ve as applySeed,le as assertCompatibleStateManifest,e as assertNeverDiskEvent,mt as attachIdleShutdown,Tn as bootServer,$t as buildAndOpenSkill,hn as buildExecResult,jt as buildInstructions,Qe as buildReadResult,rn as buildSkillZip,bn as buildStarterFolderFrontmatterYaml,ot as buildWipTree,Wt as classifyEvents,An as classifyFsPath,dt as clearContributors,vt as coercePackId,ct as colorFromSeed,cn as commitUpstreamImport,Yt as commitWip,Dt as commitWipFromTree,St as containsConflictMarkers,Je as contentHash,Pn as contributorCount,Kn as createApiExtension,nt as createAssetServeMiddleware,Hn as createContentFilter,be as createContentFilterAsync,m as createExternalChangeHandler,Rn as createLiveDerivedIndexExtension,we as createMcpHttpHandler,S as createOsProbe,v as createPersistenceExtension,ie as createServer,zt as createServerObserverExtension,o as createStreamingErrorWriter,Ft as createTestLogger,X as detectClaudeDesktopPresence,ee as detectProjectShape,ce as ensureProjectGit,E as errorResponse,I as evictStaleTrackerEntries,K as extractWikiLinksFromMarkdown,ge as findEnclosingGitRoot,Xn as findEnclosingProjectRoot,u as formatAuthRejectionWire,je as formatContributors,M as formatContributorsFrom,De as gcCheckpointRefs,Pe as getCurrentMcpLogger,k as getLocalDir,H as getLogger,dn as getMeter,z as getMetrics,Be as getTracer,Le as handleCollabSocketError,We as handleSpawnCursor,Kt as iconFromClientName,fe as incrementCollabSocketFilteredError,n as incrementServerObserverFire,ft as initShadowRepo,Cn as initTelemetry,Zt as installPrettyZodErrors,pn as installTestLoggers,kt as installUserSkill,Xe as isAllowedApiOrigin,tn as isAllowedWorkspaceHostHeader,vn as isConfigDoc,it as isHocuspocusAuthRejectionReason,Ht as isKnownPackId,On as isLoopbackAddress,wt as isOrphanMode,lt as isPairedWriteOrigin,gt as isPathWithinDir,ur as isProcessAlive,on as isProjectRoot,qt as isSelfWrite,Tt as isSystemDoc,$n as isValidLockPid,bt as lastKnownHash,Ke as listRescueCheckpoints,Mn as listStarterPacks,Wn as loadPrincipal,ir as lockFilePath,et as loggerFactory,Bn as mountMcpAndApi,ve as normalizeFsPath,f as parseAuthRejectionWire,In as parseHocuspocusAuthToken,Se as parseKeepaliveConnectionId,b as pathToDocName,g as planSeed,ne as readAllTargets,Lt as readBranchFromHead,fr as readProcessLock,er as readProcessLockDetailed,tr as readServerLock,i as readServerPackageVersion,Nt as readSkillInstallStateSnapshot,J as readStateManifest,Q as readTargetRecordedAt,oe as readTargetVersion,w as readUiLock,P as reconcile,W as recordContributor,me as recordSkillInstallEvent,Jn as registerAllTools,c as registerWrite,cr as releaseProcessLock,ar as releaseServerLock,ke as releaseUiLock,j as removeLastKnownHash,Ee as resetMetrics,Ne as resolveBundledSkillDir,O as resolveContentDir,V as resolveCursorBinaryDefault,un as resolveCursorSpawnInvocation,R as resolveLockDir,ze as resolvePack,Ie as resolvePackageVersion,He as restoreContributors,ue as rewriteMarkdownLinksForDocumentRename,t as rewriteWikiLinksForDocumentRename,pt as runAuthReposSubprocess,wn as runAuthStatusSubprocess,Qt as runCloneSubprocess,mn as runDeviceFlowSubprocess,At as runWithMcpLogger,Ze as safeContentPath,nn as safeSubdir,yn as safetyCheckpoint,at as sanitizeClientName,Ut as saveInMemoryCheckpoint,kn as saveVersion,ut as seedBasenameIndex,_t as setActiveSpanAttributes,sn as shadowGit,Jt as shutdownTelemetry,Et as spawnDetached,xt as splitMarkdownBlocks,qe as startWatcher,Nn as streamingProblemEvent,Gn as swapContributors,tt as toBroadcasterKey,Vn as tracedAppendFileSync,ye as tracedLinkSync,p as tracedMkdir,Ln as tracedMkdirSync,Ce as tracedRename,x as tracedRenameSync,_ as tracedRmSync,re as tracedRmdirSync,Rt as tracedUnlinkSync,a as tracedWriteFile,Pt as tracedWriteFileSync,Y as updateLastKnownHash,nr as updateProcessLockPort,Zn as updateServerLockPort,$ as updateUiLockPort,se as validateAgentId,T as validateCloneInputs,F as validateSkillZip,G as withSpan,he as withSpanSync,Yn as writeStateManifest,l as writeTargetVersion,Ae as writeTracker};
|