@inkeep/open-knowledge 0.4.0-beta.32 → 0.4.0-beta.34
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 +1 -1
- package/dist/cli.mjs +5 -5
- package/dist/constants-BgI7SDCI.mjs +2 -0
- package/dist/{dist-BjlSvO5w.mjs → dist-BXmbRKLs.mjs} +1 -1
- package/dist/{dist-Bfw3oOGm.mjs → dist-BaVVyZsg.mjs} +218 -2
- package/dist/index.mjs +1 -1
- package/dist/init-CfT911gp.mjs +1 -0
- package/dist/{init-DsLc7vc7.mjs → init-Mu6hjAn2.mjs} +3 -3
- package/dist/loader-tcpZSp2X.mjs +1 -0
- package/dist/{loader-DmKx1Dxe.mjs → loader-th8fUQ0l.mjs} +2 -2
- package/dist/preview-B14jfjgL.mjs +1 -0
- package/dist/{preview-CuLb6srO.mjs → preview-Brj3agTC.mjs} +2 -2
- package/dist/public/assets/{ActivityModeContent-PLMlj69Z.js → ActivityModeContent-CukRGM5b.js} +1 -1
- package/dist/public/assets/{DocumentContext-DyDoN3zw.js → DocumentContext-Dnlc0y78.js} +1 -1
- package/dist/public/assets/{SettingsDialog-BZIR95bl.js → SettingsDialog-D01daWLi.js} +1 -1
- package/dist/public/assets/{SourceEditor-BSNx4vgo.js → SourceEditor-oc5DmPOz.js} +2 -2
- package/dist/public/assets/{config-validation-events-CQdOhgu4.js → config-validation-events-BhBbdwp7.js} +1 -1
- package/dist/public/assets/index-DhEY5RAu.css +1 -0
- package/dist/public/assets/{index-DplFbAir.js → index-n61bMVO9.js} +67 -67
- package/dist/public/assets/{typing-burst-detector-2N-LtlIn.js → typing-burst-detector-niWkdPcc.js} +1 -1
- package/dist/public/index.html +5 -5
- package/dist/{src-CPSJr8lr.mjs → src-_bKfCVLS.mjs} +2 -2
- package/dist/start-BiFE3OLx.mjs +1 -0
- package/dist/{start-DUBJCx0O.mjs → start-JWghIgzZ.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-BVG2ymMz.mjs +0 -2
- package/dist/init-CcjfJ0-a.mjs +0 -1
- package/dist/loader-BLwabAxT.mjs +0 -1
- package/dist/preview-GtCa8ObI.mjs +0 -1
- package/dist/public/assets/index-CjbILLtI.css +0 -1
- package/dist/start-BoXsjqPU.mjs +0 -1
|
@@ -1506,7 +1506,223 @@ tags: [published]
|
|
|
1506
1506
|
---
|
|
1507
1507
|
|
|
1508
1508
|
(Final version. Treat as immutable; if you need to revise, fork to a new draft.)
|
|
1509
|
-
`},
|
|
1509
|
+
`},GBRAIN_FOLDERS=[{path:`people`,title:`People`,description:"Person dossiers. Compiled-truth section above `---` (overwritten as new evidence arrives); append-only timeline below (`YYYY-MM-DD:` entries, never edit existing ones — only append). Frontmatter `type: person`. Linked to `companies/` (affiliations, founders, investors) and `meetings/` (attendance). Agent: when a meeting note mentions a person not yet captured, stub a file here; route new facts into either compiled-truth (if they update current understanding) or timeline (raw evidence). Never rewrite the timeline.",tags:[`person`,`entity`,`dossier`],starterTemplate:`person`},{path:`companies`,title:`Companies`,description:"Company dossiers. Same body convention as `people/`: compiled-truth above `---`, append-only timeline below. Frontmatter `type: company`. Linked to `people/` (founders, employees, investors) and `meetings/`. Agent: when a person dossier references a company not yet captured, stub a file here; surface company-to-person edges when both exist.",tags:[`company`,`entity`,`dossier`],starterTemplate:`company`},{path:`meetings`,title:`Meetings`,description:"Meeting notes. Filename `YYYY-MM-DD-<slug>.md`. Frontmatter carries `date`, `attendees: [[wikilinks]]`, and `type: meeting`. Body is raw notes with `[[wiki-links]]` to people, companies, concepts mentioned. Agent: after a meeting note lands, extract entity mentions and append timeline entries to each referenced dossier. Do NOT rewrite the meeting note — it is the verbatim record.",tags:[`meeting`,`note`],starterTemplate:`meeting`},{path:`concepts`,title:`Concepts`,description:'Evergreen idea pages — abstract patterns, frameworks, recurring concepts that surface across people / companies / meetings. Compiled-truth + timeline convention. Frontmatter `type: concept`. Agent: when a meeting note or person dossier references a concept (e.g. "agent-runtime observability") not yet captured, stub a file here; thread links so the concept becomes a hub for everywhere it appears.',tags:[`concept`,`idea`,`evergreen`],starterTemplate:`concept`},{path:`originals`,title:`Originals`,description:"Your own thinking — untransformed. Frontmatter `type: idea`. Use freely; use `[[wiki-links]]` for anything that should become its own entity. Agent: treat originals as authoritative source material when extracting facts — these are the user's words, not inferences. Append timeline entries to referenced dossiers when a clear new claim appears, citing the original by wikilink.",tags:[`original`,`thinking`,`user`],starterTemplate:`original`},{path:`media`,title:`Media`,description:"Bulk transcripts, voice notes, articles, large attachments. Frontmatter `type: transcript` (template provided). Often `.okignore`-d so the OK index stays light. If gbrain is installed alongside OK, the `media-ingest` skill produces transcripts + backlinks here (video / audio / PDF / books), and the `voice-note-ingest` skill captures voice memos verbatim while routing the extracted content into the right entity dossier. Without gbrain, the agent does both on request. Keep raw — analysis belongs in dossiers, not here.",tags:[`media`,`transcript`,`bulk`],starterTemplate:`transcript`}],GBRAIN_TEMPLATES={person:`---
|
|
1510
|
+
title: Person Name
|
|
1511
|
+
description: One-line characterization — who they are, why they matter to you.
|
|
1512
|
+
type: person
|
|
1513
|
+
created: {{date}}
|
|
1514
|
+
author: {{user}}
|
|
1515
|
+
tags: [person]
|
|
1516
|
+
---
|
|
1517
|
+
|
|
1518
|
+
## Compiled truth
|
|
1519
|
+
|
|
1520
|
+
(Your current best understanding. Overwritten as new evidence arrives.)
|
|
1521
|
+
|
|
1522
|
+
---
|
|
1523
|
+
|
|
1524
|
+
## Timeline
|
|
1525
|
+
|
|
1526
|
+
{{date}}: First entry. Append-only — never edit existing entries, only add new \`YYYY-MM-DD:\` lines.
|
|
1527
|
+
`,company:`---
|
|
1528
|
+
title: Company Name
|
|
1529
|
+
description: One-line company summary — what they do, who's involved.
|
|
1530
|
+
type: company
|
|
1531
|
+
created: {{date}}
|
|
1532
|
+
author: {{user}}
|
|
1533
|
+
tags: [company]
|
|
1534
|
+
---
|
|
1535
|
+
|
|
1536
|
+
## Compiled truth
|
|
1537
|
+
|
|
1538
|
+
(Your current best understanding of the company. Overwritten as new evidence arrives.)
|
|
1539
|
+
|
|
1540
|
+
---
|
|
1541
|
+
|
|
1542
|
+
## Timeline
|
|
1543
|
+
|
|
1544
|
+
{{date}}: First entry.
|
|
1545
|
+
`,meeting:`---
|
|
1546
|
+
title: Meeting Title
|
|
1547
|
+
description: One-line meeting summary — fill in after the meeting.
|
|
1548
|
+
type: meeting
|
|
1549
|
+
date: {{date}}
|
|
1550
|
+
attendees: []
|
|
1551
|
+
author: {{user}}
|
|
1552
|
+
tags: [meeting]
|
|
1553
|
+
---
|
|
1554
|
+
|
|
1555
|
+
## Notes
|
|
1556
|
+
|
|
1557
|
+
(Raw notes from the meeting. Use \`[[wiki-links]]\` for people, companies, concepts mentioned.)
|
|
1558
|
+
|
|
1559
|
+
## Action items
|
|
1560
|
+
|
|
1561
|
+
- [ ]
|
|
1562
|
+
`,concept:`---
|
|
1563
|
+
title: Concept Name
|
|
1564
|
+
description: One-line concept summary — what it names and why it recurs.
|
|
1565
|
+
type: concept
|
|
1566
|
+
created: {{date}}
|
|
1567
|
+
author: {{user}}
|
|
1568
|
+
tags: [concept]
|
|
1569
|
+
---
|
|
1570
|
+
|
|
1571
|
+
## Compiled truth
|
|
1572
|
+
|
|
1573
|
+
(Your current best understanding of the concept. Rewrite as evidence accumulates.)
|
|
1574
|
+
|
|
1575
|
+
---
|
|
1576
|
+
|
|
1577
|
+
## Timeline
|
|
1578
|
+
|
|
1579
|
+
{{date}}: First entry.
|
|
1580
|
+
`,original:`---
|
|
1581
|
+
title: Idea Title
|
|
1582
|
+
description: One-line summary of the idea or take.
|
|
1583
|
+
type: idea
|
|
1584
|
+
date: {{date}}
|
|
1585
|
+
author: {{user}}
|
|
1586
|
+
tags: [original]
|
|
1587
|
+
---
|
|
1588
|
+
|
|
1589
|
+
(Your own thinking. Use \`[[wiki-links]]\` for anything that should become its own entity.)
|
|
1590
|
+
`,transcript:`---
|
|
1591
|
+
title: Transcript
|
|
1592
|
+
description: One-line transcript summary — source and key topic.
|
|
1593
|
+
type: transcript
|
|
1594
|
+
date: {{date}}
|
|
1595
|
+
source:
|
|
1596
|
+
duration:
|
|
1597
|
+
author: {{user}}
|
|
1598
|
+
tags: [transcript, media]
|
|
1599
|
+
---
|
|
1600
|
+
|
|
1601
|
+
## Source
|
|
1602
|
+
|
|
1603
|
+
(URL, file, or device captured from.)
|
|
1604
|
+
|
|
1605
|
+
## Transcript
|
|
1606
|
+
|
|
1607
|
+
(Paste raw transcript. The gbrain \`media-ingest\` skill — if installed — produces structured transcripts with backlinks to mentioned entities (video / audio / PDF / books). For voice memos specifically, gbrain's \`voice-note-ingest\` captures verbatim then routes into the right entity dossier. Without gbrain, ask your agent to do it on demand.)
|
|
1608
|
+
`},GBRAIN_LOG_MD=`---
|
|
1609
|
+
title: Work Log
|
|
1610
|
+
description: Append-only audit trail. After each turn that creates, edits, or restructures content in the vault, append one dated entry here (one per turn, not per file). gbrain users — your dream-cycle runs land here too.
|
|
1611
|
+
---
|
|
1612
|
+
|
|
1613
|
+
# Work Log
|
|
1614
|
+
|
|
1615
|
+
Append-only audit trail. **Append a dated entry after any turn that creates, edits, or restructures content in the vault** — one entry per turn, not per file.
|
|
1616
|
+
|
|
1617
|
+
What to log:
|
|
1618
|
+
|
|
1619
|
+
- New entity dossiers stubbed (\`people/\` / \`companies/\` / \`concepts/\`)
|
|
1620
|
+
- Meeting notes captured
|
|
1621
|
+
- \`dream\` runs (if gbrain is installed alongside) — gbrain writes the phase summary here
|
|
1622
|
+
- Original-thinking captures
|
|
1623
|
+
- Folder restructures or rule changes
|
|
1624
|
+
|
|
1625
|
+
**Reference docs as markdown links, not bare paths.** Every doc you touched should appear as \`[name](./path/to/doc.md)\` so the log shows up in \`get_backlinks\` for those docs.
|
|
1626
|
+
|
|
1627
|
+
<!-- Example entry shape:
|
|
1628
|
+
|
|
1629
|
+
## YYYY-MM-DD — <short title>
|
|
1630
|
+
|
|
1631
|
+
- <what was done>
|
|
1632
|
+
- Dossiers updated: [Jane Founder](./people/jane-founder.md), [Jane Co](./companies/jane-co.md)
|
|
1633
|
+
- Meetings logged: [2026-05-12 coffee](./meetings/2026-05-12-jane-founder-coffee.md)
|
|
1634
|
+
- Open follow-ups: <topic-1>, <topic-2>
|
|
1635
|
+
|
|
1636
|
+
-->
|
|
1637
|
+
`,GBRAIN_USER_MD=`---
|
|
1638
|
+
title: User profile
|
|
1639
|
+
description: Who you are. Agent reads this on every briefing / enrichment pass. Keep current.
|
|
1640
|
+
---
|
|
1641
|
+
|
|
1642
|
+
# User profile
|
|
1643
|
+
|
|
1644
|
+
**Name:**
|
|
1645
|
+
|
|
1646
|
+
**Role:**
|
|
1647
|
+
|
|
1648
|
+
**Current focus areas:**
|
|
1649
|
+
|
|
1650
|
+
- ...
|
|
1651
|
+
|
|
1652
|
+
**Network anchors:** (people you talk to most; use \`[[wikilinks]]\` once \`people/\` dossiers exist)
|
|
1653
|
+
|
|
1654
|
+
- [[]]
|
|
1655
|
+
|
|
1656
|
+
**Communication style:** (how you prefer briefings, summaries, suggestions)
|
|
1657
|
+
|
|
1658
|
+
`,GBRAIN_SOUL_MD=`---
|
|
1659
|
+
title: Agent identity
|
|
1660
|
+
description: Agent persona, values, voice. If you run gbrain alongside, this is the output of its \`soul-audit\` skill — a 6-phase interview. Fill in by hand or run \`gbrain soul-audit\`.
|
|
1661
|
+
---
|
|
1662
|
+
|
|
1663
|
+
# Agent identity (SOUL.md)
|
|
1664
|
+
|
|
1665
|
+
**Persona name:**
|
|
1666
|
+
|
|
1667
|
+
**Voice + tone:** (how the agent speaks — formal / casual / direct / hedged / etc.)
|
|
1668
|
+
|
|
1669
|
+
**Values:** (what the agent optimizes for when faced with trade-offs)
|
|
1670
|
+
|
|
1671
|
+
- ...
|
|
1672
|
+
|
|
1673
|
+
**What to avoid:** (postures / framings / topics the agent should never adopt)
|
|
1674
|
+
|
|
1675
|
+
- ...
|
|
1676
|
+
|
|
1677
|
+
**Run \`gbrain soul-audit\` to populate this via a guided interview.** Or write it by hand — anything here informs every gbrain skill that loads SOUL.md on each call.
|
|
1678
|
+
`,GBRAIN_ACCESS_POLICY_MD=`---
|
|
1679
|
+
title: Access policy
|
|
1680
|
+
description: What the agent may read, write, and surface. gbrain's 4-tier privacy model — but useful even without gbrain.
|
|
1681
|
+
---
|
|
1682
|
+
|
|
1683
|
+
# Access policy
|
|
1684
|
+
|
|
1685
|
+
## Tier 1 — Public
|
|
1686
|
+
|
|
1687
|
+
(Things the agent may surface in any briefing or shared context.)
|
|
1688
|
+
|
|
1689
|
+
## Tier 2 — Internal / professional
|
|
1690
|
+
|
|
1691
|
+
(Things the agent may use to inform briefings + dossiers, but should not surface to external parties without prompting.)
|
|
1692
|
+
|
|
1693
|
+
## Tier 3 — Personal
|
|
1694
|
+
|
|
1695
|
+
(Things the agent may use to anchor briefings, but should never write into a dossier that might be shared.)
|
|
1696
|
+
|
|
1697
|
+
## Tier 4 — Restricted
|
|
1698
|
+
|
|
1699
|
+
(Things the agent should never read or surface. Use \`.okignore\` to enforce hard exclusion at the file level.)
|
|
1700
|
+
|
|
1701
|
+
`,GBRAIN_HEARTBEAT_MD=`---
|
|
1702
|
+
title: Operational cadence
|
|
1703
|
+
description: When the agent does scheduled work — daily briefings, end-of-day dossier maintenance, weekly audits. If gbrain is installed, its \`dream\` schedule also lands here.
|
|
1704
|
+
---
|
|
1705
|
+
|
|
1706
|
+
# Heartbeat
|
|
1707
|
+
|
|
1708
|
+
## Daily
|
|
1709
|
+
|
|
1710
|
+
- **Morning briefing** (\`gbrain briefing\` or ad-hoc agent prompt): today's calendar + per-attendee dossier context.
|
|
1711
|
+
- **End of day**: ingest the day's meeting notes; let \`dream\` (or a manual agent prompt) extract entity mentions and update dossiers overnight.
|
|
1712
|
+
|
|
1713
|
+
## Nightly (\`gbrain dream\` if installed)
|
|
1714
|
+
|
|
1715
|
+
- 11-phase maintenance cycle: lint → backlinks → sync → synthesize → extract → patterns → recompute_emotional_weight → consolidate → embed → orphans → purge.
|
|
1716
|
+
|
|
1717
|
+
## Weekly
|
|
1718
|
+
|
|
1719
|
+
- Audit: dossiers untouched in 30+ days, contradictions between compiled-truth and recent timeline entries.
|
|
1720
|
+
|
|
1721
|
+
## Monthly
|
|
1722
|
+
|
|
1723
|
+
- Run OK's \`get_dead_links\` across the vault — triage redlinks into new entities (gbrain creates dossiers), typo fixes (OK edits in place), or intentional placeholders.
|
|
1724
|
+
|
|
1725
|
+
`,STARTER_PACKS={"knowledge-base":{id:`knowledge-base`,name:`Knowledge base`,description:`Source-grounded canonical articles. Three layers — sources → research → articles — wired to the ingest / research / consolidate MCP tools.`,defaultSubfolder:`brain`,folders:KNOWLEDGE_BASE_FOLDERS,templates:KNOWLEDGE_BASE_TEMPLATES,rootFiles:{"log.md":KNOWLEDGE_BASE_LOG_MD}},"software-lifecycle":{id:`software-lifecycle`,name:`Software lifecycle`,description:`Proposals, decisions, specs, postmortems, guides — the doc lifecycle for an engineering team or OSS project.`,defaultSubfolder:`project-docs`,folders:SOFTWARE_LIFECYCLE_FOLDERS,templates:SOFTWARE_LIFECYCLE_TEMPLATES},"plain-notes":{id:`plain-notes`,name:`Plain notes`,description:`Just notes/ + daily/. The "I just want to write" escape hatch — no posture imposed, link freely.`,defaultSubfolder:void 0,folders:PLAIN_NOTES_FOLDERS,templates:PLAIN_NOTES_TEMPLATES},worldbuilding:{id:`worldbuilding`,name:`Worldbuilding`,description:`Encyclopedia for fiction: characters, settings, themes, factions, lore. The graph is the product — agent excels at auto-stub creation and dead-link sweeps.`,defaultSubfolder:`world`,folders:WORLDBUILDING_FOLDERS,templates:WORLDBUILDING_TEMPLATES},"writing-pipeline":{id:`writing-pipeline`,name:`Writing pipeline`,description:`Three-stage drafting flow: ideas → drafts → published. Lean by default; CRDT history covers per-file revisions.`,defaultSubfolder:`writing`,folders:WRITING_PIPELINE_FOLDERS,templates:WRITING_PIPELINE_TEMPLATES},gbrain:{id:`gbrain`,name:`Gbrain`,description:`Track people, companies, and meetings — each gets a dossier with a rewritable summary and an append-only timeline. Inspired by Garry Tan's gbrain.`,defaultSubfolder:`vault`,folders:GBRAIN_FOLDERS,templates:GBRAIN_TEMPLATES,rootFiles:{"log.md":GBRAIN_LOG_MD,"USER.md":GBRAIN_USER_MD,"SOUL.md":GBRAIN_SOUL_MD,"ACCESS_POLICY.md":GBRAIN_ACCESS_POLICY_MD,"HEARTBEAT.md":GBRAIN_HEARTBEAT_MD}}},STARTER_PACK_IDS=Object.keys(STARTER_PACKS);function resolvePack(e){return e&&STARTER_PACKS[e]||STARTER_PACKS[DEFAULT_PACK_ID]}function isKnownPackId(e){return typeof e==`string`&&STARTER_PACK_IDS.includes(e)}function coercePackId(e){return isKnownPackId(e)?e:void 0}function deriveFolderSummary(e){let t=e.trim(),s=(/^([^.!?]+[.!?])/.exec(t)?.[1]??t).trim();return s.length<=140?s:`${s.slice(0,137)}…`}function listStarterPacks(){return STARTER_PACK_IDS.map(e=>{let t=STARTER_PACKS[e];return{id:t.id,name:t.name,description:t.description,defaultSubfolder:t.defaultSubfolder,folders:t.folders.map(e=>({path:e.path,summary:deriveFolderSummary(e.description)}))}})}const STARTER_FOLDERS=KNOWLEDGE_BASE_FOLDERS,STARTER_TEMPLATES=KNOWLEDGE_BASE_TEMPLATES,LOG_MD_TEMPLATE=KNOWLEDGE_BASE_LOG_MD,STARTER_FOLDER_FRONTMATTER_FILENAME=`frontmatter.yml`;function buildStarterFolderFrontmatterYaml(e){let t=[];t.push(`title: ${yamlScalar(e.title)}`),t.push(`description: ${yamlScalar(e.description)}`),t.push(`tags:`);for(let s of e.tags)t.push(` - ${yamlScalar(s)}`);return`${t.join(`
|
|
1510
1726
|
`)}\n`}function yamlScalar(e){return e===``?`""`:/[:#\n"'\\]|^\s|\s$/.test(e)?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e}function resolveFileContent(e,t){let s=/^([^/]+)\/\.ok\/frontmatter\.yml$/.exec(e);if(s){let e=t.folders.find(e=>e.path===s[1]);return e?buildStarterFolderFrontmatterYaml(e):void 0}let g=/^([^/]+)\/\.ok\/templates\/([^/]+)\.md$/.exec(e);if(g){let e=g[2]??``;return t.templates[e]}if(!e.includes(`/`)&&t.rootFiles?.[e]!==void 0)return t.rootFiles[e]}async function applySeed(e,t={}){let s=Date.now(),g=resolve(t.projectDir??process.cwd()),S=resolvePack(t.packId??`knowledge-base`),w=0,E=[],D=[];for(let t of e.created)try{let e=assertEntryPathInProject(g,t.path);D.push({entry:t,absPath:e})}catch(e){E.push({path:typeof t.path==`string`?t.path:String(t.path),error:e instanceof SeedRootDirError||e instanceof Error?e.message:String(e)})}for(let{entry:e,absPath:t}of D.filter(e=>e.entry.kind===`folder`))try{mkdirSync(t,{recursive:!0}),w+=1}catch(t){E.push({path:e.path,error:t instanceof Error?t.message:String(t)})}for(let{entry:e,absPath:t}of D.filter(e=>e.entry.kind===`file`)){let s=e.template??e.path,g=resolveFileContent(s,S);if(g===void 0){E.push({path:e.path,error:`No content template registered for template id "${s}" in pack "${S.id}"`});continue}if(!existsSync(t))try{writeFileSync(t,g,`utf-8`),w+=1}catch(t){E.push({path:e.path,error:t instanceof Error?t.message:String(t)})}}return{applied:w,errors:E,durationMs:Date.now()-s}}const PERSONAL_TEMPLATES={"daily-journal":`---
|
|
1511
1727
|
title: '{{date}}'
|
|
1512
1728
|
description: Daily journal entry — universal template, works in any vault.
|
|
@@ -2365,4 +2581,4 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
2365
2581
|
`).split(`
|
|
2366
2582
|
`),s=[],g=!1,S=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){g?RegExp(`^\\s{0,3}${S[0]==="`"?"`":`~`}{${S.length},}\\s*$`).test(e)&&(g=!1,S=``):(g=!0,S=t[1]);continue}if(g)continue;let w=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(w);if(e===null)break;let t=e[2];t&&s.push(t)}}return s}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:s,body:g}=stripFrontmatter(t),S=extractFrontmatterTags(s?unwrapFrontmatterFences(s):``),w=extractInlineTagsFromBody(g),E=new Set([...S,...w]),D=new Set;for(let e of E)for(let t of expandTagToHierarchy(e))D.add(t);this.applyDocSnapshot(e,E,D)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let s of t){let t=this.state.byTag.get(s);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(s))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,s){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,s)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let s=[];for(let g of t){let t=this.state.byDocLiteral.get(g);if(!t)continue;let S=tagsMatchingPrefix(t,e);s.push({docName:g,matchingTags:[...S].sort((e,t)=>e.localeCompare(t))})}return s.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),s=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&s.add(e.slice(0,t));let g=t;for(;g>0;)s.add(e.slice(0,g)),g=e.indexOf(`/`,g+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!s.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:s}of e)try{let e=readFileSync(s,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,s){let g=this.state.byDoc.get(e)??new Set;for(let t of g){if(s.has(t))continue;let g=this.state.byTag.get(t);g&&(g.delete(e),g.size===0&&this.state.byTag.delete(t))}for(let t of s){let s=this.state.byTag.get(t);s||(s=new Set,this.state.byTag.set(t,s)),s.add(e)}s.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,s),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let s;try{s=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let g of s){let s=join(e,g.name);if(g.isDirectory()){let e=relative(this.contentDir,s);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(s,t);continue}if(!g.isFile()||!isSupportedDocFile(g.name))continue;let S=relative(this.contentDir,s);this.contentFilter?.isExcluded(S)||t.push({docName:stripDocExtension(S),filePath:s})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:s=t,quiet:g=!0,debounce:S=2e3,maxDebounce:w=1e4,gitEnabled:E=!0,commitDebounceMs:D=3e4,wipRef:O=`refs/wip/main`,configHomedirOverride:k,enableTestRoutes:j=!1,shadowRepo:F,contentRoot:L,destroyTimeoutMs:B=1e4,localOpCliArgs:H,skipStateManifestCheck:q=!1}=e,J=getLogger(`server`);function Y(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||J.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>J.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ee=randomUUID(),te=getLocalDir(s);if(acquireServerLock(te,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:te,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(te),e}let ne=createBasenameIndex(),ae=(e,t)=>ne.resolveEmbed(e,t),oe=(e,s)=>{let g=ne.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g),w=resolve(t);if(S!==w&&!S.startsWith(`${w}/`))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},se,ce,ue,de,fe,me,ge,_e=null,ve=null,ye=null,Ce=null,we=new Set,Te=!1,De,je,Me,Pe=new Promise((e,t)=>{je=e,Me=t});function Ie(e){_e?.signal(e)}let Re=2e3,ze=null;function Be(){ze!==null&&clearTimeout(ze),ze=setTimeout(()=>{ze=null,ce.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let Ve=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ue=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||Ve.setRenamed(e,t)},We=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(Ve.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ve.setDeleted(e)}},Ge=e=>{isSystemDoc(e)||isConfigDoc(e)||Ve.delete(e)};try{se=createContentFilter({projectDir:s,contentDir:t,onAfterRebuild:()=>{ce.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{ue.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=Ft?.pruneFileIndexNowExcluded()??0;e>0&&getLogger(`server-factory`).info({pruned:e},`[content-filter] pruned now-excluded entries from fileIndex`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] fileIndex prune failed after onAfterRebuild`)}}}),ce=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:se}),ue=new TagIndex({contentDir:t,contentFilter:se});try{ue.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}de={current:F},fe=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:de,contentRoot:L,backlinkIndex:ce,configHomedirOverride:k,getCurrentBranch:()=>It?.getLastKnownBranch()??null,resolveEmbed:ae,resolveSize:oe,getPrincipal:()=>Ce,onAgentCommit:()=>_e?.signal(`session-activity`),onDiskFlush:(e,t)=>_e?.emitDiskAck(e,t),onConfigRejected:(e,t)=>_e?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),me=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[fe.extension]});let B=me.shouldUnloadDocument.bind(me);me.shouldUnloadDocument=e=>{if((Te||we.has(e))&&B(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},De=async e=>{we.add(e);try{await me.unloadDocument(e)}finally{we.delete(e)}},_e=new CC1Broadcaster(me),ve=new AgentFocusBroadcaster(me),ye=new AgentPresenceBroadcaster(me),ge=new AgentSessionManager(me);let q=createLiveDerivedIndexExtension({backlinkIndex:ce,tagIndex:ue,signalChannel:Ie});me.configuration.extensions.push(q),me.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,s=parseHocuspocusAuthToken(t),g=s?.expectedServerInstanceId;if(typeof g==`string`&&g.length>0&&g!==ee)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ee}`);let S=s?.expectedBranch,w=getActiveBranch();if(typeof S==`string`&&S.length>0&&S!==w)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${S}, server is on ${w}`);if(!s)return;let E=e.context;typeof s.principalId==`string`&&(Ce&&s.principalId===Ce.id?E.principalId=Ce.id:Ce?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Ce.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),me.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,s=t.socket?.remoteAddress;if(s!==void 0&&!isLoopbackAddress(s))throw Error(`config-doc admission requires loopback peer (peer=${s}, doc=${e.documentName})`);let g=e.requestHeaders,S=(g&&typeof g.get==`function`?g.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(S))throw Error(`config-doc admission requires loopback Host header (host=${S??`<absent>`}, doc=${e.documentName})`)}});let J=resolve(t);function Y(e){if(!isSafeDocName(e))return null;let t=resolve(J,`${e}${getDocExtension(e)}`);return!t.startsWith(`${J}/`)&&t!==J?null:t}me.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Ve,resolveFilePath:Y,fileExists:existsSync})}}),me.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let te=createApiExtension({hocuspocus:me,sessionManager:ge,contentDir:t,contentFilter:se,serverInstanceId:ee,getFileIndex:()=>Ft?Ft.getFileIndex():new Map,getFolderIndex:()=>Ft?Ft.getFolderIndex():new Map,getAliasMap:()=>Ft?Ft.getAliasMap():new Map,enableTestRoutes:j,shadowRef:de,flushGitCommit:()=>fe.flushPendingGitCommit(),flushContributors:()=>fe.flushContributors(),getCurrentBranch:()=>It?.getLastKnownBranch()??null,getDiskAckSVs:()=>_e?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:ce,tagIndex:ue,signalChannel:Ie,agentFocusBroadcaster:ve,agentPresenceBroadcaster:ye,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Lt,localOpCliArgs:H,projectDir:s,resolveEmbed:ae,getPrincipal:()=>Ce,forceUnloadDocument:De,ready:Pe,recentlyRemovedDocs:Ve});me.configuration.extensions.push(te),me.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:de,contentRoot:L,getCurrentBranch:()=>It?.getLastKnownBranch()??null,resolveEmbed:ae,resolveSize:oe}))}catch(e){throw releaseServerLock(te),e}let Ke=null,Xe=new Map,$e=[];function nt(e,t){let s=resolve(e,`rescue`),g=resolve(s,`${t}${getDocExtension(t)}`);return g.startsWith(`${s}/`)?g:null}function rt(e){let t=me.documents.get(e);if(!t)return null;let{frontmatter:s,body:g}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(s,g)}let it=(e,t)=>applyExternalChange(me,e,t,ae,oe),at=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of me.documents){if(isSystemDoc(s)||isConfigDoc(s))continue;let g=me.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,ae,s)},FILE_WATCHER_ORIGIN)}catch(t){J.error({err:t,docName:s,assetBasename:e},`[asset-event] failed to re-render ${s} for asset basename ${e}`)}}},st=null,vt=e=>{e&&(st===null&&(st=new Set,setImmediate(()=>{let e=st;if(st=null,e)try{for(let t of e)at(t)}catch(t){J.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),st.add(e))};function Tt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Et(e){try{switch(e.kind){case`create`:J.info({docName:e.docName},`[reconcile] create: ${e.docName}`),ce.updateDocumentFromMarkdown(e.docName,e.content),Be(),ue.updateDocumentFromMarkdown(e.docName,e.content),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),Ge(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=me.documents.get(t);if(!g){ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`);return}let S=getReconciledBase(t)??``,w=rt(t)??S,E=reconcile({docName:t,base:S,ours:w,theirs:s}),D=contentHash(S).slice(0,6),O=contentHash(w).slice(0,6),k=contentHash(s).slice(0,6);switch(J.info({docName:t,base:D,ours:O,theirs:k,result:E.kind},`[reconcile] ${t} base=${D} ours=${O} theirs=${k} result=${E.kind}`),E.kind){case`noop`:ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`);break;case`clean`:try{it(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`merged`:try{it(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`conflicts`:try{it(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),ce.updateDocumentFromMarkdown(t,s),Be(),ue.updateDocumentFromMarkdown(t,s),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}catch(e){J.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,s)}break;case`refused`:{incrementConflict();let e=g.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,E.reason);break}}break}case`delete`:{let{docName:t}=e,s=me.documents.get(t);if(!s){ce.deleteDocument(t),Be(),ue.deleteDocument(t),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),We(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=rt(t)??``,w=S!==g;if(w&&de.current){let e=de.current,s=It?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,L??``,{kind:`external-change-rescue`,docName:t,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:s,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{J.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),ce.deleteDocument(t),Be(),ue.deleteDocument(t),J.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),me.closeConnections(t),await De(s),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),We(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:s,content:g}=e,S=me.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),ce.renameDocument(t,s,g),Be(),ue.renameDocument(t,s,g),S){let e=S.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,s)}J.info({oldDocName:t,newDocName:s},`[reconcile] rename: ${t} → ${s}`),Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`),Ue(t,s),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:s,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,s=me.documents.get(t);if(!s)return;let g=s.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),J.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ne.add(e.relativePath),Ie(`files`),vt(basename(e.relativePath));break;case`asset-delete`:ne.remove(e.relativePath),Ie(`files`),vt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:Ie(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Tt(e);J.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let Dt=[];async function jt(e){if(isBatchInProgress()){Dt.push(e);return}await Et(e)}async function Mt(){let e=Dt.splice(0,Dt.length);for(let t of e)await Et(t)}let Ft=null,It=null,Lt=null,Rt=null;async function zt(e){if(me.documents.size===0)return;let t=!1,s=new Promise(e=>{me.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(me.documents.keys());me.closeConnections(),me.flushPendingStores();for(let e of me.documents.values())e.getConnectionsCount()===0&&me.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let S,w=new Promise((s,w)=>{S=setTimeout(()=>{t=!0;let s=Array.from(me.documents.keys()),S=[],E=[];if(de.current){for(let e of s)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=rt(e);if(t===null){J.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=nt(de.current.gitDir,e);if(!s){J.warn({docName:e,gitDir:de.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),E.push(e);continue}mkdirSync(dirname(s),{recursive:!0}),writeFileSync(s,t,`utf-8`),incrementRescueBuffer(),S.push(e),J.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){E.push(e),J.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else J.warn({stillLoadedCount:s.length},`[rescue] shadow repo unavailable at flush timeout — ${s.length} doc(s) will be lost: [${s.join(`, `)}]`),E.push(...s);let D=S.length>0||E.length>0?` — rescued [${S.join(`, `)}]${E.length>0?`, lost [${E.join(`, `)}]`:``}`:``;w(Error(`flushAllStoresAndWait timeout after ${e}ms — ${s.length}/${g.length} docs did not unload: [${s.join(`, `)}]${D}`))},e)});try{await Promise.race([s,w])}finally{S!==void 0&&clearTimeout(S)}}async function Bt(){return Rt||(Rt=(async()=>{let e=Date.now(),t=[];Te=!0,ze!==null&&(clearTimeout(ze),ze=null);let g,S=await Promise.race([Pe.then(()=>`completed`,e=>(J.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{g=setTimeout(()=>e(`timeout`),5e3)})]);g!==void 0&&clearTimeout(g),S===`timeout`&&J.warn({},`[server] init did not complete within 5s during shutdown`);let w=me.documents.size;try{try{try{It&&=(await It.unsubscribe(),null),Ft&&=(await Ft.unsubscribe(),null);for(let{docName:e,cleanup:t}of $e)try{await t()}catch(t){J.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}$e.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{_e?.destroy(),ye?.destroy(),Ke&&=(await Ke.disconnect(),null);for(let[e,t]of Xe)try{await t.disconnect()}catch(t){J.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Xe.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ge.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await zt(B)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await fe.flushPendingGitCommit(),await fe.waitForPendingCommits()})(),new Promise((t,s)=>{e=setTimeout(()=>s(Error(`L2 git flush timeout`)),B)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Lt&&=(await Lt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(de.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(de.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(de.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let g=Date.now()-e;t.length===0?J.info({documentCount:w,durationMs:g},`[server] shutdown flushed ${w} documents in ${g}ms`):J.warn({documentCount:w,durationMs:g,phaseErrors:t},`[server] shutdown flushed ${w} documents in ${g}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(te)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),J.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Rt)}let Vt=[];async function Ht(){try{Ce=await loadPrincipal(s),J.info({principalId:Ce.id},`[server] principal loaded`)}catch(e){J.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!de.current)try{de.current=await initShadowRepo(s),J.info({gitDir:de.current.gitDir},`[server] history repo initialized at ${de.current.gitDir}`)}catch(e){J.error({err:e},`[server] history repo init failed`),Vt.push(`shadow-repo`)}if(de.current){let e=null;try{e=loadRenameLogIndex(de.current.gitDir),sweepLazyPopOrphans(de.current.gitDir,e),setRenameLogIndex(de.current.gitDir,e),J.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){J.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(de.current,e,{rebuild:!0}),new Promise((e,s)=>setTimeout(()=>s(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){J.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(de.current)try{await shadowGit(de.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){J.warn({},`[server] history repo appears corrupted — reinitializing`);try{de.current=await initShadowRepo(s)}catch(e){J.error({err:e},`[server] history repo reinit failed`),de.current=void 0,Vt.includes(`shadow-repo`)||Vt.push(`shadow-repo`)}}else J.error({err:e},`[server] history repo check failed (transient?)`)}if(de.current)try{let e=resolve(de.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let g=null;try{g=(await esm_default({baseDir:s,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(g!==null){if(g!==t){let e=`main`;try{let t=(await esm_default({baseDir:s,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}J.info({lastKnownHead:t,currentHead:g,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=import`);try{await commitUpstreamImport(de.current,L??``,t,g,e),incrementUpstreamImport()}catch(e){J.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else J.info({currentHead:g},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${g}, action=noop`);try{writeFileSync(e,g,`utf-8`)}catch(e){J.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){J.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,s);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,s=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;J.warn({journalVersion:e.journal.version,fromPath:t,toPath:s,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${s}`)}}catch(e){J.error({err:e},`[server] managed rename recovery failed`),Vt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(s);(e.deleted>0||e.errors>0)&&J.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){J.error({err:e},`[server] upload-tempfile sweep failed`),Vt.push(`upload-tempfile-sweep`)}try{Ke=await me.openDirectConnection(SYSTEM_DOC_NAME),_e?.emitServerInfo(ee,getActiveBranch())}catch(e){J.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Vt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await me.openDirectConnection(e);Xe.set(e,t)}catch(t){J.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Vt.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,s)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,s)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,s,k)]]);for(let t of CONFIG_DOC_NAMES){let s=e.get(t);if(s)try{J.info({docName:t,path:s},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(s,e=>{let s=me.documents.get(t);J.info({docName:t,hasDocument:s!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let g=applyExternalConfigChange(s??null,t,e,fe.configPersistenceCtx);if(J.info({docName:t,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=Y();Lt?.setEnabled(e).catch(t=>{J.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});$e.push({docName:t,cleanup:e}),J.info({docName:t,path:s},`[config-file-watcher] started`)}catch(e){J.warn({err:e,docName:t,path:s},`[config-file-watcher] failed to start for ${t}`),Vt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),g=resolve(s,`.gitignore`),S=J;S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let w=await startMultiPathConfigFileWatcher([e,g],(t,g)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(me.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,fe.configPersistenceCtx);S.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){S.error({err:e,changedPath:relative(s,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let w=await se.rebuildIgnorePatterns();if(w.ok)S.info({changedPath:relative(s,t),patternCount:w.patternCount,nestedFileCount:w.nestedFileCount,durationMs:w.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),_e?.signal(`files`);else{let e=relative(s,t)||`.`;S.warn({changedPath:e,error:w.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),_e?.emitConfigIgnoreNestedError(e,w.error.message)}})().catch(e=>{S.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});$e.push({docName:`__ignore-files__`,cleanup:w}),S.info({okignorePath:e,gitignorePath:g},`[ignore-watcher] multi-path watcher started`)}catch(e){J.warn({err:e,projectDir:s,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Vt.push(`ignore-files-watcher`)}let g=resolveGitDir(s),S=g?readBranchFromHead(g)??`main`:`main`;switchReconciledBaseScope(S),ce.switchBranch(S);try{{let e=getActiveBranch();try{if(await ce.loadFromDisk(e)){let t=await ce.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&J.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await ce.rebuildFromDisk(e);ce.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){J.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Ft=await startWatcher(t,jt,se),ue.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:se,basenameIndex:ne,onSkip:(t,s,g)=>{e++,J.warn({reason:t,code:s,path:g},`[basename-index] skipped entry during seed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Vt.push(`basename-index-partial`))}catch(e){J.error({err:e},`[basename-index] startup seed failed`),Vt.push(`basename-index`)}}catch(e){J.error({err:e},`[server] disk bridge watcher failed to start`),Vt.push(`file-watcher`)}try{It=await startHeadWatcher(s,async({trigger:e})=>{if(J.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),me.flushPendingStores(),await fe.flushPendingGitCommit(),setBatchInProgress(!0),de.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of me.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let s=null;if(t.transact(()=>{s=rt(e)},PARK_SNAPSHOT_ORIGIN),s===null)continue;let g=getReconciledBase(e)??s;S.push({docName:e,markdown:s,diskSnapshot:g})}if(S.length>0)try{let t=await parkBranch(de.current,e,SERVICE_WRITER.id,S,g);t&&(incrementPark(),J.info({count:S.length,branch:e,sha:t.slice(0,8)},`[history] parked ${S.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){J.error({err:e},`[shadow] park failed`)}}},async e=>{let s=Dt.length,g=e.newBranch??`main`;if(J.info({kind:e.batchKind,headMoved:e.headMoved,docs:s,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${s}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)setBatchInProgress(!1),await Mt(),await fe.flushDeferredStores(`within-branch`);else{incrementBranchSwitch(),Dt.splice(0,Dt.length),switchReconciledBaseScope(g),ze!==null&&(clearTimeout(ze),ze=null),ce.switchBranch(g),se.rebuildDirCount();try{let e=0;ne.clear(),seedBasenameIndex({contentDir:t,contentFilter:se,basenameIndex:ne,onSkip:(t,s,S)=>{e++,J.warn({reason:t,code:s,path:S,branch:g},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(J.warn({count:e,branch:g},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Vt.includes(`basename-index-partial`)||Vt.push(`basename-index-partial`))}catch(e){J.error({err:e,branch:g},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of me.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let S=safeContentPath(e,t);if(!existsSync(S)){let t=getReconciledBase(e)??``,S=rt(e)??``;if(S!==t&&de.current){let t=de.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:S,label:`External change recovered @ ${new Date().toISOString()}`,branch:g,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),J.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{J.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}s.getMap(`lifecycle`).set(`status`,`deleted-upstream`),J.info({docName:e,branch:g},`[branch-switch] tombstone: ${e} (not on ${g})`);continue}let w=readFileSync(S,`utf-8`);it(e,w),setReconciledBase(e,w),J.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){J.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}J.info({branch:g,docCount:me.documents.size},`[branch-switch] loaded branch ${g} (${me.documents.size} docs)`);try{if(await ce.loadFromDisk(g)){let e=await ce.reconcileWithDisk(g);(e.added>0||e.updated>0||e.deleted>0)&&J.info(e,`[backlinks] branch-switch reconcile for ${g}`)}else await ce.rebuildFromDisk(g);ce.saveToDisk(g).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${g}:`,e)})}catch(e){J.error({err:e,branch:g},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(ue.init(),de.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of me.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let s=await readParkedState(de.current,g,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let S=getReconciledBase(t);if(!S)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:S});switch(w.kind){case`merged`:case`clean`:it(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:it(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;break;case`noop`:case`refused`:break}}catch(e){J.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&J.info({count:e,branch:g},`[branch-switch] restored ${e} parked docs on ${g}`)}if(e.oldBranch?.startsWith(`detached-`)&&de.current)try{let t=shadowGit(de.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
2367
2583
|
`))e&&await t.raw(`update-ref`,`-d`,e);J.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){J.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await fe.flushDeferredStores(`discard-stale`),_e?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&de.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(de.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),J.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){J.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){J.error({err:e},`[server] HEAD watcher failed to start`),Vt.push(`head-watcher`)}let w=H?.[0]??`open-knowledge`,E=[`-c`,`credential.helper=!${H&&H.length>1?H.join(` `):w} auth git-credential`];try{Lt=new SyncEngine({projectDir:s,contentDir:t,contentFilter:se,contentRoot:L,syncEnabled:Y(),credentialArgs:E,cc1Broadcaster:_e,setBatchInProgress:e=>{setBatchInProgress(e),e||fe.flushDeferredStores(`within-branch`).catch(e=>{J.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{J.info({state:e},`[sync] state → ${e}`)},onAutoDisable:async e=>{J.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||J.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Lt.start()}catch(e){J.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Lt=null}Ie(`files`),Ie(`backlinks`),Ie(`graph`),Ie(`tags`)}return Ht().then(je,Me),{hocuspocus:me,sessionManager:ge,cc1Broadcaster:_e,agentFocusBroadcaster:ve,agentPresenceBroadcaster:ye,contentFilter:se,basenameIndex:ne,serverInstanceId:ee,destroy:Bt,ready:Pe,degraded:Vt,lockDir:te,get syncEngine(){return Lt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){initTelemetry();let{kind:t,gitdir:s}=computeWorktreeAttributes(e.projectDir??e.contentDir),g={"ok.worktree.kind":t};return s!==null&&(g[`ok.worktree.gitdir`]=normalizeFsPath(s)),withSpan(`ok.boot`,{attributes:g},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-D7DXNVql-B5nINglj.mjs`).then(e=>e.a),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=findLegacyRuntimeFiles(F);L.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${L.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let B=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:H,destroy:q,ready:J,degraded:Y,lockDir:ee,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:ae}=B,oe=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),se=e.port??0,ce=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${oe}:${se}`,log:S}),ue=D();ue.headersTimeout=3e4,ue.requestTimeout=6e4;let de=e.serveContentAssets?createAssetServeMiddleware({contentFilter:B.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,fe=mountMcpAndApi({httpServer:ue,hocuspocus:H,mcpHttpHandler:ce,log:S,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:ae,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:de}),me=null;g!==null&&(me=attachIdleShutdown({httpServer:ue,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await q()})})),await new Promise((t,s)=>{let g=e=>s(e);ue.once(`error`,g),ue.listen(e.port,e.host,()=>{ue.removeListener(`error`,g),t()})});let ge=ue.address(),_e=typeof ge==`object`&&ge?ge.port:e.port??0;if(se=_e,O(ee,_e),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ee,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let ve=!1,ye=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return{httpServer:ue,destroy:async()=>{if(ve)return;ve=!0;let e=[],t=async(t,s)=>{try{await ye(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{me?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>fe.shutdown()),await t(`mcpHttpHandler.close`,()=>ce.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{fe.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ue.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ue.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>q()),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},lockDir:ee,contentDir:e.contentDir,port:_e,ready:J,degraded:Y,didAutoInit:k,serverInstance:B}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const ANCESTOR_WALK_DEPTH_LIMIT$1=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT$1;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const ANCESTOR_WALK_DEPTH_LIMIT=30,OK_CONFIG_MARKER=`.ok/config.yml`;function findEnclosingProjectRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,OK_CONFIG_MARKER))}catch{e=!1}if(e)return{rootPath:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),S=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let w=``;try{w=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,w);return S?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}export{applySeed as $,runAuthReposSubprocess as $n,incrementCollabSocketFilteredError as $t,MissingOkConfigError as A,readServerPackageVersion as An,updateUiLockPort as Ar,createServer$1 as At,STARTER_FOLDER_FRONTMATTER_FILENAME as B,registerWrite as Bn,McpServer as Br,findEnclosingGitRoot as Bt,LOG_MD_TEMPLATE as C,parseHocuspocusAuthToken as Cn,tracedRenameSync as Cr,createContentFilter as Ct,MCP_SERVER_NAME as D,planSeed as Dn,tracedWriteFile as Dr,createMcpHttpHandler as Dt,MCP_CONNECTION_ID_HEADER as E,planPersonalTemplates as En,tracedUnlinkSync as Er,createLiveDerivedIndexExtension as Et,ProjectGitInitError as F,readUiLock as Fn,withSpanSync as Fr,detectProjectShape as Ft,SeedPrerequisiteError as G,resolveContentDir as Gn,isJSONRPCResultResponse as Gr,getCurrentMcpLogger as Gt,STARTER_PACK_IDS as H,removeLastKnownHash as Hn,LATEST_PROTOCOL_VERSION as Hr,formatAuthRejectionWire as Ht,ROLLBACK_ORIGIN as I,reconcile as In,writePersonalTemplates as Ir,ensureProjectGit as It,TagIndex as J,resolveLockDir as Jn,writeConfigPatch as Jr,getMeter as Jt,SeedRootDirError as K,resolveCursorBinaryDefault as Kn,readConfigSafely as Kr,getLocalDir as Kt,SERVICE_WRITER as L,recordContributor as Ln,writeStateManifest as Lr,errorResponse as Lt,PERSONAL_TEMPLATES as M,readStateManifest as Mn,validateCloneInputs as Mr,createStreamingErrorWriter as Mt,PERSONAL_TEMPLATE_NAMES as N,readTargetRecordedAt as Nn,validateSkillZip as Nr,createTestLogger as Nt,MISSING_OK_CONFIG_MESSAGE as O,readAllTargets as On,tracedWriteFileSync as Or,createOsProbe as Ot,PinoLogger as P,readTargetVersion as Pn,withSpan as Pr,detectClaudeDesktopPresence as Pt,applyExternalChange as Q,rewriteWikiLinksForDocumentRename as Qn,handleSpawnCursor as Qt,SKILL_INSTALL_EVENTS_FILE_REL as R,recordSkillInstallEvent as Rn,writeTargetVersion as Rr,evictStaleTrackerEntries as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,parseAuthRejectionWire as Sn,tracedRename as Sr,createAssetServeMiddleware as St,MAX_AGENT_SESSIONS as T,pathToDocName as Tn,tracedRmdirSync as Tr,createExternalChangeHandler as Tt,STARTER_TEMPLATES as U,resetMetrics as Un,isInitializedNotification as Ur,formatContributors as Ut,STARTER_PACKS as V,releaseUiLock as Vn,JSONRPCMessageSchema as Vr,findEnclosingProjectRoot as Vt,STATE_MANIFEST_FILENAME as W,resolveBundledSkillDir as Wn,isJSONRPCRequest as Wr,gcCheckpointRefs as Wt,acquireUiLock as X,resolvePackageVersion as Xn,MalformedGitPointerError as Xr,getTracer as Xt,UiLockCollisionError as Y,resolvePack as Yn,GitDirAccessError as Yr,getMetrics as Yt,applyAgentMarkdownWrite as Z,rewriteMarkdownLinksForDocumentRename as Zn,handleCollabSocketError as Zt,GIT_UPSTREAM_WRITER as _,listStarterPacks as _n,toBroadcasterKey as _r,commitWipFromTree as _t,AgentPresenceBroadcaster as a,isAllowedApiOrigin as an,safeSubdir as ar,buildExecResult as at,HocuspocusAuthTokenSchema as b,mountMcpAndApi as bn,tracedMkdir as br,contributorCount as bt,BacklinkIndex as c,isHocuspocusAuthRejectionReason as cn,saveInMemoryCheckpoint as cr,buildSkillZip as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,isPairedWriteOrigin as dn,setActiveSpanAttributes as dr,classifyEvents as dt,incrementServerObserverFire as en,runAuthStatusSubprocess as er,assertCompatibleStateManifest as et,ConfigSchema as f,isPathWithinDir as fn,shadowGit as fr,classifyFsPath as ft,FILE_WATCHER_ORIGIN as g,listRescueCheckpoints as gn,streamingProblemEvent as gr,commitWip as gt,FILE_SYSTEM_WRITER as h,lastKnownHash as hn,startWatcher as hr,commitUpstreamImport as ht,AgentFocusBroadcaster as i,installUserSkill as in,safeContentPath as ir,buildAndOpenSkill as it,OBSERVER_SYNC_ORIGIN as j,readSkillInstallStateSnapshot as jn,validateAgentId as jr,createServerObserverExtension as jt,McpLogger as k,readBranchFromHead as kn,updateLastKnownHash as kr,createPersistenceExtension as kt,CC1Broadcaster as l,isKnownPackId as ln,saveVersion as lr,buildStarterFolderFrontmatterYaml as lt,DEFAULT_PACK_ID as m,isSystemDoc as mn,splitMarkdownBlocks as mr,coercePackId as mt,AGENT_ID_RE as n,initTelemetry as nn,runDeviceFlowSubprocess as nr,attachIdleShutdown as nt,AgentSessionCapacityError as o,isAllowedWorkspaceHostHeader as on,safetyCheckpoint as or,buildInstructions as ot,DEFAULT_CHECKPOINT_RETENTION as p,isSelfWrite as pn,shutdownTelemetry as pr,clearContributors as pt,StateManifestError as q,resolveCursorSpawnInvocation as qn,resolveConfigPath as qr,getLogger as qt,AGENT_WRITE_ORIGIN as r,installTestLoggers as rn,runWithMcpLogger as rr,bootServer as rt,AgentSessionManager as s,isConfigDoc as sn,sanitizeClientName as sr,buildReadResult as st,AGENT_ID_MAX_LEN as t,initShadowRepo as tn,runCloneSubprocess as tr,assertNeverDiskEvent as tt,CONFLICT_MARKER_RE as u,isLoopbackAddress as un,seedBasenameIndex as ur,buildWipTree as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,loadPrincipal as vn,tracedAppendFileSync as vr,containsConflictMarkers as vt,MANAGED_RENAME_ORIGIN as w,parseKeepaliveConnectionId as wn,tracedRmSync as wr,createContentFilterAsync as wt,INSTALLED_AGENTS_SCHEMES as x,normalizeFsPath as xn,tracedMkdirSync as xr,createApiExtension as xt,HocuspocusAuthRejection as y,loggerFactory as yn,tracedLinkSync as yr,contentHash as yt,STARTER_FOLDERS as z,registerAllTools as zn,writeTracker as zr,extractWikiLinksFromMarkdown as zt};
|
|
2368
|
-
//# sourceMappingURL=dist-
|
|
2584
|
+
//# sourceMappingURL=dist-BaVVyZsg.mjs.map
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e,d as t,f as n,i as r,l as i,m as a,p as o,t as s,u as c}from"./init-
|
|
1
|
+
import{c as e,d as t,f as n,i as r,l as i,m as a,p as o,t as s,u as c}from"./init-Mu6hjAn2.mjs";import{n as l}from"./loader-th8fUQ0l.mjs";import{n as u}from"./preview-Brj3agTC.mjs";import{t as d}from"./src-_bKfCVLS.mjs";export{c as ALL_EDITOR_IDS,t as EDITOR_LABELS,n as EDITOR_TARGETS,s as detectInstalledEditors,a as initContent,l as loadConfig,u as previewContent,r as readExistingMcpEntry,o as resolveProjectRoot,e as writeEditorMcpConfig,d as writeProjectAiIntegrations,i as writeUserMcpConfigs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as e}from"./init-Mu6hjAn2.mjs";export{e as runInit};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{J as a,ir as o,n as s,or as c}from"./dist-k62w-4-v.mjs";import{D as l,F as u,It as d,Pt as f,Wn as p,in as m}from"./dist-Bfw3oOGm.mjs";import{n as h,t as g}from"./constants-BVG2ymMz.mjs";import{t as _}from"./is-object-C-4FJ0rP.mjs";import{i as v,o as y,r as b,s as x,t as S}from"./colors-BtKMHmBX.mjs";import{t as ee}from"./preview-CuLb6srO.mjs";import{execFileSync as te}from"node:child_process";import ne,{basename as re,dirname as C,isAbsolute as ie,join as w,posix as ae,relative as T,resolve as E,sep as D,win32 as oe}from"node:path";import{cpSync as se,existsSync as O,lstatSync as ce,mkdirSync as k,readFileSync as A,realpathSync as le,rmSync as ue,writeFileSync as j}from"node:fs";import M from"node:process";import{homedir as N}from"node:os";import{AsyncLocalStorage as de,AsyncResource as fe}from"node:async_hooks";import{stripVTControlCharacters as pe,styleText as P}from"node:util";import*as me from"node:readline";function he(){return M.platform.startsWith(`win`)?!!M.env.CI||!!M.env.WT_SESSION||!!M.env.TERMINUS_SUBLIME||M.env.ConEmuTask===`{cmd::Cmder}`||M.env.TERM_PROGRAM===`Terminus-Sublime`||M.env.TERM_PROGRAM===`vscode`||M.env.TERM===`xterm-256color`||M.env.TERM===`alacritty`||M.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:M.env.TERM!==`linux`}const ge={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},_e={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},ve={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},ye={...ge,..._e},be={...ge,...ve},F=he()?ye:be;Object.entries(_e);var xe=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Se=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),Ce=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,we=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Te=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ee=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,De=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Oe=/\t{1,1000}/y,ke=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Ae=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,je=/\p{M}+/gu,Me={limit:1/0,ellipsis:``},Ne=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Ne(i,Me,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ae,l],[Te,0],[Ee,o],[Oe,s],[ke,c],[De,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(je,``)){let t=e.codePointAt(0)||0;if(S=Ce(t)?2:we(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===De?Se(e.slice(p,n.lastIndex)):n===ke?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Pe={limit:1/0,ellipsis:``,ellipsisWidth:0},I=(e,t={})=>Ne(e,Pe,t).width,Fe=`]8;;`,Ie=RegExp(`(?:\\[(?<code>\\d+)m|\\${Fe}(?<uri>.*))`,`y`),Le=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Re=e=>`[${e}m`,ze=e=>`${Fe}${e}`,Be=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:I(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=I(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(Fe,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ve=e=>{let t=e.split(` `),n=t.length;for(;n&&!I(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},He=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=I(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=I(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Be(s,r,t),c=I(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Be(s,r,t),c=I(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Be(s,r,t),c=I(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ve(e)));let l=s.join(`
|
|
1
|
+
import{i as e,o as t,t as n}from"./chunk-FK9Q3tQk.mjs";import{r,t as i}from"./esm-CEs3LWY3.mjs";import{J as a,ir as o,n as s,or as c}from"./dist-k62w-4-v.mjs";import{D as l,F as u,It as d,Pt as f,Wn as p,in as m}from"./dist-BaVVyZsg.mjs";import{n as h,t as g}from"./constants-BgI7SDCI.mjs";import{t as _}from"./is-object-C-4FJ0rP.mjs";import{i as v,o as y,r as b,s as x,t as S}from"./colors-BtKMHmBX.mjs";import{t as ee}from"./preview-Brj3agTC.mjs";import{execFileSync as te}from"node:child_process";import ne,{basename as re,dirname as C,isAbsolute as ie,join as w,posix as ae,relative as T,resolve as E,sep as D,win32 as oe}from"node:path";import{cpSync as se,existsSync as O,lstatSync as ce,mkdirSync as k,readFileSync as A,realpathSync as le,rmSync as ue,writeFileSync as j}from"node:fs";import M from"node:process";import{homedir as N}from"node:os";import{AsyncLocalStorage as de,AsyncResource as fe}from"node:async_hooks";import{stripVTControlCharacters as pe,styleText as P}from"node:util";import*as me from"node:readline";function he(){return M.platform.startsWith(`win`)?!!M.env.CI||!!M.env.WT_SESSION||!!M.env.TERMINUS_SUBLIME||M.env.ConEmuTask===`{cmd::Cmder}`||M.env.TERM_PROGRAM===`Terminus-Sublime`||M.env.TERM_PROGRAM===`vscode`||M.env.TERM===`xterm-256color`||M.env.TERM===`alacritty`||M.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:M.env.TERM!==`linux`}const ge={circleQuestionMark:`(?)`,questionMarkPrefix:`(?)`,square:`█`,squareDarkShade:`▓`,squareMediumShade:`▒`,squareLightShade:`░`,squareTop:`▀`,squareBottom:`▄`,squareLeft:`▌`,squareRight:`▐`,squareCenter:`■`,bullet:`●`,dot:`․`,ellipsis:`…`,pointerSmall:`›`,triangleUp:`▲`,triangleUpSmall:`▴`,triangleDown:`▼`,triangleDownSmall:`▾`,triangleLeftSmall:`◂`,triangleRightSmall:`▸`,home:`⌂`,heart:`♥`,musicNote:`♪`,musicNoteBeamed:`♫`,arrowUp:`↑`,arrowDown:`↓`,arrowLeft:`←`,arrowRight:`→`,arrowLeftRight:`↔`,arrowUpDown:`↕`,almostEqual:`≈`,notEqual:`≠`,lessOrEqual:`≤`,greaterOrEqual:`≥`,identical:`≡`,infinity:`∞`,subscriptZero:`₀`,subscriptOne:`₁`,subscriptTwo:`₂`,subscriptThree:`₃`,subscriptFour:`₄`,subscriptFive:`₅`,subscriptSix:`₆`,subscriptSeven:`₇`,subscriptEight:`₈`,subscriptNine:`₉`,oneHalf:`½`,oneThird:`⅓`,oneQuarter:`¼`,oneFifth:`⅕`,oneSixth:`⅙`,oneEighth:`⅛`,twoThirds:`⅔`,twoFifths:`⅖`,threeQuarters:`¾`,threeFifths:`⅗`,threeEighths:`⅜`,fourFifths:`⅘`,fiveSixths:`⅚`,fiveEighths:`⅝`,sevenEighths:`⅞`,line:`─`,lineBold:`━`,lineDouble:`═`,lineDashed0:`┄`,lineDashed1:`┅`,lineDashed2:`┈`,lineDashed3:`┉`,lineDashed4:`╌`,lineDashed5:`╍`,lineDashed6:`╴`,lineDashed7:`╶`,lineDashed8:`╸`,lineDashed9:`╺`,lineDashed10:`╼`,lineDashed11:`╾`,lineDashed12:`−`,lineDashed13:`–`,lineDashed14:`‐`,lineDashed15:`⁃`,lineVertical:`│`,lineVerticalBold:`┃`,lineVerticalDouble:`║`,lineVerticalDashed0:`┆`,lineVerticalDashed1:`┇`,lineVerticalDashed2:`┊`,lineVerticalDashed3:`┋`,lineVerticalDashed4:`╎`,lineVerticalDashed5:`╏`,lineVerticalDashed6:`╵`,lineVerticalDashed7:`╷`,lineVerticalDashed8:`╹`,lineVerticalDashed9:`╻`,lineVerticalDashed10:`╽`,lineVerticalDashed11:`╿`,lineDownLeft:`┐`,lineDownLeftArc:`╮`,lineDownBoldLeftBold:`┓`,lineDownBoldLeft:`┒`,lineDownLeftBold:`┑`,lineDownDoubleLeftDouble:`╗`,lineDownDoubleLeft:`╖`,lineDownLeftDouble:`╕`,lineDownRight:`┌`,lineDownRightArc:`╭`,lineDownBoldRightBold:`┏`,lineDownBoldRight:`┎`,lineDownRightBold:`┍`,lineDownDoubleRightDouble:`╔`,lineDownDoubleRight:`╓`,lineDownRightDouble:`╒`,lineUpLeft:`┘`,lineUpLeftArc:`╯`,lineUpBoldLeftBold:`┛`,lineUpBoldLeft:`┚`,lineUpLeftBold:`┙`,lineUpDoubleLeftDouble:`╝`,lineUpDoubleLeft:`╜`,lineUpLeftDouble:`╛`,lineUpRight:`└`,lineUpRightArc:`╰`,lineUpBoldRightBold:`┗`,lineUpBoldRight:`┖`,lineUpRightBold:`┕`,lineUpDoubleRightDouble:`╚`,lineUpDoubleRight:`╙`,lineUpRightDouble:`╘`,lineUpDownLeft:`┤`,lineUpBoldDownBoldLeftBold:`┫`,lineUpBoldDownBoldLeft:`┨`,lineUpDownLeftBold:`┥`,lineUpBoldDownLeftBold:`┩`,lineUpDownBoldLeftBold:`┪`,lineUpDownBoldLeft:`┧`,lineUpBoldDownLeft:`┦`,lineUpDoubleDownDoubleLeftDouble:`╣`,lineUpDoubleDownDoubleLeft:`╢`,lineUpDownLeftDouble:`╡`,lineUpDownRight:`├`,lineUpBoldDownBoldRightBold:`┣`,lineUpBoldDownBoldRight:`┠`,lineUpDownRightBold:`┝`,lineUpBoldDownRightBold:`┡`,lineUpDownBoldRightBold:`┢`,lineUpDownBoldRight:`┟`,lineUpBoldDownRight:`┞`,lineUpDoubleDownDoubleRightDouble:`╠`,lineUpDoubleDownDoubleRight:`╟`,lineUpDownRightDouble:`╞`,lineDownLeftRight:`┬`,lineDownBoldLeftBoldRightBold:`┳`,lineDownLeftBoldRightBold:`┯`,lineDownBoldLeftRight:`┰`,lineDownBoldLeftBoldRight:`┱`,lineDownBoldLeftRightBold:`┲`,lineDownLeftRightBold:`┮`,lineDownLeftBoldRight:`┭`,lineDownDoubleLeftDoubleRightDouble:`╦`,lineDownDoubleLeftRight:`╥`,lineDownLeftDoubleRightDouble:`╤`,lineUpLeftRight:`┴`,lineUpBoldLeftBoldRightBold:`┻`,lineUpLeftBoldRightBold:`┷`,lineUpBoldLeftRight:`┸`,lineUpBoldLeftBoldRight:`┹`,lineUpBoldLeftRightBold:`┺`,lineUpLeftRightBold:`┶`,lineUpLeftBoldRight:`┵`,lineUpDoubleLeftDoubleRightDouble:`╩`,lineUpDoubleLeftRight:`╨`,lineUpLeftDoubleRightDouble:`╧`,lineUpDownLeftRight:`┼`,lineUpBoldDownBoldLeftBoldRightBold:`╋`,lineUpDownBoldLeftBoldRightBold:`╈`,lineUpBoldDownLeftBoldRightBold:`╇`,lineUpBoldDownBoldLeftRightBold:`╊`,lineUpBoldDownBoldLeftBoldRight:`╉`,lineUpBoldDownLeftRight:`╀`,lineUpDownBoldLeftRight:`╁`,lineUpDownLeftBoldRight:`┽`,lineUpDownLeftRightBold:`┾`,lineUpBoldDownBoldLeftRight:`╂`,lineUpDownLeftBoldRightBold:`┿`,lineUpBoldDownLeftBoldRight:`╃`,lineUpBoldDownLeftRightBold:`╄`,lineUpDownBoldLeftBoldRight:`╅`,lineUpDownBoldLeftRightBold:`╆`,lineUpDoubleDownDoubleLeftDoubleRightDouble:`╬`,lineUpDoubleDownDoubleLeftRight:`╫`,lineUpDownLeftDoubleRightDouble:`╪`,lineCross:`╳`,lineBackslash:`╲`,lineSlash:`╱`},_e={tick:`✔`,info:`ℹ`,warning:`⚠`,cross:`✘`,squareSmall:`◻`,squareSmallFilled:`◼`,circle:`◯`,circleFilled:`◉`,circleDotted:`◌`,circleDouble:`◎`,circleCircle:`ⓞ`,circleCross:`ⓧ`,circlePipe:`Ⓘ`,radioOn:`◉`,radioOff:`◯`,checkboxOn:`☒`,checkboxOff:`☐`,checkboxCircleOn:`ⓧ`,checkboxCircleOff:`Ⓘ`,pointer:`❯`,triangleUpOutline:`△`,triangleLeft:`◀`,triangleRight:`▶`,lozenge:`◆`,lozengeOutline:`◇`,hamburger:`☰`,smiley:`㋡`,mustache:`෴`,star:`★`,play:`▶`,nodejs:`⬢`,oneSeventh:`⅐`,oneNinth:`⅑`,oneTenth:`⅒`},ve={tick:`√`,info:`i`,warning:`‼`,cross:`×`,squareSmall:`□`,squareSmallFilled:`■`,circle:`( )`,circleFilled:`(*)`,circleDotted:`( )`,circleDouble:`( )`,circleCircle:`(○)`,circleCross:`(×)`,circlePipe:`(│)`,radioOn:`(*)`,radioOff:`( )`,checkboxOn:`[×]`,checkboxOff:`[ ]`,checkboxCircleOn:`(×)`,checkboxCircleOff:`( )`,pointer:`>`,triangleUpOutline:`∆`,triangleLeft:`◄`,triangleRight:`►`,lozenge:`♦`,lozengeOutline:`◊`,hamburger:`≡`,smiley:`☺`,mustache:`┌─┐`,star:`✶`,play:`►`,nodejs:`♦`,oneSeventh:`1/7`,oneNinth:`1/9`,oneTenth:`1/10`},ye={...ge,..._e},be={...ge,...ve},F=he()?ye:be;Object.entries(_e);var xe=n(((t,n)=>{n.exports=i;function r(t){let n={defaultWidth:0,output:process.stdout,tty:e(`tty`)};return t?(Object.keys(n).forEach(function(e){t[e]||(t[e]=n[e])}),t):n}function i(e){let t=r(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&e!==0)return e}return t.defaultWidth}}));const Se=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),Ce=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,we=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,Te=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ee=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,De=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Oe=/\t{1,1000}/y,ke=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,Ae=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,je=/\p{M}+/gu,Me={limit:1/0,ellipsis:``},Ne=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Ne(i,Me,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[Ae,l],[Te,0],[Ee,o],[Oe,s],[ke,c],[De,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(je,``)){let t=e.codePointAt(0)||0;if(S=Ce(t)?2:we(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===De?Se(e.slice(p,n.lastIndex)):n===ke?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},Pe={limit:1/0,ellipsis:``,ellipsisWidth:0},I=(e,t={})=>Ne(e,Pe,t).width,Fe=`]8;;`,Ie=RegExp(`(?:\\[(?<code>\\d+)m|\\${Fe}(?<uri>.*))`,`y`),Le=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Re=e=>`[${e}m`,ze=e=>`${Fe}${e}`,Be=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:I(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=I(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(Fe,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},Ve=e=>{let t=e.split(` `),n=t.length;for(;n&&!I(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},He=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=I(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=I(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),Be(s,r,t),c=I(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Be(s,r,t),c=I(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Be(s,r,t),c=I(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ve(e)));let l=s.join(`
|
|
2
2
|
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){Ie.lastIndex=e+1;let t=Ie.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
|
|
3
3
|
`){a&&(r+=ze(``));let e=i?Le(i):void 0;i&&e&&(r+=Re(e))}else t===`
|
|
4
4
|
`&&(i&&Le(i)&&(r+=Re(i)),a&&(r+=ze(a)))}return r},Ue=/\r?\n/;function We(e,t,n){return String(e).normalize().split(Ue).map(e=>He(e,t,n)).join(`
|
|
@@ -404,5 +404,5 @@ last-spawn-error.log
|
|
|
404
404
|
`)?n:`${n}\n`,`utf-8`)}function ur(e,t){let n;try{n=le(t)}catch{n=E(t)}let r;try{r=ce(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run \`ok init\`, or pass \`--no-mcp\` to skip MCP config writes.`);let i=C(e);for(;i.length>1&&i!==D;){let t;try{t=le(i)}catch(e){if(e.code===`ENOENT`){i=C(i);continue}throw e}let r=T(n,t);if(r===``||!r.startsWith(`..`)&&!ie(r))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run, or pass \`--no-mcp\`.`)}}const dr=e=>e!==`project`,fr=e=>e!==`user`;async function pr(){let e=await rn({message:`Where should the MCP server be configured?
|
|
405
405
|
`,required:!1,theme:{icon:{checked:`[x]`,unchecked:`[ ]`}},choices:[{name:`User-level (~/.claude.json, ~/.cursor/mcp.json, …)`,value:`user`,checked:!0},{name:`Project-level (.mcp.json, .cursor/mcp.json, …)`,value:`project`,checked:!0}]});return e.includes(`user`)&&e.includes(`project`)?`both`:e.includes(`user`)?`user`:e.includes(`project`)?`project`:null}async function mr(e){return e.mcp===!1?null:e.scope?e.scope:e.isTTY??process.stdout.isTTY?(e.promptFn??pr)():`both`}const hr=`0.0.1`,gr=`open-knowledge-ui`;function _r(e,t={}){let n=w(e,`.claude`,`launch.json`),r=t.mode===`dev`?{name:gr,runtimeExecutable:`node`,runtimeArgs:[Yn(),`ui`],port:3e3}:{name:gr,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:3e3};try{if(ur(n,e),!O(n))return k(C(n),{recursive:!0}),j(n,`${JSON.stringify({version:hr,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=A(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!_(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let a=Array.isArray(i.configurations)?i.configurations:[],o=a.findIndex(e=>_(e)&&e.name===gr);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??hr,configurations:a};return j(n,`${JSON.stringify(s,null,2)}\n`,`utf-8`),{action:o>=0?`merged`:`created`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function vr(e,t,n){try{return O(e.detectPath?.(t,n)??C(e.configPath(t,n)))}catch{return!1}}function $(e,t,n,r,i){let a=e.serverName(t),o;try{o=i??e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,serverName:a,error:t instanceof Error?t.message:String(t)}}if(!i&&!n.skipAvailabilityCheck&&!vr(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{ur(o,t)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t),configScope:`project`}}let s;try{s=e.format===`toml`?sr(o):or(o)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let c=s[e.topLevelKey]??{},l=c[a],u;try{u=e.buildEntry(t,n)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}let d={...s,[e.topLevelKey]:{...c,[a]:u}};try{e.format===`toml`?lr(o,d):cr(o,d)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:o,serverName:a,error:t instanceof Error?t.message:String(t)}}return{editorId:e.id,label:e.label,action:l===void 0?`written`:`overwritten`,configPath:o,serverName:a,...i===void 0?{}:{configScope:`project`}}}function yr(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=p(),i=C(n);ur(i,t);let a=O(n)?`overwritten`:`written`;return ue(i,{recursive:!0,force:!0}),k(C(i),{recursive:!0}),se(r,i,{recursive:!0}),{editorId:e.id,label:e.label,action:a,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}function br(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!O(n)))return{editorId:e.id,label:e.label,path:n}}async function xr(e){let t=ar(e.editors),n={mode:`published`,cliPath:e.cliPath,skipAvailabilityCheck:!0};return t.map(t=>$(t,``,n,e.home))}function Sr(e,t,n){let r;try{r=e.configPath(t,n)}catch{return null}let i;try{i=e.format===`toml`?sr(r):or(r)}catch{return null}let a=i[e.topLevelKey];if(!_(a))return null;let o=a[e.serverName(t)];return _(o)?o:null}async function Cr(e={}){let t=Kn(E(e.cwd??process.cwd()),{homeDir:e.home}),n=t.projectRoot,r=!O(w(n,`.ok`));t.ancestorPromoted?console.log(`[ok] Opened existing project at ${n}`):t.gitRootPromoted&&r&&console.log(`[ok] Initialized OK at ${n} (scoped to ${t.defaultContentDir}/)`);let i={mode:e.devMcp?`dev`:`published`},a=await d(n),o;try{o=Un(n,{contentDir:t.defaultContentDir})}catch(t){let r=Q.claude.configPath(n,e.home);return{projectRoot:n,contentCreated:[],contentUpdated:[],contentSkipped:[],editors:[],projectSkills:[],legacyProjectConfigs:[],didGitInit:a.didInit,claudeDesktopDetected:!1,mcpAction:`failed`,mcpPath:r,mcpError:`Content scaffolding failed: ${t instanceof Error?t.message:String(t)}`}}let s=await mr({scope:e.scope,mcp:e.mcp,isTTY:e.isTTY,promptFn:e.promptFn}),c=e.editors??Tr(n,e.home),l=e.editors??J.filter(e=>Q[e].projectConfigPath!==void 0),u=ar(c),p=ar(l),h=e.mcp===!1||s===null,g=Array.from(new Map([...u,...h?[]:p].map(e=>[e.id,e])).values()),_=u.filter(t=>vr(t,n,e.home)),v=[],y=[],b=new Set;for(let t of g){if(h){let r=``;try{r=t.configPath(n,e.home)}catch{}v.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:r,serverName:t.serverName(n)});continue}if(dr(s)&&u.includes(t)&&v.push($(t,n,i,e.home)),fr(s)&&p.includes(t)&&t.projectConfigPath){let r=t.projectConfigPath(n),a=$(t,n,i,e.home,r);v.push(a),(a.action===`written`||a.action===`overwritten`)&&(b.add(r),y.push(yr(t,n)))}}let x=!h&&s!==null&&fr(s)?p.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,S=h?[]:_.map(e=>br(e,n)).filter(e=>e!==void 0).filter(e=>!b.has(e.path)),ee=_.some(e=>e.id===`claude`)&&!h?_r(n,i):void 0,te=await(e.installUserSkill??m)({home:e.home}),ne=f({home:e.home}),re=h?`skipped-flag`:`skipped-missing`,C=v.find(e=>e.editorId===`claude`)??v[0]??{action:re,configPath:Q.claude.configPath(n,e.home)};return{projectRoot:n,contentCreated:o.created,contentUpdated:o.updated,contentSkipped:o.skipped,editors:v,projectSkills:y,legacyProjectConfigs:S,launchJson:ee,skillInstall:te,didGitInit:a.didInit,claudeDesktopDetected:ne,mcpAction:C.action,mcpPath:C.configPath,mcpError:`error`in C?C.error:void 0,projectScopeUnsupportedLabels:x}}function wr(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),s=e=>{let n=e.configPath.startsWith(t)?T(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`);let c=w(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(S(`Content scaffolded at ${c}/`)),e.contentCreated.length>0&&n.push(` Created: ${e.contentCreated.join(`, `)}`),e.contentUpdated.length>0&&n.push(` Updated: ${e.contentUpdated.join(`, `)}`)):n.push(S(`Content already present at ${c}/`)),e.contentSkipped.length>0&&n.push(` Skipped (already exist): ${e.contentSkipped.join(`, `)}`),n.push(``),e.mcpError&&e.editors.length===0)n.push(`Warning: ${e.mcpError}`);else if(e.editors.length===0)if(n.push(S(`MCP server configuration:`)),e.mcpAction===`skipped-flag`)n.push(` MCP config not written — use without --no-mcp to configure editors`);else if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}else n.push(` No supported editor config directories detected; skipped MCP registration`);else if(a)n.push(`MCP config not written — use without --no-mcp to configure editors`);else if(o)n.push(S(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(S(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?T(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,c=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-c.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${c}${l}${i} ${y(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${y(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${b(`FAILED`)}: ${r.error}`);break;case`skipped-flag`:break}r.editorId===`claude`&&e.launchJson&&n.push(s(e.launchJson))}if(e.projectScopeUnsupportedLabels&&e.projectScopeUnsupportedLabels.length>0){let t=e.projectScopeUnsupportedLabels.join(`, `),r=e.projectScopeUnsupportedLabels.length===1?`does`:`do`;n.push(` ${t} ${r} not support project-level config; skipped`)}}if(e.projectSkills.length>0){n.push(``),n.push(S(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?T(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${y(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${y(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${b(`FAILED`)}: ${r.error}`);break}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${T(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(S(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${y(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${y(`already installed at current version`)}`);break;case`failed`:n.push(` ${x(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${x(` npx skills@~1.5.0 add <bundled-path> --agent '*' -g -y --copy`)}`);break}if(e.claudeDesktopDetected&&(n.push(``),n.push(`Claude Desktop App detected. To enable in Claude Chat & Cowork, run: ${S(`ok install-skill`)}`)),e.preview?(n.push(``),n.push(ee(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),r){let t=new Set,r=e.editors.filter(e=>e.action===`written`||e.action===`overwritten`).filter(e=>!t.has(e.editorId)&&t.add(e.editorId)).map(e=>e.label);n.push(``),n.push(`${y(`✓`)} ${S(`Next steps:`)}`),n.push(` 1. Open your editor (${v(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${v(`ok seed`)}`),n.push(` 4. Use the three MCP workflow tools as you build the wiki:`),n.push(` - ${v(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${v(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${v(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
|
|
406
406
|
`)}function Tr(e,t){let n=[];for(let r of J)vr(Q[r],e,t)&&n.push(r);return n}function Er(){return new i(`init`).description(`Scaffold .ok/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the .ok/ directory but do not touch MCP config`).option(`--dev-mcp`,`Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging`).addOption(new r(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).action(async e=>{let t=process.cwd(),n;try{n=await Cr({cwd:t,mcp:e.mcp,devMcp:e.devMcp,scope:e.scope})}catch(e){if(e instanceof u){process.stderr.write(`open-knowledge requires git to initialize a parent repo. Install git or run 'git init' yourself, then re-run.
|
|
407
|
-
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-
|
|
408
|
-
//# sourceMappingURL=init-
|
|
407
|
+
`),e.stderr&&process.stderr.write(`${e.stderr.trim()}\n`),process.exitCode=1;return}throw e}try{let{previewContent:e}=await import(`./preview-B14jfjgL.mjs`),{loadConfig:t}=await import(`./loader-tcpZSp2X.mjs`),{resolveContentDir:r}=await import(`./dist-BXmbRKLs.mjs`),{config:i}=t(n.projectRoot),a=r(i,n.projectRoot);n.preview=e({projectDir:n.projectRoot,contentDir:a})}catch(e){n.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${wr(n,n.projectRoot)}\n`),(n.editors.some(e=>e.action===`failed`)||n.mcpAction===`failed`)&&(process.exitCode=1)})}export{We as C,Ge as S,F as T,at as _,mr as a,ut as b,$ as c,Y as d,Q as f,it as g,st as h,Sr as i,xr as l,Un as m,wr as n,Cr as o,Kn as p,Er as r,_r as s,Tr as t,J as u,ct as v,xe as w,tt as x,ot as y};
|
|
408
|
+
//# sourceMappingURL=init-Mu6hjAn2.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-th8fUQ0l.mjs";export{e as loadConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ln as e,Zr as t,lr as n}from"./dist-k62w-4-v.mjs";import{Kr as r,f as i}from"./dist-
|
|
1
|
+
import{Ln as e,Zr as t,lr as n}from"./dist-k62w-4-v.mjs";import{Kr as r,f as i}from"./dist-BaVVyZsg.mjs";import{t as a}from"./constants-BgI7SDCI.mjs";import{t as o}from"./is-object-C-4FJ0rP.mjs";import{resolve as s}from"node:path";import{existsSync as c,readFileSync as l}from"node:fs";import{homedir as u}from"node:os";import{realpath as d}from"node:fs/promises";async function f(e){let t=s(e);try{return await d(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}var p=t();function m(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];o(a)&&o(i)?n[r]=m(i,a):a!==void 0&&(n[r]=a)}return n}function h(e){if(!c(e))return{value:null,path:e,source:null,doc:null};let t;try{t=l(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,p.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return o(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}const g=[`include`,`exclude`];function _(e){let t="Run `ok config migrate` to strip the obsolete key from config.yml automatically, or remove it by hand.";return e===`exclude`?[`Move these patterns to .okignore at the project root (gitignore syntax, 1:1 migration).`,t].join(` `):[`content.include has been removed.`,`For subdirectory scoping, set content.dir in .ok/config.yml instead.`,`For pattern-based filtering, use .okignore (gitignore syntax — exclude-only; do not copy include patterns directly).`,t].join(` `)}function v(e){let t=e.value;if(!o(t))return[];let r=t.content;if(!o(r))return[];let i=[];for(let t of g)if(t in r){let r=[`content`,t],a;e.doc!==null&&e.source!==null&&(a=n({file:e.path,source:e.source,doc:e.doc,path:r})),i.push({code:`REMOVED_KEY`,path:r,redirect:_(t),...a===void 0?{}:{source:a}})}return i}function y(e,t){return e.map(e=>{let r=e.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:e.message,issueCode:e.code};if(t.doc!==null&&t.source!==null){let e=n({file:t.path,source:t.source,doc:t.doc,path:r});if(e!==void 0)return{...i,source:e}}return i})}function b(t){let n=t??process.cwd(),o=[],c=s(u(),`.ok`,a),l=r({absPath:c}),d={};l.valid&&l.source!==void 0?(d=m(d,l.value),o.push(c)):l.valid;let f=s(n,`.ok`,a),p=h(f);if(p.value!==null){let t=v(p);if(t.length>0)throw Error(t.map(e).join(`
|
|
2
2
|
|
|
3
3
|
`));d=m(d,p.value),o.push(f)}x(d,[`upload`,`maxBytes`],`streaming uploads have no user-facing cap`),x(d,[`github`,`oauthAppClientId`],`use the OPEN_KNOWLEDGE_GITHUB_CLIENT_ID env var instead`),x(d,[`server`,`host`],`use the --host flag or HOST env var instead`),x(d,[`server`,`openOnAgentEdit`]),x(d,[`mcp`,`autoStart`],`to disable auto-start, set OK_MCP_AUTOSTART=0`),x(d,[`mcp`,`tools`,`read_document`,`historyDepth`]),x(d,[`mcp`,`tools`,`grep`,`maxResults`]),x(d,[`mcp`,`tools`,`search`,`maxResults`]),x(d,[`preview`,`baseUrl`],"preview URLs now resolve only to the running UI process — start one with `ok ui`");let g=i.safeParse(d);if(!g.success){let t={code:`SCHEMA_INVALID`,issues:y(g.error.issues,p)};throw Error(e(t))}return{config:g.data,sources:o}}function x(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){if(!o(r))return;r=r[t[e]]}if(!o(r))return;let i=t[t.length-1];if(r[i]===void 0)return;let a=t.join(`.`);console.warn(`[config] ${a} is no longer user-configurable; ${n??`the value is hardcoded in @inkeep/open-knowledge-core`}. Remove the key to silence this warning.`)}function S(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??b,r=new Map,i=new Map,a=f(e.startupCwd);return async o=>{let s=await f(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{b as n,S as t};
|
|
4
|
-
//# sourceMappingURL=loader-
|
|
4
|
+
//# sourceMappingURL=loader-th8fUQ0l.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./preview-Brj3agTC.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Ct as e}from"./dist-
|
|
1
|
+
import{Ct as e}from"./dist-BaVVyZsg.mjs";import"./constants-BgI7SDCI.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);return a.push(``),r(t(i,`.ok`,`config.yml`))?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
|
|
2
2
|
`)}export{c as n,l as t};
|
|
3
|
-
//# sourceMappingURL=preview-
|
|
3
|
+
//# sourceMappingURL=preview-Brj3agTC.mjs.map
|