document360-writer 0.4.70 → 0.4.71
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/cli.js +29 -29
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -167,7 +167,7 @@ Anything only a human knows that would help document this product. For example:
|
|
|
167
167
|
`),"utf8")}async function vs(){let e=process.cwd(),t=ws(e);if(ht(t)&&!await Al({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let n=Cs(e)??hs(e),o=await Dt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Dt({message:"Capture directory (where document360-capture .spec.ts files live):",default:ks}),s=await Dt({message:"Screenshot output directory:",default:bs}),c=await Dt({message:"Default connection profile name:",default:"berlin"}),p=await Dt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:o,docsDir:ys,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:Ps(e)},b=_l(e);b?.terminologyGlossary&&(g.terminologyGlossary=b.terminologyGlossary),gs(g,e),$s(e);let k=pt(e);console.log(""),console.log(j(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${A(`d360-writer login --profile ${c}`)} ${f("(sign in; project & workspace auto-selected)")}`),console.log("");for(let D of ft(k))console.log(D);return console.log(""),console.log(`${f("Then ask:")} ${A('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function Cs(e){let t=wn(e,"package.json");if(!ht(t))return null;try{return JSON.parse(El(t,"utf8")).name??null}catch{return null}}function Ps(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])ht(wn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=wn(e,n);ht(o)&&!Ol(o)&&t.push(n)}return t}function Ol(e){try{return Il(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}L();import{readMcpConfig as po,writeMcpConfig as Ts}from"document360-engine";async function yn(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Ml(),{kind:"continue"}):t==="add"?(Ll(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Wl(e.slice(1)),{kind:"continue"}):(console.log(x(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Ml(){let e=po(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
|
|
168
168
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
169
169
|
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${A(n)} ${f("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${A(n)} ${f(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function Ll(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log(x("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log(x(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=po(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let g=o[++p],b=g?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log(x(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log(x(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=s,Ts(r),console.log(""),console.log(j(`\u2713 Registered "${t}" (${n})`)),console.log(M(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Wl(e){let t=e[0];if(!t){console.log(x("Usage: /mcp remove <name>"));return}let n=po();if(!n.servers[t]){console.log(x(`No server named "${t}".`));return}delete n.servers[t],Ts(n),console.log(j(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}L();import{select as Jl}from"@inquirer/prompts";import{computeSyncStatus as xo,planPartitions as Ql,relatedArticlePaths as Zl,resolveModelForOperation as ec,runPartitioned as tc}from"document360-engine";import B from"picocolors";import Es from"wrap-ansi";import yo from"string-width";L();import Ee from"picocolors";import fo from"wrap-ansi";import mo from"string-width";var Ss=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Rs=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ds=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Fl(e){let t=e.replace(/\r/g,"").split(`
|
|
170
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Ss(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Rs(t[o+1])){let p=Ds(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(Ds(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ss(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Rs(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function ho(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ee.bold(t.slice(2,-2)):t.startsWith("`")?A(t.slice(1,-1)):Ee.italic(t.slice(1,-1)))}var ql=(e,t)=>e+" ".repeat(Math.max(0,t-mo(e)));function Hl(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(mo(C),...t.map(_=>mo(_[N]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],g=()=>p.reduce((C,N)=>C+N,0)+c,b=0;for(;g()>s&&b++<1e4;){let C=-1,N=6;for(let _=0;_<o;_++)p[_]>N&&(N=p[_],C=_);if(C===-1)break;p[C]-=1}let k=(C,N,_)=>Ee.gray(C+p.map(F=>"\u2500".repeat(F+2)).join(N)+_),D=Ee.gray("\u2502"),w=(C,N)=>{let _=p.map(($e,oe)=>{let ke=C[oe]??"",
|
|
170
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(Ss(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&Rs(t[o+1])){let p=Ds(r);o+=2;let g=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)g.push(Ds(t[o++]));n.push({kind:"table",header:p,rows:g});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!Ss(t[o])&&!(t[o].includes("|")&&o+1<t.length&&Rs(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function ho(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ee.bold(t.slice(2,-2)):t.startsWith("`")?A(t.slice(1,-1)):Ee.italic(t.slice(1,-1)))}var ql=(e,t)=>e+" ".repeat(Math.max(0,t-mo(e)));function Hl(e,t,n){let o=e.length,r=e.map((C,N)=>Math.max(mo(C),...t.map(_=>mo(_[N]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],g=()=>p.reduce((C,N)=>C+N,0)+c,b=0;for(;g()>s&&b++<1e4;){let C=-1,N=6;for(let _=0;_<o;_++)p[_]>N&&(N=p[_],C=_);if(C===-1)break;p[C]-=1}let k=(C,N,_)=>Ee.gray(C+p.map(F=>"\u2500".repeat(F+2)).join(N)+_),D=Ee.gray("\u2502"),w=(C,N)=>{let _=p.map(($e,oe)=>{let ke=C[oe]??"",le=N?Ee.bold(ke):ho(ke);return fo(le,$e,{hard:!0}).split(`
|
|
171
171
|
`)}),F=Math.max(..._.map($e=>$e.length)),ee=[];for(let $e=0;$e<F;$e++)ee.push(p.map((oe,ke)=>`${D} ${ql(_[ke][$e]??"",oe)} `).join("")+D);return ee.join(`
|
|
172
172
|
`)},v=[k("\u250C","\u252C","\u2510"),w(e,!0)];return v.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,N)=>{v.push(w(C,!1)),v.push(N===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),v.join(`
|
|
173
173
|
`)}function Bl(e,t){switch(e.kind){case"heading":return Ee.bold(e.text);case"hr":return Ee.gray("\u2500".repeat(t));case"para":return fo(ho(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=fo(ho(n),Math.max(10,t-4)).split(`
|
|
@@ -176,7 +176,7 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
176
176
|
`);case"code":return e.lines.map(n=>Ee.gray(" "+n)).join(`
|
|
177
177
|
`);case"table":return Hl(e.header,e.rows,t)}}function go(e,t){let n=Math.max(20,t);return Fl(e).map(o=>Bl(o,n)).join(`
|
|
178
178
|
|
|
179
|
-
`)}L();import Gl from"picocolors";var Vl=[127,86,217],Yl=[22,38,43],js={T:Vl,E:Yl},jt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],wo=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,zl=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function As(){if(!Gl.isColorSupported)return[];let e=jt[0].length,t=[];for(let n=0;n<jt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=js[jt[n][r]],c=n+1<jt.length?js[jt[n+1][r]]:void 0;s&&c?o+=`${wo(s)}${zl(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${wo(s)}\u2580\x1B[39m`:c?o+=`${wo(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function At(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function
|
|
179
|
+
`)}L();import Gl from"picocolors";var Vl=[127,86,217],Yl=[22,38,43],js={T:Vl,E:Yl},jt=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],wo=([e,t,n])=>`\x1B[38;2;${e};${t};${n}m`,zl=([e,t,n])=>`\x1B[48;2;${e};${t};${n}m`;function As(){if(!Gl.isColorSupported)return[];let e=jt[0].length,t=[];for(let n=0;n<jt.length;n+=2){let o="";for(let r=0;r<e;r++){let s=js[jt[n][r]],c=n+1<jt.length?js[jt[n+1][r]]:void 0;s&&c?o+=`${wo(s)}${zl(c)}\u2580\x1B[49m\x1B[39m`:s?o+=`${wo(s)}\u2580\x1B[39m`:c?o+=`${wo(c)}\u2584\x1B[39m`:o+=" "}t.push(o)}return t}function At(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function ae(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Ie(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var gt=(e,t)=>` ${e.padEnd(13)}${t}`;function Xl(e,t){let n=[Pt("\u270E document360-writer")+B.gray(` v${e.version}`),B.gray(" Reads your code, writes your docs."),"",gt("Claude:",`${e.claude}${B.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),gt("Document360:",e.configured?e.loggedOut?B.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?B.gray(` (${e.sessionHint})`):""}`:B.yellow("not set up \u2014 run /init")),gt("Profile:",e.configured?`${e.profile}${B.gray(` (${e.apiUrl})`)}${e.prod?B.bold(B.yellow(" \u26A0 PRODUCTION")):""}`:B.gray("\u2014 (run /init)")),gt("Project:",e.project),gt("Mode:",B.gray(e.mode)),gt("cwd:",B.gray(e.cwd))],o=As();if(o.length===0)return n.join(`
|
|
180
180
|
`);let r=2,s=3,c=yo(o[0]);if(!(t>=r+c+s+Math.max(...n.map(k=>yo(k)))))return[...o.map(k=>" "+k),...n].join(`
|
|
181
181
|
`);let g=Math.max(0,Math.floor((n.length-o.length)/2)),b=[];for(let k=0;k<Math.max(o.length+g,n.length);k++){let D=o[k-g]??" ".repeat(c);b.push((" ".repeat(r)+D+" ".repeat(s)+(n[k]??"")).trimEnd())}return b.join(`
|
|
182
182
|
`)}var Kl={error:B.red,warn:B.yellow,ok:B.green,info:B.gray};function ko(e,t){let n=Math.max(20,t);switch(e.kind){case"banner":return Xl(e.info,n);case"user":{let o="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,n-4),c=50,p=e.text.split(`
|
|
@@ -193,10 +193,10 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
193
193
|
|
|
194
194
|
`+go(e.text,n);case"note":return`
|
|
195
195
|
`+Kl[e.tone](St(e.text));case"done":return`
|
|
196
|
-
`+(e.ok?B.magenta("\u2736 "):B.red("\u2736 "))+B.gray(`Cooked for ${At(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${
|
|
196
|
+
`+(e.ok?B.magenta("\u2736 "):B.red("\u2736 "))+B.gray(`Cooked for ${At(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${ae(e.costUsd)}`:""))}}function Is(e,t){return e.map(n=>ko(n,t)).join(`
|
|
197
197
|
`)}var Et=3;function $o(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
|
|
198
198
|
`)}var Ns={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function It(e){return e.filter(t=>t.path!==null&&t.status in Ns).map(t=>({path:t.path,label:Ns[t.status]}))}function nc(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=t.replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}function _s(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),s=n.get(r);s?s.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((s,c)=>s.path.localeCompare(c.path));t.push({kind:"category",label:`${nc(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let c=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:c,paths:[s.path],indent:!0,note:s.label})}}return t}function kn(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
|
|
199
|
-
`)}function vo(e,t,n){let o=w=>t[w.index]?.paths.length??0,r=e.filter(w=>w.ok),s=e.filter(w=>!w.ok),c=e.reduce((w,v)=>w+o(v),0),p=r.reduce((w,v)=>w+o(v),0),g=n==="api"?`${
|
|
199
|
+
`)}function vo(e,t,n){let o=w=>t[w.index]?.paths.length??0,r=e.filter(w=>w.ok),s=e.filter(w=>!w.ok),c=e.reduce((w,v)=>w+o(v),0),p=r.reduce((w,v)=>w+o(v),0),g=n==="api"?`${ae(e.reduce((w,v)=>w+v.costUsd,0))} total`:Ie(e.reduce((w,v)=>w+v.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=w=>`${w} article${w===1?"":"s"}`,D=[];if(s.length===0)D.push(`Published ${k(c)} (${b}) successfully \xB7 ${g}.`),D.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{D.push(`Published ${p}/${k(c)} (${b}) \xB7 ${g}.`),D.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let w of s)D.push(` \u2717 ${w.label}${w.error?` \u2014 ${w.error}`:""}`)}return D}async function bo(e,t){let n=Ql(t),{model:o}=ec(e.cwd,"standard");console.log(f(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Et} agents at once) on ${o}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of tc({cwd:e.cwd,partitions:n,promptFor:s=>kn(s.paths),concurrency:Et,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(f(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(j(` \u2713 ${r.label}`)):console.log(x(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let c of vo(r.results,n,s))console.log(r.ok?j(c):M(c))}}catch(r){console.log(x(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function bn(e,t,n){let o=Zl(e,n);if(o.length===0)return[];let r=new Set(It((await xo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function Us(e,t){let n=e[0];if(n==="--related"&&e[1]){if(!t)return{kind:"continue"};let o=await bn(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return o.length===0?(console.log(j("\u2713 All related articles are already published.")),{kind:"continue"}):await bo(t,o)}if(n==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let o=It((await xo({cwd:t?.cwd??process.cwd()})).entries);return o.length===0?(console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await bo(t,o.map(r=>r.path)):{kind:"forward-to-agent",prompt:kn(o.map(r=>r.path)),display:"/publish --all"}}catch(o){return console.log(x(`Could not compute sync status: ${o.message}`)),{kind:"continue"}}}if(!n){console.log(f("Checking what needs publishing\u2026"));let o;try{o=It((await xo({cwd:t?.cwd??process.cwd()})).entries)}catch(r){return console.log(x(`Could not compute sync status: ${r.message}`)),console.log(f("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(o.length===0)return console.log(j("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let r of o)console.log(` ${r.path} ${f(`(${r.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{n=await t.withPausedInput(()=>Jl({message:"Publish which article?",choices:[...o.length>1?[{name:`All ${o.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...o.map(r=>({name:r.path,value:r.path,description:r.label}))]}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(n==="--all")return await bo(t,o.map(r=>r.path))}return{kind:"forward-to-agent",prompt:$o(n),display:`/publish ${n}`}}async function xn(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | adopt) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
|
|
200
200
|
`),display:"/audit"}}L();import{checkbox as oc}from"@inquirer/prompts";import{inventoryRepo as rc,readProjectConfig as Os,writeProjectConfig as sc}from"document360-engine";function Co(e,t){let n=Os(e);n&&(n.authoritativeSourceFiles=t,sc(n,e))}function $n(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Ms(e,t){let n=t?.cwd??process.cwd();if(!Os(n))return console.log(x("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=rc(n);if(o.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(A("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f($n(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>oc({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${$n(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};Co(n,r),console.log(j(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}L();import{confirm as uc}from"@inquirer/prompts";import{applyPull as Hs,computeSyncStatus as Bs,planPull as dc,D360AuthError as pc}from"document360-engine";L();var Ls=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:x,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:M,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:A,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:x,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:x,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:te,mark:"X"},{status:"untracked-local",header:"Untracked local articles \u2014 publish to start tracking:",paint:f,mark:"?"},{status:"untracked-remote",header:"Untracked Document360 articles \u2014 no local file maps to them:",paint:f,mark:"?"},{status:"unknown-base",header:"No sync base recorded yet \u2014 the next /publish or /sync pull of each records one:",paint:te,mark:"\xB7"}];function ic(e){return e.path?e.path:`${e.title??"(untitled)"} ${te(`[${e.articleId}]`)}`}function vn(e){let t=[];for(let c of Ls){let p=e.entries.filter(g=>g.status===c.status);if(p.length!==0){t.push(""),t.push(Pe(c.header));for(let g of p)t.push(` ${c.paint(c.mark)} ${c.paint(ic(g))}${g.detail?te(` (${g.detail})`):""}`)}}let n=e.counts["in-sync"]??0,o=e.entries.length;t.push("");let r={"in-sync":"in sync","local-ahead":"local ahead","remote-ahead":"remote ahead",conflict:"conflicts","untracked-local":"untracked local","untracked-remote":"untracked remote","deleted-local":"deleted locally","deleted-remote":"deleted on D360",orphaned:"orphaned","unknown-base":"no base yet"},s=o===n?j("\u2713 everything in sync"):[n>0?j(`\u2713 ${n} in sync`):null,...Ls.map(c=>{let p=e.counts[c.status]??0;return p>0?`${p} ${r[c.status]}`:null})].filter(Boolean).join(te(" \xB7 "));return t.push(s+te(` \xB7 ${o} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as ac}from"diff";import Ws from"picocolors";var Fs=80,lc="\x1B[48;2;74;28;28m",cc="\x1B[48;2;24;66;24m",qs="\x1B[49m",Po=e=>String(e).padStart(5);function Ge(e,t,n){let o=w=>{let v=w.replace(/\r\n/g,`
|
|
201
201
|
`);return v.endsWith(`
|
|
202
202
|
`)||v===""?v:v+`
|
|
@@ -206,7 +206,7 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
206
206
|
- Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
|
|
207
207
|
- Work only on these files:
|
|
208
208
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
209
|
-
`)}function Ao(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${
|
|
209
|
+
`)}function Ao(e,t,n){let o=e.reduce((p,g)=>p+g.paths.length,0),[r,s]=t.usd;return[`Convert ${o} article${o===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${ae(r)}\u2013${ae(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Eo(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),b=e.reduce((C,N)=>C+N.outputTokens,0),k=n==="api"?`${ae(g)} total`:Ie(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,v=[];if(s.length===0)v.push(`Converted ${w(c)} (${D}) successfully \xB7 ${k}.`);else{v.push(`Converted ${p}/${w(c)} (${D}) \xB7 ${k}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let C of s)v.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return v}async function Vs(e,t){if(!kc(t.cwd))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:n,run:o}=So(e),r=$c(t.cwd,t.profileName);if(r.length===0)return console.log(x("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Ro(r,n);if(s.length===0)return console.log(x(`No tracked articles under "${n}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=yc(s),p=`/convert${n?` --scope ${n}`:""} --run`,{model:g,forced:b}=bc(t.cwd,"light");if(!o){let k=wc({files:Do(t.cwd,s),op:"convert",model:g});n&&console.log(f(`Scope: ${n} (${s.length} of ${r.length} tracked articles).`));for(let D of Ao(c,k,To))console.log(D);return console.log(f(`Model: ${g}${b?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${To} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let k of xc({cwd:t.cwd,partitions:c,promptFor:jo,concurrency:To,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(k.type==="partition_status")k.status==="running"?console.log(f(` \u25B8 ${k.label} \u2014 converting\u2026`)):k.status==="done"?console.log(j(` \u2713 ${k.label}`)):console.log(x(` \u2717 ${k.label}`));else if(k.type==="run_done"){console.log("");let D=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let w of Eo(k.results,c,D))console.log(k.ok?j(w):M(w))}}catch(k){console.log(x(`Convert run failed: ${k.message}`))}return console.log(""),{kind:"continue"}}L();import{statSync as Ys}from"node:fs";import{resolve as zs}from"node:path";import{estimateBulkCost as vc,planPartitions as Cc,readDocsPlan as Pc,readProjectConfig as Xs,DEFAULT_DOCS_DIR as Tc,resolveModelForOperation as Sc,runPartitioned as Rc}from"document360-engine";var Io=5;function No(e){let t,n,o=!1;for(let s=0;s<e.length;s++){let c=e[s];if(c==="--run"||c==="--yes")o=!0;else{if(c==="--all")continue;c==="--scope"?t=e[++s]:c?.startsWith("--scope=")?t=c.slice(8):c&&!c.startsWith("--")&&(n=c)}}let r=s=>s?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:r(t),path:r(n),run:o}}function Dc(e,t){let n=e.replace(/\\/g,"/").replace(/\/+$/,""),o=`${t.replace(/\/+$/,"")}/`;return n.startsWith(o)?n.slice(o.length):n}function jc(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function Ac(e,t,n){return n.filter(o=>{try{return Ys(zs(e,t,o)).size===0}catch{return!0}})}function _o(e,t,n){let o=new Map(t.map(r=>[r.path,r]));return n.map(r=>{let s=1;for(let c of o.get(r)?.sources??[])try{s+=Ys(zs(e,c)).size}catch{}return{path:r,bytes:s}})}function Uo(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
210
210
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
211
211
|
- Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour \u2014 if the source does not say it, omit it.
|
|
212
212
|
- Write the finished article to ${t}/<path>, following the write-article structure and the project terminologyGlossary. Add the \`sources:\` frontmatter listing the files you actually read.
|
|
@@ -214,7 +214,7 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
214
214
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
|
|
215
215
|
Articles:
|
|
216
216
|
`+e.paths.map(n=>`- ${n}`).join(`
|
|
217
|
-
`)}function Oo(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${
|
|
217
|
+
`)}function Oo(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${ae(r)}\u2013${ae(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function Mo(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,N)=>C+o(N),0),p=r.reduce((C,N)=>C+o(N),0),g=e.reduce((C,N)=>C+N.costUsd,0),b=e.reduce((C,N)=>C+N.outputTokens,0),k=n==="api"?`${ae(g)} total`:Ie(b),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,v=[];if(s.length===0)v.push(`Wrote ${w(c)} (${D}) successfully \xB7 ${k}.`),v.push("Next \u2014 push them to Document360:"),v.push("/publish --all"),v.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{v.push(`Wrote ${p}/${w(c)} (${D}) \xB7 ${k}.`),v.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)v.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return v}function Lo(e,t,n){let o=(Xs(e)?.docsDir??Tc).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Dc(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=jc(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};let c=Ac(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Ks(e,t){if(!Xs(t.cwd))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Pc(t.cwd);if(n.length===0)return console.log(x("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,run:s}=No(e),{docsDir:c,targets:p,reason:g}=Lo(t.cwd,n,{scope:o,path:r});if(p.length===0)return console.log(g?M(g):M("Nothing to write.")),{kind:"continue"};let b=Cc(p),{model:k,forced:D}=Sc(t.cwd,"standard");if(!s&&!!!r){let v=vc({files:_o(t.cwd,n,p),op:"write",model:k});o&&console.log(f(`Scope: ${o} (${p.length} pending).`));for(let C of Oo(b,v,Io))console.log(C);return console.log(f(`Model: ${k}${D?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${o?` --scope ${o}`:" --all"} --run to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${p.length} article${p.length===1?"":"s"} across ${b.length} partition${b.length===1?"":"s"} (\u2264${Io} agents at once) on ${k}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let v of Rc({cwd:t.cwd,partitions:b,promptFor:C=>Uo(C,c),concurrency:Io,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:k}))if(v.type==="partition_status")v.status==="running"?console.log(f(` \u25B8 ${v.label} \u2014 writing\u2026`)):v.status==="done"?console.log(j(` \u2713 ${v.label}`)):console.log(x(` \u2717 ${v.label}`));else if(v.type==="run_done"){console.log("");let C=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let N of Mo(v.results,b,C))console.log(v.ok?j(N):M(N))}}catch(v){console.log(x(`Write run failed: ${v.message}`))}return console.log(""),{kind:"continue"}}L();import{existsSync as Ec,readdirSync as Js,statSync as Qs}from"node:fs";import{join as Zs}from"node:path";import{inputDir as Ic,readProjectConfig as Nc}from"document360-engine";var ei=/\.(md|markdown|pdf|txt)$/i;function Wo(e){let t=Ic(e);if(!Ec(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Js(t)){let s=Zs(t,r),c=!1;try{c=Qs(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=_c(s);p>0&&n.push({name:r,docCount:p})}else ei.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function _c(e){let t=0;for(let n of Js(e))try{Qs(Zs(e,n)).isFile()&&ei.test(n)&&t++}catch{}return t}function Fo(e,t){let n=t.trim().toLowerCase();return n?e.find(o=>o.name.toLowerCase()===n)?.name??e.find(o=>o.name.toLowerCase().startsWith(n))?.name??e.find(o=>o.name.toLowerCase().includes(n))?.name??null:null}function Cn(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write --all. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
218
218
|
`)}var qo="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function ti(e,t){let n=t?.cwd??process.cwd();if(!Nc(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=Wo(n);if(o.length===0&&r===0)return console.log(f(qo)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(f("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let g of o)console.log(` ${g.name} ${f(`(${g.docCount} doc${g.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Cn(p),display:p?`/draft ${p}`:"/draft"}}let c=Fo(o,s);return{kind:"forward-to-agent",prompt:Cn(c??"",c?void 0:s),display:`/draft ${s}`}}L();import{listOpenForDocs as Uc,readProjectConfig as Oc}from"document360-engine";function Ho(e){try{return Uc(e).filter(t=>t.kind==="request").length}catch{return 0}}function Bo(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Go(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
|
|
219
219
|
`)}var Vo="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function ni(e,t){let n=t?.cwd??process.cwd();if(!Oc(n))return console.log(x("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Bo(e);if(!r&&Ho(n)===0)return console.log(f(Vo)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Go(r,o),display:s}}L();import{search as Mc}from"@inquirer/prompts";import{findByName as Lc,getSession as Wc,listSessions as Fc,relativeTime as ri}from"document360-engine";async function si(e,t){let n=Fc(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Lc(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(x(`No session matches "${o}".`)),oi(n),{kind:"continue"})}if(!process.stdin.isTTY)return oi(n),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Mc({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${ri(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Wc(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function oi(e){console.log("");for(let t of e.slice(0,15))console.log(` ${A(t.name)} ${f(ri(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}L();import{renameSession as qc}from"document360-engine";function Yo(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function ii(e,t){let n=Yo(e.join(" "));if(!n)return console.log(x("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(qc(o,n)?console.log(j(`\u2713 Session renamed to "${n}"`)):console.log(x("Could not find the current session record.")),{kind:"continue"}):(console.log(x("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as ai,readProjectConfig as Hc,writeProjectConfig as Bc}from"document360-engine";L();function zo(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Hc(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return ai().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Bc(o,e),null):`Unknown environment "${r}". Known: ${ai().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function li(e,t){let n=e[0];if(!n)return sn(t.cwd),{kind:"continue"};if(n==="add"){let o=zo(t.cwd,e[1],e[2]);return o?(console.log(x(o)),{kind:"continue"}):(console.log(j(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${A(`/profile ${e[1]}`)} then ${A("/login")}`),{kind:"continue"})}return an(t.cwd,n),ln(t.cwd,n),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}L();import{select as Gc}from"@inquirer/prompts";import{readProjectConfig as Vc,readUserConfig as ci,resolveModelSetting as Xo,writeUserConfig as ui}from"document360-engine";var xe=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function Pn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=xe.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function Yc(e){switch(e.source){case"project":return".d360-writer.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function Nt(e,t){let n=()=>{let s=Xo(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=ci();return s.defaultModel?(delete s.defaultModel,ui(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Xo(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}ui({...ci(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Vc(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function di(e,t){let n=e[0]?.trim();if(!n){let c=Xo(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${A(c.model??"Claude Code default")}`),console.log(f(` source: ${Yc(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Pn(c),g;try{g=await t.withPausedInput(()=>Gc({message:`Select model (current: ${c.model??"Claude Code default"})`,default:xe[p].value,choices:xe.map((w,v)=>({name:`${w.label}${v===p?" \u2714":""}`,value:w.value,description:w.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:D}=Nt(t.cwd,g??"default");for(let w of b)console.log(w.startsWith("\u26A0")?M(w):w.startsWith("\u2713")?j(w):f(w));return k&&await t.setModel(D),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Nt(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?M(c):c.startsWith("\u2713")?j(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}Tn();async function yi(e,t){return await t.withPausedInput(()=>ut(t.cwd)),{kind:"clear"}}async function ki(e,t){return await t.withPausedInput(()=>Xr(t.cwd,t.profileName)),{kind:"clear"}}L();import{resolveActiveProfile as su}from"document360-engine";async function bi(e,t){let n=!1;try{n=su(t.cwd).production}catch{}return n?(console.log(M("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}L();var xi=async(e,t)=>{try{await t.withPausedInput(()=>rn({}))}catch(n){console.log(x(`Login failed: ${n.message}`))}return{kind:"continue"}};L();import{resolveActiveProfile as iu,clearTokens as au,clearProfileProject as lu}from"document360-engine";async function $i(e,t){let n;try{n=iu(t.cwd,t.profileName).name}catch(r){return console.log(x(r.message)),{kind:"continue"}}let o=au(n);return lu(t.cwd,n),console.log(o?j(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):f(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as vi}from"node:fs";import{isAbsolute as cu,join as uu,resolve as du}from"node:path";import{readProjectConfig as pu,screenshotPlaceholderIds as fu,DEFAULT_CAPTURE_DIR as mu,DEFAULT_OUTPUT_DIR as hu}from"document360-engine";var Ci=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Jo(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?Ci(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:Ci(o),setup:t}:{mode:"single",id:o}}function Qo(e,t){let n=pu(e),o=n?.captureDir??mu,r=n?.outputDir??hu,s=(c,p)=>cu(c)?uu(c,p):du(e,c,p);return fu(e,{scope:t}).map(({id:c,file:p})=>{let g=vi(s(r,`${c}.png`))?"captured":vi(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:g}})}var gu={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},wu={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Zo(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let c of e.filter(p=>p.file===s))r.push(` ${gu[c.state]} ${c.id.padEnd(34)} ${wu[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function Pi(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
|
|
220
220
|
`),"","For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
|
|
@@ -239,29 +239,29 @@ Articles:
|
|
|
239
239
|
`),truncated:c>0||g>0}}}return{text:e,truncated:!1}}function la(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
240
240
|
`)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as br,jsx as R,jsxs as W}from"react/jsx-runtime";var ep={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},ha=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
241
241
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
242
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function tp(e,t,n,o){let r=ba(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=xr(e),p=Q(e),g=(p?.docsDir??xa).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,k={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:ep[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return k;try{let D=fe(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let w=Ye(D.name);if(w){let v={...kt(w.idToken)??{},...kt(w.accessToken)??{}},C=v.email??v.preferred_username??"signed in";_e(w)?w.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(w.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function np(e,t){try{let n=fe(e,t),o=Ye(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...kt(o.idToken)??{},...kt(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return _e(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var ga=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Bn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],op="Ask me to write or update an article\u2026";function Hn({ch:e,dim:t}){let[n,o]=q(!0);return Ue(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),R(S,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var rp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function wa(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var sp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ya(e){try{return ka(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ip(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ya(Wt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ya(Wt(e,o)))}function ap({startTime:e,chars:t}){let[n,o]=q(0);Ue(()=>{let g=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(g)},[]);let r=Bn[n%Bn.length],s=ga[Math.floor(n/16)%ga.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return W(K,{children:[R(S,{color:H,children:` ${r} ${s}\u2026 `}),R(S,{color:"gray",children:`(${At(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var lp=12e4;function cp({p:e}){let[t,n]=q(0);Ue(()=>{let _=setInterval(()=>n(F=>F+1),150);return()=>clearInterval(_)},[]);let o=Bn[t%Bn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=lp,g=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((_,F)=>_+F.items,0),D=g.toLowerCase(),w=e.rows,v=0;if(w.length>Mn){let _=w.findIndex(ee=>ee.status==="active"||ee.status==="pending"),F=Math.max(0,Math.min(_-2,w.length-Mn));v=w.slice(0,F).filter(ee=>ee.status==="done").length,w=w.slice(F,F+Mn)}let C=Math.min(40,Math.max(...w.map(_=>mr(_.label).length),0)),N=_=>_==="failed"?"red":_==="active"?H:void 0;return W(K,{flexDirection:"column",children:[W(K,{children:[R(S,{color:H,children:` ${o} ${g} ${k} ${b}${k===1?"":"s"} `}),R(S,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${At(r)} \xB7 esc to stop`})]}),v>0&&R(S,{dimColor:!0,children:` \u2714 +${v} done`}),w.map(_=>W(S,{color:N(_.status),dimColor:_.status==="done"||_.status==="pending",children:[` ${Qi[_.status]} ${mr(_.label).padEnd(C)}`,_.status!=="pending"?` (${_.items} ${b}${_.items===1?"":"s"})`:"",_.status==="active"?` \u2190 ${D}\u2026`:""]},_.label)),p&&R(S,{color:"yellow",children:` \u26A0 no activity for ${At(s)} \u2014 press esc to stop if it's wedged`})]})}function $a({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=bd(),[s,c]=q(n),[p,g]=q(null),[b,k]=q({text:"",pos:0}),D=b.text,w=z(l=>{k(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),v=z(l=>{k(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=z(()=>{k(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=ra(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,_]=q(!1),[F,ee]=q(!1),[$e,oe]=q(0),[ke,
|
|
242
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function tp(e,t,n,o){let r=ba(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=xr(e),p=Q(e),g=(p?.docsDir??xa).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${g}/ + config`,k={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:ep[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return k;try{let D=fe(e,o);k.profile=D.name,k.apiUrl=D.connection.apiUrl,k.prod=D.production,k.project=D.project.projectName??D.project.projectId??"(chosen at login)";let w=Ye(D.name);if(w){let v={...kt(w.idToken)??{},...kt(w.accessToken)??{}},C=v.email??v.preferred_username??"signed in";_e(w)?w.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(w.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function np(e,t){try{let n=fe(e,t),o=Ye(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...kt(o.idToken)??{},...kt(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return _e(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var ga=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Bn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],op="Ask me to write or update an article\u2026";function Hn({ch:e,dim:t}){let[n,o]=q(!0);return Ue(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),R(S,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var rp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function wa(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var sp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ya(e){try{return ka(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ip(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ya(Wt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ya(Wt(e,o)))}function ap({startTime:e,chars:t}){let[n,o]=q(0);Ue(()=>{let g=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(g)},[]);let r=Bn[n%Bn.length],s=ga[Math.floor(n/16)%ga.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return W(K,{children:[R(S,{color:H,children:` ${r} ${s}\u2026 `}),R(S,{color:"gray",children:`(${At(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var lp=12e4;function cp({p:e}){let[t,n]=q(0);Ue(()=>{let _=setInterval(()=>n(F=>F+1),150);return()=>clearInterval(_)},[]);let o=Bn[t%Bn.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=lp,g=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((_,F)=>_+F.items,0),D=g.toLowerCase(),w=e.rows,v=0;if(w.length>Mn){let _=w.findIndex(ee=>ee.status==="active"||ee.status==="pending"),F=Math.max(0,Math.min(_-2,w.length-Mn));v=w.slice(0,F).filter(ee=>ee.status==="done").length,w=w.slice(F,F+Mn)}let C=Math.min(40,Math.max(...w.map(_=>mr(_.label).length),0)),N=_=>_==="failed"?"red":_==="active"?H:void 0;return W(K,{flexDirection:"column",children:[W(K,{children:[R(S,{color:H,children:` ${o} ${g} ${k} ${b}${k===1?"":"s"} `}),R(S,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${At(r)} \xB7 esc to stop`})]}),v>0&&R(S,{dimColor:!0,children:` \u2714 +${v} done`}),w.map(_=>W(S,{color:N(_.status),dimColor:_.status==="done"||_.status==="pending",children:[` ${Qi[_.status]} ${mr(_.label).padEnd(C)}`,_.status!=="pending"?` (${_.items} ${b}${_.items===1?"":"s"})`:"",_.status==="active"?` \u2190 ${D}\u2026`:""]},_.label)),p&&R(S,{color:"yellow",children:` \u26A0 no activity for ${At(s)} \u2014 press esc to stop if it's wedged`})]})}function $a({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=bd(),[s,c]=q(n),[p,g]=q(null),[b,k]=q({text:"",pos:0}),D=b.text,w=z(l=>{k(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),v=z(l=>{k(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=z(()=>{k(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=ra(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,_]=q(!1),[F,ee]=q(!1),[$e,oe]=q(0),[ke,le]=q(null),[bt,G]=q([]),ze=J(0),[Ta,Ft]=q(!1),[Sa,Xe]=q(0),Oe=J(0),[xt,Ke]=q(0),[Je,qt]=q(null),Cr=J(new Map),Ra=J(0),Qe=J([]),me=J(null);me.current===null&&(me.current=da({cwd:e,profileName:s,allowProdWrites:!1}));let ve=J({uuid:null,firstPrompt:null,titleFired:!1}),Ht=J(new Map),Ze=J(!1),Gn=J([]),Re=J([]),Vn=J(null),[Pr,et]=q(null),[Me,Le]=q(null),[Ce,tt]=q(null),[De,nt]=q(null),[se,ot]=q(null),[he,rt]=q(null),[We,st]=q(null),[Tr,Bt]=q(null),[ge,Fe]=q(null),[ce,it]=q(null),[Sr,Yn]=q([]),qe=J([]),$t=J(!1),we=J(null),[Rr,X]=q(null),Gt=J(!1),Vt=J(null),[ye,He]=q(null),[Dr,at]=q(0),[jr,lt]=q(0),[Da,Ar]=q(0),zn=gr(()=>{try{return xr(e).model??"auto"}catch{return null}},[e,Da]),{stdout:be}=$d(),[,ja]=q(0),Er=J(`${be.columns??80}x${be.rows??24}`),je=z(()=>Math.max(20,(be.columns??80)-1),[be]),u=z(l=>{Qe.current.push(l),console.log(ko(l,je()))},[je]);Ue(()=>{let l=`d360-writer \xB7 ${Pr??Lt(e)}`;if(!N){Un(0),Ot(`${fr} ${l}`);return}Un(3);let i=0;Ot(`${On[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%On.length,Ot(`${On[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,Pr]),Ue(()=>()=>Un(0),[]),Ue(()=>{u({kind:"banner",info:tp(e,o,t,s)});let l=ba(t).state==="missing";if(l&&u({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
243
243
|
${Cd}
|
|
244
|
-
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Q(e)){
|
|
245
|
-
${ha}`}),G(l?["/doctor","/init"]:["/init"]);return}l&&G(["/doctor"]);try{let i=fe(e,s),a=Ye(i.name);a&&_e(a)&&a.refreshToken?Rd({profile:i.name,connection:i.connection}).then(()=>{
|
|
246
|
-
`)})}catch{}try{let i=yt(wt(e));i&&(
|
|
247
|
-
`)})}}catch(
|
|
248
|
-
`)}),
|
|
249
|
-
${ha}`}),G(["/init"]),Ft(!1),!0},[e,
|
|
250
|
-
`)});return;case"exit":case"quit":me.current?.close(),r();return;case"clear":ue(),Qe.current=[],Ft(!1),
|
|
244
|
+
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Q(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
245
|
+
${ha}`}),G(l?["/doctor","/init"]:["/init"]);return}l&&G(["/doctor"]);try{let i=fe(e,s),a=Ye(i.name);a&&_e(a)&&a.refreshToken?Rd({profile:i.name,connection:i.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),oe(h=>h+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),G(["/login"])}):(!a||_e(a))&&(u({kind:"note",tone:"warn",text:`Profile "${i.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"]))}catch{}try{let i=Q(e),a=fe(e,s),h=Ye(a.name);i&&h&&!_e(h)&&ip(e,i.authoritativeSourceFiles)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),G(["/scope"]))}catch{}try{hn(e);let i=gn(e);i.length&&u({kind:"note",tone:"warn",text:i.join(`
|
|
246
|
+
`)})}catch{}try{let i=yt(wt(e));i&&(u({kind:"note",tone:"info",text:`\u{1F4CB} ${i} from the repo's coding agent \u2014 press 1 to /catch-up.`}),G(a=>a.includes("/catch-up")?a:[...a,"/catch-up"]))}catch{}try{Qd(Jd())&&Q(e)?.mode!=="engineer"&&Kd({pkg:Ve,currentVersion:o}).then(async i=>{if(!i.updateAvailable||!i.latest)return;u({kind:"note",tone:"info",text:`\u2B06 Updating ${Ve} ${i.current} \u2192 ${i.latest}\u2026`}),(await Dn()).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${i.latest} \u2014 /exit and relaunch to apply (press 1).`}),G(h=>h.includes("/exit")?h:[...h,"/exit"])):u({kind:"note",tone:"warn",text:`Update available (v${i.latest}) but auto-update failed \u2014 run: ${Rn}`})}).catch(()=>{})}catch{}},[]),Ue(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let h=`${be.columns??80}x${be.rows??24}`;h!==Er.current&&(Er.current=h,ja(d=>d+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Is(Qe.current,je())+"\x1B[?2026l")},80))},400)};return be.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),be.off("resize",a)}},[be,je]);let Be=Math.max(20,(be.columns??80)-1),Ir=gr(()=>np(e,s),[e,s,$e]),Xn=(()=>{let l=Q(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=Wt(e,(l.docsDir??xa).replace(/\/+$/,"")),a=(()=>{try{return ca(i)&&ka(i).length>0}catch{return!1}})();try{let h=fe(e,s),d=Ye(h.name);if(!(!!d&&!(_e(d)&&!d.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:op,isSetup:!1}:{text:"Let's get started \u2014 try /devhints (best docs), or: write the docs for this repo",isSetup:!1}})(),vt=ss(D),Nr=vt.length>0&&!N,Kn=p!==null?aa(p,8,Be):null,Yt=ge?ge.paths.filter(l=>!ge.query||l.toLowerCase().includes(ge.query.toLowerCase())).slice(0,8):[],zt=ye?ye.sessions.filter(l=>{let i=ye.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],ue=z((l,i)=>{me.current?.close(),me.current=da({cwd:e,resume:l,profileName:i??s,allowProdWrites:Ze.current}),l||(ve.current={uuid:null,firstPrompt:null,titleFired:!1},et(null)),at(0),lt(0)},[e,s]),_r=z((l,i,a)=>{if(rp.test(l))try{let h=fe(e,s),d=typeof i.project_id=="string"&&i.project_id||h.project.projectId,m=Nn(i,a),y=[],T=_n(a);l.endsWith("publish_article")&&T&&y.push(`Live: ${T}`),m&&d&&y.push(`Preview: ${In(h.connection.portalUrl,d,m,h.project.languageCode??"en")}`),y.length>0&&u({kind:"link",lines:y})}catch{}},[e,s,u]),de=z(async(l,i)=>{Ft(!0),le(null),G([]),Bt(null);let a=++ze.current;i?.quietUser||u({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let h=ve.current;h.firstPrompt||(h.firstPrompt=i?.display??l),Oe.current=Date.now(),Xe(0),_(!0),Ht.current.clear();let d="",m=!1,y=!1,T="",E=null,I=()=>{E||(E=setTimeout(()=>{E=null,g(T.length>0?T:null)},60))},re=()=>{E&&clearTimeout(E),E=null,g(null)},V=()=>{if(T.trim()){let $=T.trimEnd();u({kind:"assistant",text:$})}T="",re()};try{for await(let $ of me.current.send(l))if($.type==="session"){if(!h.uuid){h.uuid=$.sessionId;let P=new Date().toISOString(),U=Nd(h.firstPrompt??"session");_d({uuid:$.sessionId,name:U,renamed:!1,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:P,updatedAt:P}),et(U)}}else if($.type==="text"){T+=$.delta,d+=$.delta;let P=la(T);if(P>0){let U=T.slice(0,P).trimEnd();U&&u({kind:"assistant",text:U}),T=T.slice(P)}I(),Xe(U=>U+$.delta.length)}else if($.type==="tool"){m=!0;let P=An($.name,$.input);P&&(V(),u({kind:"tool",title:P.title,sep:P.sep,arg:P.arg}),Ht.current.set($.id,{name:$.name,input:$.input}))}else if($.type==="article_diff"){let P=Ge($.oldContent,$.newContent,je());P&&(V(),u({kind:"diff",added:P.added,removed:P.removed,lines:P.lines,hidden:P.hidden}))}else if($.type==="tool_result"){$.isError&&/run \/login|not logged in|session expired|rejected the token/i.test($.output)&&(Gt.current=!0);let P=Ht.current.get($.id);if(P){Ht.current.delete($.id),V();let U=En($.output,4,$.isError?void 0:P.name,P.input);u({kind:"tool-result",lines:U.lines,hidden:U.hidden,isError:$.isError}),$.isError||_r(P.name,P.input,$.output)}}else if($.type==="result"){V(),at(U=>U+$.outputTokens),lt(U=>U+$.costUsd),u({kind:"done",seconds:Math.round((Date.now()-Oe.current)/1e3),tokens:$.outputTokens,costUsd:$.costUsd,ok:$.ok}),!y&&!m&&!d.trim()&&!$t.current&&u({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."});let P=$.ok?Ji(d,Rt.map(U=>U.name)):[];if(P.length>0?G(P):$.ok&&d.trim()&&Ld(l,d,e).then(U=>{U&&ze.current===a&&le(U)}).catch(()=>{}),h.uuid&&(wr(h.uuid),!h.titleFired)){h.titleFired=!0;let U=h.uuid,Z=h.firstPrompt;Z&&pa(Z,e).then(O=>{O&&(Id(U,O),et(O))}).catch(()=>{})}}else $.type==="error"&&(V(),y=!0,$.kind==="auth"&&(Gt.current=!0),u({kind:"note",text:`agent error: ${$.message}`,tone:"error"}))}finally{_(!1),re(),oe($=>$+1),ve.current.uuid&&Xi(e,ve.current.uuid,Qe.current),Gt.current&&(Gt.current=!1,Vt.current=i?.display??l,G(["/login"])),$t.current&&($t.current=!1,qe.current.length>0&&(u({kind:"note",tone:"info",text:`(${qe.current.length} queued message(s) discarded)`}),qe.current=[],Yn([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,_r,je]),Xt=z(async l=>{let i=kr(l),a=qn(e,"standard");Oe.current=Date.now(),Xe(0),_(!0);let h=new AbortController;we.current=h,X({verb:"Publishing",total:i.length,done:0,active:[],rows:Mt(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Et} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let d of Fn({cwd:e,partitions:i,promptFor:m=>kn(m.paths),concurrency:Et,profileName:s,allowProdWrites:Ze.current,model:a.model,signal:h.signal}))if(d.type==="partition_status")d.status==="running"?X(m=>m&&{...m,active:[...m.active,d.label],rows:Te(m.rows,d.label,"active"),lastAt:Date.now()}):X(m=>m&&{...m,active:m.active.filter(y=>y!==d.label),done:m.done+1,rows:Te(m.rows,d.label,d.status==="done"?"done":"failed"),lastAt:Date.now()});else if(d.type==="partition_event")X(m=>{if(!m)return m;let y={...m,lastAt:Date.now()};return d.event.type==="tool"?y.tools=m.tools+1:d.event.type==="text"&&(y.chars=m.chars+d.event.delta.length),y});else if(d.type==="run_done"){lt(T=>T+d.totalCostUsd),at(T=>T+d.results.reduce((E,I)=>E+I.outputTokens,0));let m=d.aborted?"Stopped. ":"",y=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+vo(d.results,i,y).join(`
|
|
247
|
+
`)})}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{we.current=null,X(null),_(!1),oe(d=>d+1)}},[e,s,u,t]),Jn=z(async l=>{await de($o(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await bn(e,s,l.replace(/\\/g,"/"));i.length>0&&(Bt(`Related articles not yet published (${i.length}):`),G([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,de]),Qn=z(l=>{let i=Ye(l);if(!i||_e(i)&&!i.refreshToken)return null;let a={...kt(i.idToken)??{},...kt(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Zn=z((l,i)=>{if(i){let a=Q(e);a&&(a.defaultProfile=l,Wd(a,e))}c(l),ue(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Qn(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"])),oe(a=>a+1)},[e,u,ue,Qn]),Kt=z((l,i,a)=>{tn(e,l,i,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),ue(),fa(e,l)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),u({kind:"note",tone:"info",text:ft(pt(e)).join(`
|
|
248
|
+
`)}),u({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,u,ue]),Jt=z(async l=>{let i;try{i=await Tt(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),G(["/workspace"]);return}if(i.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),h=a.length>0?a:i.workspaces;if(h.length===1){let d=h[0],m=i.workspaces.length-h.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Kt(i.profile,i.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),G(["/workspace"])},[e,u,Kt]),Ur=z((l,i)=>{ro(e,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),ue(),Jt(l)},[e,u,ue,Jt]),Or=z(async l=>{let i;try{i=fe(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await dt(e,i.name),h=a.find(d=>d.id===i.project.projectId);h?.name&&Zd(e,i.name,{projectName:h.name})}catch{}await Jt(i.name);return}u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),G(["/project"])}},[e,u,Jt]),Qt=z(()=>{let l=Re.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=Ge(l.oldContent,l.newContent,je());u(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,je]),Mr=z(l=>{if(Re.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Re.current.shift();try{Fd({cwd:e,profileName:s},a),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Re.current.length===0&&G(h=>h.length>0?h:["/sync"])}catch(h){u({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(i==="n"||i==="no"){let a=Re.current.shift();u({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Re.current.length;return Re.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return Qt(),!0},[e,s,Qt,u]),Lr=z(l=>{let i=Vn.current;if(!i)return!1;if(Vn.current=null,le(null),ze.current++,l.trim()!==i.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:h}=ar(e,i.targets);u({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let d of h)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
249
|
+
${ha}`}),G(["/init"]),Ft(!1),!0},[e,u]),Wr=z(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),h=i.slice(1);switch(Ft(!0),a){case"help":u({kind:"note",tone:"info",text:cn().join(`
|
|
250
|
+
`)});return;case"exit":case"quit":me.current?.close(),r();return;case"clear":ue(),Qe.current=[],Ft(!1),le(null),ze.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=fe(e,s)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),ee(!0);try{let m=await Pd(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},T=>u({kind:"note",tone:"info",text:T})),y=Td(d.name,m);Sd(y),await so(y,d.name,T=>u({kind:"note",tone:"info",text:T})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${on(y)}`}),await Or(s),Vt.current&&(le(Vt.current),Vt.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{ee(!1),oe(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=fe(e,s).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}Ze.current=!0,ue(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=Yo(h.join(" ")),m=ve.current.uuid;if(!m){u({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let y=ve.current.firstPrompt??"";pa(y,e).then(T=>{T?(le(`/rename ${T}`),u({kind:"note",tone:"info",text:`Suggestion: "${T}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Md(m,d),et(d),Ot(`${fr} d360-writer \xB7 ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=h[0],m=Q(e);if(!d){let y=Object.entries(m?.profiles??{});if(y.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let T=y.map(([re,V])=>({name:re,env:V.connection?.environment??"custom",prod:V.production===!0,who:Qn(re)})),E=s??m?.defaultProfile,I=Math.max(0,T.findIndex(re=>re.name===E));tt({cursor:I,current:I,rows:T});return}if(d==="add"){let y=zo(e,h[1],h[2]);if(y){u({kind:"note",tone:"error",text:y});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Zn(h[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}Zn(d,!0);return}case"doctor":await _t(h,{cwd:e});return;case"mcp":await yn(h);return;case"init":{if(Q(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let d=Bd().map(m=>({name:m,apiUrl:Gd(m).apiUrl}));nt({cursor:0,rows:d});return}case"resume":{let d=h.join(" ").trim(),m=Od(e).filter(E=>E.uuid!==ve.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}He({query:"",cursor:0,sessions:m});return}let y=Ud(e,d);if(!y){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}ue(y.uuid),ve.current={uuid:y.uuid,firstPrompt:y.firstPrompt,titleFired:!0},et(y.name),wr(y.uuid),Qe.current=[];let T=pr(e,y.uuid);for(let E of T)u(E);u({kind:"note",tone:"ok",text:T.length?`Resumed "${y.name}" \u2014 restored ${T.length} message(s); continue where you left off.`:`Resumed "${y.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=h.join(" ").trim(),m;try{m=await Tt(e,s)}catch(T){u({kind:"note",tone:"error",text:`Could not list workspaces: ${T.message}`});return}if(!d){let T=m.workspaces.map(I=>({id:I.id,name:I.name??I.id,type:I.workspace_type}));if(T.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let E=Math.max(0,T.findIndex(I=>I.id===m.current));ot({cursor:E,current:E,rows:T,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let y=oo(m.workspaces,d);if(!y){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}Kt(m.profile,m.projectId,y);return}case"project":{let d=h.join(" ").trim(),m;try{m=await dt(e,s)}catch(T){u({kind:"note",tone:"error",text:`Could not list projects: ${T.message} (signed in? try /login)`});return}if(!d){let T=m.projects.map(I=>({id:I.id,name:I.name??I.id,sub:I.sub_domain}));if(T.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let E=T.findIndex(I=>I.id===m.current);rt({cursor:Math.max(0,E),current:E,rows:T,profile:m.profile,environment:m.environment});return}let y=zr(m.projects,d);if(!y){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map(T=>T.name??T.id).join(", ")}`});return}Ur(m.profile,y);return}case"logout":{let d;try{d=fe(e,s).name}catch(y){u({kind:"note",tone:"error",text:y.message});return}let m=Ad(d);Ed(e,d),ue(),oe(y=>y+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),G(["/login"]);return}case"publish":{if(h[0]==="--related"&&h[1]){let m=await bn(e,s,h[1].replace(/\\/g,"/"));if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await Xt(m);return}if(h[0]&&h[0]!=="--all"){await Jn(h[0]);return}let d=h[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await yr({cwd:e,profileName:s}),y=It(m.entries);if(y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let T=m.counts["unknown-base"]??0;T>0&&u({kind:"note",tone:"info",text:`(${T} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(d){await Xt(y.map(T=>T.path));return}st({cursor:0,rows:_s(y)})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let d=h.join(" ").trim();if(!d){let y=[];try{y=Object.keys(fa(e,fe(e,s).name)?.articles??{})}catch{}if(y.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Fe({query:"",cursor:0,paths:y});return}let m=vd(d)?d:Wt(e,d);if(ca(m)){try{u({kind:"preview",name:Lt(m),text:wa(ua(m,"utf8"))})}catch(y){u({kind:"note",tone:"error",text:`Could not read ${m}: ${y.message}`})}return}if(sp.test(d)){try{let y=fe(e,s),T={profile:y.name,connection:y.connection},E=y.project.projectId??Dd(T),I=await jd(T,E,d);u({kind:"preview",name:I.title??d,text:I.content??"*(article has no content)*"})}catch(y){u({kind:"note",tone:"error",text:`Could not fetch article: ${y.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=h[0]?.trim();if(!d){let E=Pn(xr(e));Le({cursor:E,current:E});return}let{lines:m,changed:y,effective:T}=Nt(e,d);for(let E of m)u({kind:"note",tone:E.startsWith("\u26A0")?"warn":E.startsWith("\u2713")?"ok":"info",text:E});y&&(Ar(E=>E+1),me.current?.setModel(T));return}case"convert":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:m}=So(h),y=zd(e,s);if(y.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let T=Ro(y,d);if(T.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${y.length} are tracked overall.)`});return}let E=kr(T),I=3,re=`/convert${d?` --scope ${d}`:""} --run`,V=qn(e,"light");if(!m){let P=ma({files:Do(e,T),op:"convert",model:V.model}),U=d?`Scope: ${d} (${T.length} of ${y.length} tracked)
|
|
251
251
|
`:"",Z=`
|
|
252
|
-
Model: ${V.model}${V.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;
|
|
253
|
-
`)+Z}),G([re]);return}Oe.current=Date.now(),Xe(0),_(!0);let $=new AbortController;we.current=$,X({verb:"Converting",total:E.length,done:0,active:[],rows:Mt(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),
|
|
254
|
-
`)})}}catch(P){
|
|
255
|
-
`:"",
|
|
256
|
-
Model: ${P.model}${P.forced?" (forced)":" \u2014 authoring; /model to override"}`;
|
|
257
|
-
`)+
|
|
258
|
-
`)}),!O.aborted&&O.ok&&G(["/publish --all","/screenshot --all"])}}catch(O){
|
|
259
|
-
${
|
|
260
|
-
`)}`}),G(
|
|
261
|
-
`)});return}if(
|
|
262
|
-
`)})}return}case"devhints":{if(!Q(e)){
|
|
263
|
-
`)});return}case"inbox":{if(!Q(e)){
|
|
264
|
-
`)});return}if(
|
|
265
|
-
`)})}return}case"reset":{let
|
|
266
|
-
`)}),se(Lt(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Qt,d,ue,de,Xt,Jn,Or]),Zt=z(l=>{let i=(l??D).trim();if(w(""),qt(null),Ke(0),i.startsWith("/")&&(se(null),ze.current++,Bt(null),G(h=>Zi(h,i))),!i||Lr(i)||Mr(i))return;Gn.current.push(i);let a=oa(i,Cr.current);i.startsWith("/")?(d({kind:"user",text:i}),Wr(a)):de(a,{display:i})},[D,Lr,Mr,Wr,de]),Fr=z(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=ea(l);if(ta(i)){let a=na(++Ra.current,i);Cr.current.set(a,i),v(a)}else v(i);return}v(l)},[v]),ct=Math.max(10,Be-6),qr=gr(()=>Ln(b.text,ct),[b.text,ct]),eo=z(l=>k(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),en=z(l=>k(i=>({...i,pos:sa(Ln(i.text,ct),i.pos,l)})),[ct]),Ct=z(l=>k(i=>({...i,pos:ia(Ln(i.text,ct),i.pos,l)})),[ct]),Aa=["\x1B[H","\x1B[1~","\x1BOH"],Ea=["\x1B[F","\x1B[4~","\x1BOF"],Hr=z((l,i)=>i.leftArrow?(eo(-1),!0):i.rightArrow?(eo(1),!0):l&&Aa.includes(l)?(Ct("start"),!0):l&&Ea.includes(l)?(Ct("end"),!0):i.ctrl&&l==="a"?(Ct("start"),!0):i.ctrl&&l==="e"?(Ct("end"),!0):!1,[eo,Ct]);return xd((l,i)=>{if(i.ctrl&&l==="c"){me.current?.close(),r();return}if(!F){if(N){if(i.escape){if(we.current){we.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),we.current.abort());return}$t.current||($t.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),me.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;qe.current.push(a),Yn([...qe.current]),w("");return}if(Hr(l,i))return;if(i.upArrow){en(-1);return}if(i.downArrow){en(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Fr(l);return}if(Me){if(i.upArrow){Le(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Le(a=>a&&{...a,cursor:Math.min(xe.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Le(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe[Me.cursor];Le(null);let{lines:h,changed:u,effective:m}=Nt(e,a.value??"default");for(let y of h)d({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});u&&(Ar(y=>y+1),me.current?.setModel(m));return}if(l==="s"){let a=xe[Me.cursor];Le(null),me.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Le(null);return}return}if(Ce){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ce.rows.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Ce.rows[Ce.cursor];tt(null),Zn(a.name,i.return===!0);return}if(i.escape){tt(null);return}return}if(De){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){nt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=De.rows[De.cursor].name;if(nt(null),!xs(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let u=!1;try{let m=Ye(a);u=!!m&&!(_e(m)&&!m.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),G(["/login"]),oe(m=>m+1);return}if(i.escape){nt(null);return}return}if(ie){if(i.upArrow){ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ot(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ie.rows.length){ot(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ie.rows[ie.cursor],{profile:h,projectId:u}=ie;ot(null),Kt(h,u,a);return}if(i.escape){ot(null);return}return}if(he){if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=he.rows.length){rt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=he.rows[he.cursor],{profile:h}=he;rt(null),Ur(h,a);return}if(i.escape){rt(null);return}return}if(ce){if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){it(a=>a&&{...a,rows:a.rows.map((h,u)=>u===a.cursor?{...h,checked:!h.checked}:h)});return}if(i.return){let a=ce.rows.filter(h=>h.checked).map(h=>h.path);if(it(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Co(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let h of a)d({kind:"note",tone:"info",text:` ${h}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){it(null);return}return}if(We){if(i.upArrow){st(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){st(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=We.rows.length){st(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=We.rows[We.cursor];st(null),a.kind==="article"?Jn(a.paths[0]):Xt(a.paths);return}if(i.escape){st(null);return}return}if(ge){if(i.escape){Fe(null);return}if(i.upArrow){Fe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Fe(a=>a&&{...a,cursor:Math.min(Math.max(0,Yt.length-1),a.cursor+1)});return}if(i.return){let a=Yt[ge.cursor];if(a){Fe(null);try{d({kind:"preview",name:Lt(a),text:wa(ua(Wt(e,a),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${a}: ${h.message}`})}}return}if(i.backspace||i.delete){Fe(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Fe(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(ye){if(i.escape){He(null);return}if(i.upArrow){He(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){He(a=>a&&{...a,cursor:Math.min(Math.max(0,zt.length-1),a.cursor+1)});return}if(i.return){let a=zt[ye.cursor];if(a){He(null),ue(a.uuid),ve.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},et(a.name),wr(a.uuid),Qe.current=[];let h=pr(e,a.uuid);for(let u of h)d(u);d({kind:"note",tone:"ok",text:h.length?`Resumed "${a.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){He(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){He(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&ke){w(ke),se(null),ze.current++;return}if(!D&&bt.length>0&&l&&/^[1-9]$/.test(l)){let a=bt[Number(l)-1];if(a){w(a);return}}if(!Hr(l,i)){if(Nr){if(i.upArrow){Ke(a=>Math.max(0,a-1));return}if(i.downArrow){Ke(a=>Math.min(vt.length-1,a+1));return}if(i.tab){w("/"+(vt[xt]?.name??"")+" "),Ke(0);return}if(i.return){let a=vt[xt];if(a){let h=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(is(a.usage)&&!h){w("/"+a.name+" "),Ke(0);return}Zt("/"+a.name+(h?" "+h:""));return}}}else{if(i.upArrow){if(D!==""&&Je===null){en(-1);return}let a=Gn.current;if(!a.length)return;let h=Je===null?a.length-1:Math.max(0,Je-1);qt(h),w(a[h]??"");return}if(i.downArrow){if(D!==""&&Je===null){en(1);return}let a=Gn.current;if(Je===null)return;let h=Je+1;h>=a.length?(qt(null),w("")):(qt(h),w(a[h]??""));return}}if(i.return){Zt();return}if(i.backspace||i.delete){C();return}if(i.escape){w(""),Ke(0),se(null),G([]),Bt(null);return}l&&!i.ctrl&&!i.meta&&Fr(l)}}}),Ue(()=>{if(N||F)return;let l=qe.current.shift();l!==void 0&&(Yn([...qe.current]),Zt(l))},[N,F,Zt]),W(K,{flexDirection:"column",width:Be,children:[Kn!==null&&W(K,{marginTop:1,flexDirection:"column",children:[Kn.truncated&&R(S,{dimColor:!0,children:"\u2026"}),R(S,{children:Kn.text})]}),N&&(Rr?R(cp,{p:Rr}):R(ap,{startTime:Oe.current,chars:Sa})),R(K,{borderStyle:"round",borderColor:Ir.prod?"yellow":H,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?qr.map((l,i)=>{let a=b.text.slice(l.start,l.end),h=i===Wn(qr,b.pos),u=Math.min(b.pos,l.end)-l.start;return W(S,{children:[R(S,{color:H,children:i===0?"> ":" "}),h?W(br,{children:[a.slice(0,u),R(Hn,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):W(S,{children:[R(S,{color:H,children:"> "}),ke&&!N?W(br,{children:[R(Hn,{ch:ke[0],dim:!0}),R(S,{color:"gray",children:ke.slice(1)}),R(S,{dimColor:!0,children:" (tab)"})]}):Xn.isSetup||!Ta?W(br,{children:[R(Hn,{ch:Xn.text[0],dim:!0}),R(S,{color:"gray",children:Xn.text.slice(1)})]}):R(Hn,{ch:" "})]})}),Sr.length>0&&R(K,{flexDirection:"column",paddingX:1,children:Sr.map((l,i)=>R(S,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Me?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Select model"}),R(S,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),xe.map((l,i)=>W(S,{color:i===Me.cursor?H:void 0,children:[i===Me.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Me.current?" \u2714":""}`.padEnd(16),R(S,{color:"gray",children:l.desc})]},l.label)),R(S,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ce?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Switch connection profile"}),Ce.rows.map((l,i)=>W(S,{color:i===Ce.cursor?H:void 0,children:[i===Ce.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Ce.current?" \u2714":""}`.padEnd(20),R(S,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?R(S,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),R(S,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):De?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Pick your Document360 environment"}),De.rows.map((l,i)=>W(S,{color:i===De.cursor?H:void 0,children:[i===De.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),R(S,{color:"gray",children:l.apiUrl})]},l.name)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ie?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Switch workspace"}),R(S,{dimColor:!0,children:`environment ${ie.environment} \xB7 project ${ie.projectName??`${ie.projectId.slice(0,8)}\u2026`}`}),ie.rows.map((l,i)=>W(S,{color:i===ie.cursor?H:void 0,children:[i===ie.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ie.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.type??""})]},l.id)),R(S,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):he?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Choose project"}),R(S,{dimColor:!0,children:`environment ${he.environment}`}),he.rows.map((l,i)=>W(S,{color:i===he.cursor?H:void 0,children:[i===he.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===he.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.sub??""})]},l.id)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ce?(()=>{let i=Math.min(Math.max(0,ce.cursor-Math.floor(7)),Math.max(0,ce.rows.length-14)),a=ce.rows.slice(i,i+14),h=ce.rows.filter(u=>u.checked).length;return W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ce.rows.length})`}),i>0?R(S,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,m)=>{let y=i+m;return W(S,{color:y===ce.cursor?H:void 0,children:[y===ce.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,Be-34)),R(S,{color:"gray",children:$n(u)})]},u.path)}),i+14<ce.rows.length?R(S,{dimColor:!0,children:` \u2193 ${ce.rows.length-i-14} more`}):null,R(S,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():We?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),We.rows.map((l,i)=>{let a=i===We.cursor,h=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return W(S,{color:a?H:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${h}${u} ${l.label}`.padEnd(Math.min(56,Be-24)),l.note?R(S,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),R(S,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ge?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:`Preview article${ge.query?` \u2014 filter: ${ge.query}`:" (type to filter)"}`}),Yt.length===0?R(S,{color:"gray",children:"no articles match"}):Yt.map((l,i)=>W(S,{color:i===ge.cursor?H:void 0,children:[i===ge.cursor?"\u276F ":" ",l]},l)),R(S,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),zt.length===0?R(S,{color:"gray",children:"no sessions match"}):zt.map((l,i)=>W(S,{color:i===ye.cursor?H:void 0,children:[i===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),R(S,{color:i===ye.cursor?H:"gray",children:l.firstPrompt.slice(0,Math.max(10,Be-40))})]},l.uuid)),R(S,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Nr?R(K,{flexDirection:"column",children:vt.map((l,i)=>W(S,{color:i===xt?H:void 0,children:[i===xt?"\u276F ":" ",l.usage.padEnd(22)," ",R(S,{color:i===xt?H:"gray",children:l.name==="model"&&zn?`${l.desc} (currently ${zn})`:l.desc})]},l.name))}):!D&&bt.length>0?W(K,{flexDirection:"column",paddingX:1,children:[Tr?R(S,{color:H,children:Tr}):null,bt.map((l,i)=>W(S,{children:[R(S,{color:H,children:i+1})," ",l.slice(0,Math.max(20,Be-5))]},l)),R(S,{dimColor:!0,children:`press 1-${bt.length} to fill the command \xB7 esc dismiss`})]}):R(K,{paddingX:1,children:W(S,{color:"gray",children:[Ir.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${zn??"model n/a"}${t.kind==="api"?jr>0?` \xB7 ${le(jr)}`:"":Dr>0?` \xB7 ${Ie(Dr)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}L();import{jsx as pp}from"react/jsx-runtime";async function va(e=process.cwd(),t="auto",n,o="0.0.0"){let r=dp(t);r.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=up(pp($a,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
252
|
+
Model: ${V.model}${V.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:U+Ao(E,P,I).join(`
|
|
253
|
+
`)+Z}),G([re]);return}Oe.current=Date.now(),Xe(0),_(!0);let $=new AbortController;we.current=$,X({verb:"Converting",total:E.length,done:0,active:[],rows:Mt(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${T.length} articles across ${E.length} partitions (\u2264${I} agents at once) on ${V.model}\u2026 (esc to stop)`});try{for await(let P of Fn({cwd:e,partitions:E,promptFor:jo,concurrency:I,profileName:s,allowProdWrites:Ze.current,model:V.model,signal:$.signal}))if(P.type==="partition_status")P.status==="running"?X(U=>U&&{...U,active:[...U.active,P.label],rows:Te(U.rows,P.label,"active"),lastAt:Date.now()}):X(U=>U&&{...U,active:U.active.filter(Z=>Z!==P.label),done:U.done+1,rows:Te(U.rows,P.label,P.status==="done"?"done":"failed"),lastAt:Date.now()});else if(P.type==="partition_event")X(U=>{if(!U)return U;let Z={...U,lastAt:Date.now()};return P.event.type==="tool"?Z.tools=U.tools+1:P.event.type==="text"&&(Z.chars=U.chars+P.event.delta.length),Z});else if(P.type==="run_done"){lt(O=>O+P.totalCostUsd),at(O=>O+P.results.reduce((Y,ie)=>Y+ie.outputTokens,0));let U=P.aborted?"Stopped. ":"",Z=t.kind==="api"?"api":"subscription";u({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:U+Eo(P.results,E,Z).join(`
|
|
254
|
+
`)})}}catch(P){u({kind:"note",tone:"error",text:`Convert run failed: ${P.message}`})}finally{we.current=null,X(null),_(!1),oe(P=>P+1)}return}case"write":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Xd(e);if(d.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:y,run:T}=No(h),{docsDir:E,targets:I,reason:re}=Lo(e,d,{scope:m,path:y});if(I.length===0){u({kind:"note",tone:"warn",text:re??"Nothing to write."});return}let V=kr(I),$=5,P=qn(e,"standard");if(!T&&!!!y){let O=ma({files:_o(e,d,I),op:"write",model:P.model}),Y=m?`Scope: ${m} (${I.length} pending)
|
|
255
|
+
`:"",ie=`
|
|
256
|
+
Model: ${P.model}${P.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:Y+Oo(V,O,$).join(`
|
|
257
|
+
`)+ie}),G([`/write${m?` --scope ${m}`:" --all"} --run`]);return}Oe.current=Date.now(),Xe(0),_(!0);let Z=new AbortController;we.current=Z,X({verb:"Writing",total:V.length,done:0,active:[],rows:Mt(V),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${I.length} article${I.length===1?"":"s"} across ${V.length} partition${V.length===1?"":"s"} (\u2264${$} agents at once) on ${P.model}${P.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let O of Fn({cwd:e,partitions:V,promptFor:Y=>Uo(Y,E),concurrency:$,profileName:s,allowProdWrites:Ze.current,model:P.model,signal:Z.signal}))if(O.type==="partition_status")O.status==="running"?X(Y=>Y&&{...Y,active:[...Y.active,O.label],rows:Te(Y.rows,O.label,"active"),lastAt:Date.now()}):X(Y=>Y&&{...Y,active:Y.active.filter(ie=>ie!==O.label),done:Y.done+1,rows:Te(Y.rows,O.label,O.status==="done"?"done":"failed"),lastAt:Date.now()});else if(O.type==="partition_event")X(Y=>{if(!Y)return Y;let ie={...Y,lastAt:Date.now()};return O.event.type==="tool"?ie.tools=Y.tools+1:O.event.type==="text"&&(ie.chars=Y.chars+O.event.delta.length),ie});else if(O.type==="run_done"){lt(to=>to+O.totalCostUsd),at(to=>to+O.results.reduce((Ia,Na)=>Ia+Na.outputTokens,0));let Y=O.aborted?"Stopped. ":"",ie=t.kind==="api"?"api":"subscription";u({kind:"note",tone:O.aborted?"warn":O.ok?"ok":"warn",text:Y+Mo(O.results,V,ie).join(`
|
|
258
|
+
`)}),!O.aborted&&O.ok&&G(["/publish --all","/screenshot --all"])}}catch(O){u({kind:"note",tone:"error",text:`Write run failed: ${O.message}`})}finally{we.current=null,X(null),_(!1),oe(O=>O+1)}return}case"draft":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:m}=Wo(e);if(d.length===0&&m===0){u({kind:"note",tone:"info",text:qo});return}let y=h.join(" ").trim();if(!y&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
259
|
+
${d.map(I=>` \u2022 ${I.name} (${I.docCount} doc${I.docCount===1?"":"s"})`).join(`
|
|
260
|
+
`)}`}),G(d.map(I=>`/draft ${I.name}`));return}let T="",E;if(y){let I=Fo(d,y);I?T=I:E=y}else T=d[0]?.name??"";await de(Cn(T,E),{display:y?`/draft ${y}`:"/draft",quietUser:!0});return}case"sync":{let d=(h[0]??"status").toLowerCase();try{if(d==="status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let m=await yr({cwd:e,profileName:s});u({kind:"note",tone:"info",text:vn(m).join(`
|
|
261
|
+
`)});return}if(d==="pull"){let m=h[1];if(!m){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let y;if(m==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),y=(await yr({cwd:e,profileName:s})).entries.filter(I=>I.status==="remote-ahead"&&I.path).map(I=>I.path),y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else y=[m.replace(/\\/g,"/")];let T=[];for(let E of y)T.push(await qd({cwd:e,profileName:s,relPath:E}));Re.current=T,Qt();return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${d} \u2014 use /sync or /sync pull <path>|--all.`})}catch(m){u({kind:"note",tone:"error",text:`Sync failed: ${m.message}`})}return}case"scope":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Hd(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}it({cursor:0,rows:d.map(m=>({...m,checked:m.recommended}))});return}case"audit":case"capture-setup":{let m=await(a==="audit"?xn:Ut)(h,void 0);if(m.kind==="forward-to-agent"&&m.prompt&&await de(m.prompt,{display:m.display,quietUser:!0}),a==="capture-setup"){let y=er(e);y&&u({kind:"note",tone:"info",text:y.join(`
|
|
262
|
+
`)})}return}case"devhints":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:ft(pt(e)).join(`
|
|
263
|
+
`)});return}case"inbox":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(tr(e)===0){u({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await de(nr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:m}=Bo(h);if(!m&&Ho(e)===0){u({kind:"note",tone:"info",text:Vo});return}let y=`/document${m?` ${m}`:""}${d?" --publish":""}`;await de(Go(m,d),{display:y,quietUser:!0});return}case"catch-up":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d}=or(h),m=yt(wt(e));u({kind:"note",tone:"info",text:m?`Catching up on ${m} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026"}),await de(rr({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{u({kind:"note",tone:"info",text:`Updating ${Ve}\u2026`}),(await Dn()).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 /exit and relaunch to apply (press 1)."}),G(m=>m.includes("/exit")?m:[...m,"/exit"])):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Rn}`});return}case"screenshot":{let d=Jo(h);if(d.mode==="list"){if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:Zo(Qo(e,d.scope),d.scope).join(`
|
|
264
|
+
`)});return}if(d.mode==="single"){let $=await Sn(h);$.kind==="forward-to-agent"&&$.prompt&&await de($.prompt,{display:$.display,quietUser:!0});return}if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=d.mode==="scope"?d.scope:void 0,y=Yd(e,{scope:m}).map($=>$.id);if(y.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let T=6,E=Vd(y,3),I=qn(e,"standard");Oe.current=Date.now(),Xe(0),_(!0);let re=new AbortController;we.current=re,X({verb:"Authoring",unit:"spec",total:E.length,done:0,active:[],rows:Mt(E),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${y.length} screenshot spec${y.length===1?"":"s"} across ${E.length} partition${E.length===1?"":"s"} (\u2264${T} agents at once) on ${I.model}${I.forced?" (forced)":""}\u2026 (esc to stop)`});let V=!1;try{for await(let $ of Fn({cwd:e,partitions:E,promptFor:Pi,concurrency:T,profileName:s,allowProdWrites:Ze.current,model:I.model,signal:re.signal}))if($.type==="partition_status")$.status==="running"?X(P=>P&&{...P,active:[...P.active,$.label],rows:Te(P.rows,$.label,"active"),lastAt:Date.now()}):X(P=>P&&{...P,active:P.active.filter(U=>U!==$.label),done:P.done+1,rows:Te(P.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")X(P=>{if(!P)return P;let U={...P,lastAt:Date.now()};return $.event.type==="tool"?U.tools=P.tools+1:$.event.type==="text"&&(U.chars=P.chars+$.event.delta.length),U});else if($.type==="run_done"){lt(O=>O+$.totalCostUsd),at(O=>O+$.results.reduce((Y,ie)=>Y+ie.outputTokens,0));let P=$.results.filter(O=>O.ok).length,U=$.aborted?"Stopped. ":"";V=!$.aborted&&d.setup;let Z=$.aborted?"":V?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:`${U}Authored specs \u2014 ${P}/${$.results.length} batches ok.${Z}`})}}catch($){u({kind:"note",tone:"error",text:`Spec authoring failed: ${$.message}`})}finally{we.current=null,X(null),_(!1),oe($=>$+1)}if(V){let $=await Ut();$.kind==="forward-to-agent"&&$.prompt&&await de($.prompt,{display:$.display,quietUser:!0});let P=er(e);P&&u({kind:"note",tone:"info",text:P.join(`
|
|
265
|
+
`)})}return}case"reset":{let d=ir(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}Vn.current={repoName:Lt(e),targets:d},u({kind:"note",tone:"warn",text:lr(e,d).join(`
|
|
266
|
+
`)}),le(Lt(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,Qt,u,ue,de,Xt,Jn,Or]),Zt=z(l=>{let i=(l??D).trim();if(w(""),qt(null),Ke(0),i.startsWith("/")&&(le(null),ze.current++,Bt(null),G(h=>Zi(h,i))),!i||Lr(i)||Mr(i))return;Gn.current.push(i);let a=oa(i,Cr.current);i.startsWith("/")?(u({kind:"user",text:i}),Wr(a)):de(a,{display:i})},[D,Lr,Mr,Wr,de]),Fr=z(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=ea(l);if(ta(i)){let a=na(++Ra.current,i);Cr.current.set(a,i),v(a)}else v(i);return}v(l)},[v]),ct=Math.max(10,Be-6),qr=gr(()=>Ln(b.text,ct),[b.text,ct]),eo=z(l=>k(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),en=z(l=>k(i=>({...i,pos:sa(Ln(i.text,ct),i.pos,l)})),[ct]),Ct=z(l=>k(i=>({...i,pos:ia(Ln(i.text,ct),i.pos,l)})),[ct]),Aa=["\x1B[H","\x1B[1~","\x1BOH"],Ea=["\x1B[F","\x1B[4~","\x1BOF"],Hr=z((l,i)=>i.leftArrow?(eo(-1),!0):i.rightArrow?(eo(1),!0):l&&Aa.includes(l)?(Ct("start"),!0):l&&Ea.includes(l)?(Ct("end"),!0):i.ctrl&&l==="a"?(Ct("start"),!0):i.ctrl&&l==="e"?(Ct("end"),!0):!1,[eo,Ct]);return xd((l,i)=>{if(i.ctrl&&l==="c"){me.current?.close(),r();return}if(!F){if(N){if(i.escape){if(we.current){we.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),we.current.abort());return}$t.current||($t.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),me.current?.interrupt());return}if(i.return){let a=D.trim();if(!a)return;qe.current.push(a),Yn([...qe.current]),w("");return}if(Hr(l,i))return;if(i.upArrow){en(-1);return}if(i.downArrow){en(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Fr(l);return}if(Me){if(i.upArrow){Le(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Le(a=>a&&{...a,cursor:Math.min(xe.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Le(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=xe[Me.cursor];Le(null);let{lines:h,changed:d,effective:m}=Nt(e,a.value??"default");for(let y of h)u({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});d&&(Ar(y=>y+1),me.current?.setModel(m));return}if(l==="s"){let a=xe[Me.cursor];Le(null),me.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Le(null);return}return}if(Ce){if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ce.rows.length){tt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Ce.rows[Ce.cursor];tt(null),Zn(a.name,i.return===!0);return}if(i.escape){tt(null);return}return}if(De){if(i.upArrow){nt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){nt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){nt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=De.rows[De.cursor].name;if(nt(null),!xs(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let d=!1;try{let m=Ye(a);d=!!m&&!(_e(m)&&!m.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),G(["/login"]),oe(m=>m+1);return}if(i.escape){nt(null);return}return}if(se){if(i.upArrow){ot(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ot(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=se.rows.length){ot(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=se.rows[se.cursor],{profile:h,projectId:d}=se;ot(null),Kt(h,d,a);return}if(i.escape){ot(null);return}return}if(he){if(i.upArrow){rt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){rt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=he.rows.length){rt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=he.rows[he.cursor],{profile:h}=he;rt(null),Ur(h,a);return}if(i.escape){rt(null);return}return}if(ce){if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){it(a=>a&&{...a,rows:a.rows.map((h,d)=>d===a.cursor?{...h,checked:!h.checked}:h)});return}if(i.return){let a=ce.rows.filter(h=>h.checked).map(h=>h.path);if(it(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Co(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let h of a)u({kind:"note",tone:"info",text:` ${h}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){it(null);return}return}if(We){if(i.upArrow){st(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){st(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=We.rows.length){st(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=We.rows[We.cursor];st(null),a.kind==="article"?Jn(a.paths[0]):Xt(a.paths);return}if(i.escape){st(null);return}return}if(ge){if(i.escape){Fe(null);return}if(i.upArrow){Fe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Fe(a=>a&&{...a,cursor:Math.min(Math.max(0,Yt.length-1),a.cursor+1)});return}if(i.return){let a=Yt[ge.cursor];if(a){Fe(null);try{u({kind:"preview",name:Lt(a),text:wa(ua(Wt(e,a),"utf8"))})}catch(h){u({kind:"note",tone:"error",text:`Could not read ${a}: ${h.message}`})}}return}if(i.backspace||i.delete){Fe(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Fe(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(ye){if(i.escape){He(null);return}if(i.upArrow){He(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){He(a=>a&&{...a,cursor:Math.min(Math.max(0,zt.length-1),a.cursor+1)});return}if(i.return){let a=zt[ye.cursor];if(a){He(null),ue(a.uuid),ve.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},et(a.name),wr(a.uuid),Qe.current=[];let h=pr(e,a.uuid);for(let d of h)u(d);u({kind:"note",tone:"ok",text:h.length?`Resumed "${a.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){He(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){He(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!D&&ke){w(ke),le(null),ze.current++;return}if(!D&&bt.length>0&&l&&/^[1-9]$/.test(l)){let a=bt[Number(l)-1];if(a){w(a);return}}if(!Hr(l,i)){if(Nr){if(i.upArrow){Ke(a=>Math.max(0,a-1));return}if(i.downArrow){Ke(a=>Math.min(vt.length-1,a+1));return}if(i.tab){w("/"+(vt[xt]?.name??"")+" "),Ke(0);return}if(i.return){let a=vt[xt];if(a){let h=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(is(a.usage)&&!h){w("/"+a.name+" "),Ke(0);return}Zt("/"+a.name+(h?" "+h:""));return}}}else{if(i.upArrow){if(D!==""&&Je===null){en(-1);return}let a=Gn.current;if(!a.length)return;let h=Je===null?a.length-1:Math.max(0,Je-1);qt(h),w(a[h]??"");return}if(i.downArrow){if(D!==""&&Je===null){en(1);return}let a=Gn.current;if(Je===null)return;let h=Je+1;h>=a.length?(qt(null),w("")):(qt(h),w(a[h]??""));return}}if(i.return){Zt();return}if(i.backspace||i.delete){C();return}if(i.escape){w(""),Ke(0),le(null),G([]),Bt(null);return}l&&!i.ctrl&&!i.meta&&Fr(l)}}}),Ue(()=>{if(N||F)return;let l=qe.current.shift();l!==void 0&&(Yn([...qe.current]),Zt(l))},[N,F,Zt]),W(K,{flexDirection:"column",width:Be,children:[Kn!==null&&W(K,{marginTop:1,flexDirection:"column",children:[Kn.truncated&&R(S,{dimColor:!0,children:"\u2026"}),R(S,{children:Kn.text})]}),N&&(Rr?R(cp,{p:Rr}):R(ap,{startTime:Oe.current,chars:Sa})),R(K,{borderStyle:"round",borderColor:Ir.prod?"yellow":H,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?qr.map((l,i)=>{let a=b.text.slice(l.start,l.end),h=i===Wn(qr,b.pos),d=Math.min(b.pos,l.end)-l.start;return W(S,{children:[R(S,{color:H,children:i===0?"> ":" "}),h?W(br,{children:[a.slice(0,d),R(Hn,{ch:a[d]??" "}),a.slice(d+1)]}):a||" "]},`${i}-${l.start}`)}):W(S,{children:[R(S,{color:H,children:"> "}),ke&&!N?W(br,{children:[R(Hn,{ch:ke[0],dim:!0}),R(S,{color:"gray",children:ke.slice(1)}),R(S,{dimColor:!0,children:" (tab)"})]}):Xn.isSetup||!Ta?W(br,{children:[R(Hn,{ch:Xn.text[0],dim:!0}),R(S,{color:"gray",children:Xn.text.slice(1)})]}):R(Hn,{ch:" "})]})}),Sr.length>0&&R(K,{flexDirection:"column",paddingX:1,children:Sr.map((l,i)=>R(S,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Me?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Select model"}),R(S,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),xe.map((l,i)=>W(S,{color:i===Me.cursor?H:void 0,children:[i===Me.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Me.current?" \u2714":""}`.padEnd(16),R(S,{color:"gray",children:l.desc})]},l.label)),R(S,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Ce?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Switch connection profile"}),Ce.rows.map((l,i)=>W(S,{color:i===Ce.cursor?H:void 0,children:[i===Ce.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Ce.current?" \u2714":""}`.padEnd(20),R(S,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?R(S,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),R(S,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):De?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Pick your Document360 environment"}),De.rows.map((l,i)=>W(S,{color:i===De.cursor?H:void 0,children:[i===De.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),R(S,{color:"gray",children:l.apiUrl})]},l.name)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):se?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Switch workspace"}),R(S,{dimColor:!0,children:`environment ${se.environment} \xB7 project ${se.projectName??`${se.projectId.slice(0,8)}\u2026`}`}),se.rows.map((l,i)=>W(S,{color:i===se.cursor?H:void 0,children:[i===se.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===se.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.type??""})]},l.id)),R(S,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):he?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Choose project"}),R(S,{dimColor:!0,children:`environment ${he.environment}`}),he.rows.map((l,i)=>W(S,{color:i===he.cursor?H:void 0,children:[i===he.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===he.current?" \u2714":""}`.padEnd(30),R(S,{color:"gray",children:l.sub??""})]},l.id)),R(S,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ce?(()=>{let i=Math.min(Math.max(0,ce.cursor-Math.floor(7)),Math.max(0,ce.rows.length-14)),a=ce.rows.slice(i,i+14),h=ce.rows.filter(d=>d.checked).length;return W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ce.rows.length})`}),i>0?R(S,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((d,m)=>{let y=i+m;return W(S,{color:y===ce.cursor?H:void 0,children:[y===ce.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Be-34)),R(S,{color:"gray",children:$n(d)})]},d.path)}),i+14<ce.rows.length?R(S,{dimColor:!0,children:` \u2193 ${ce.rows.length-i-14} more`}):null,R(S,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():We?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),We.rows.map((l,i)=>{let a=i===We.cursor,h=l.indent?" ":" ",d=`${i+1}.`.padEnd(3);return W(S,{color:a?H:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${h}${d} ${l.label}`.padEnd(Math.min(56,Be-24)),l.note?R(S,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),R(S,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ge?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:`Preview article${ge.query?` \u2014 filter: ${ge.query}`:" (type to filter)"}`}),Yt.length===0?R(S,{color:"gray",children:"no articles match"}):Yt.map((l,i)=>W(S,{color:i===ge.cursor?H:void 0,children:[i===ge.cursor?"\u276F ":" ",l]},l)),R(S,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?W(K,{flexDirection:"column",paddingX:1,children:[R(S,{color:H,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),zt.length===0?R(S,{color:"gray",children:"no sessions match"}):zt.map((l,i)=>W(S,{color:i===ye.cursor?H:void 0,children:[i===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),R(S,{color:i===ye.cursor?H:"gray",children:l.firstPrompt.slice(0,Math.max(10,Be-40))})]},l.uuid)),R(S,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Nr?R(K,{flexDirection:"column",children:vt.map((l,i)=>W(S,{color:i===xt?H:void 0,children:[i===xt?"\u276F ":" ",l.usage.padEnd(22)," ",R(S,{color:i===xt?H:"gray",children:l.name==="model"&&zn?`${l.desc} (currently ${zn})`:l.desc})]},l.name))}):!D&&bt.length>0?W(K,{flexDirection:"column",paddingX:1,children:[Tr?R(S,{color:H,children:Tr}):null,bt.map((l,i)=>W(S,{children:[R(S,{color:H,children:i+1})," ",l.slice(0,Math.max(20,Be-5))]},l)),R(S,{dimColor:!0,children:`press 1-${bt.length} to fill the command \xB7 esc dismiss`})]}):R(K,{paddingX:1,children:W(S,{color:"gray",children:[Ir.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${zn??"model n/a"}${t.kind==="api"?jr>0?` \xB7 ${ae(jr)}`:"":Dr>0?` \xB7 ${Ie(Dr)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}L();import{jsx as pp}from"react/jsx-runtime";async function va(e=process.cwd(),t="auto",n,o="0.0.0"){let r=dp(t);r.kind==="none"&&(console.error(""),console.error(x("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${A("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${A("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=up(pp($a,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
267
267
|
`),process.exit(0)}var gp=mp(import.meta.url),Ca=gp("../package.json"),Se=new fp;function $r(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Se.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{$r(e),await rn({profile:e.profile,manual:e.manual})});Se.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{$r(e),await ts({profile:e.profile})});Se.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{$r(e),await es({profile:e.profile})});var vr=Se.command("profile").description("Manage connection profiles for the current repo");vr.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>sn(process.cwd()));vr.command("use <name>").description("Set the default profile for this repo").action(e=>an(process.cwd(),e));vr.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>ln(process.cwd(),e));var Pa=Se.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Pa.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ut(process.cwd(),e.profile));Pa.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Vr(process.cwd(),e,t.profile)});Se.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>os());Se.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(Tn(),wi)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Se.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Ca.version,"-v, --version").option("-p, --prompt <text>","One-shot prompt mode (non-interactive)").option("-r, --resume <name>","Resume a saved session (with --prompt; use /resume inside the REPL)").option("-C, --cwd <dir>","Working directory",process.cwd()).option("--auth <mode>","Auth mode: auto | api | subscription","auto").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--yes","Skip the production write confirmation (for one-shot/CI)").option("--classic","Use the plain readline REPL instead of the Ink TUI").action(async e=>{if(hp.includes(e.auth)||(console.error(`\u2717 Invalid --auth mode: ${e.auth}`),console.error("Run: d360-writer --auth auto | api | subscription"),process.exit(2)),e.prompt){await rs(e.cwd,e.prompt,e.auth,e.resume,e.profile,e.yes);return}e.resume&&(console.error("\u2717 --resume requires --prompt. In the interactive REPL, use /resume instead."),process.exit(2)),e.classic||!process.stdin.isTTY?await Gi(e.cwd,e.auth,e.profile):await va(e.cwd,e.auth,e.profile,Ca.version)});Se.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|
package/package.json
CHANGED