document360-writer 0.4.14 → 0.4.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +56 -52
- package/dist/commands/convert.d.ts +2 -1
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,70 +1,74 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Kr=Object.defineProperty;var rn=(e,t,o)=>()=>{if(o)throw o[0];try{return e&&(t=e(e=0)),t}catch(n){throw o=[n],n}};var Qr=(e,t)=>{for(var o in t)Kr(e,o,{get:t[o],enumerable:!0})};import ye from"picocolors";var W,Zr,es,ts,sn,Ke,c,$,E,S,y,Y,ne,M=rn(()=>{"use strict";W="#7f56d9",[Zr,es,ts]=[127,86,217],sn=e=>ye.isColorSupported?`\x1B[38;2;${Zr};${es};${ts}m${e}\x1B[39m`:e,Ke=e=>ye.bold(sn(e)),c=e=>ye.dim(e),$=e=>ye.red(e),E=e=>ye.yellow(e),S=e=>ye.green(e),y=sn,Y=e=>ye.gray(e),ne=e=>ye.bold(e)});var sr={};Qr(sr,{doctorCommand:()=>rt,renderDoctorChecks:()=>rr,runDoctorChecks:()=>nr});import{existsSync as Ii}from"node:fs";import{d360GetAll as Ei,getAccessToken as Di,isExpired as Do,loadProfileMap as Mi,loadTokens as _i,packageSkillsDir as or,projectConfigPath as Li,readProjectConfig as Ni,resolveActiveProfile as Oi,resolveAuth as Ui,resolveModelSetting as Wi}from"document360-engine";async function nr(e){let t=[],o=Number(process.versions.node.split(".")[0]);t.push(o>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let n=Ui("auto");t.push(n.kind==="none"?{level:"fail",label:"Claude auth: not configured",fix:"Set ANTHROPIC_API_KEY, or sign in to Claude Code once (subscription reuse)"}:{level:"ok",label:`Claude auth: ${n.kind==="api"?"API key":"subscription"}`});let r=Wi(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=Ni(e);if(!s)return t.push({level:"fail",label:`No ${Li(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let u=(s.docsDir??"user-docs").replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${u}/, markdown, capture specs, and d360 config`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Docs scope: ${p.length} folder(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Docs scope not set (authoritativeSourceFiles empty)",fix:"Run: /scope to choose which folders back the docs"});let k;try{k=Oi(e),t.push({level:"ok",label:`Profile: ${k.name} (${k.connection.name})${k.production?" \u26A0 PRODUCTION":""}`})}catch(T){return t.push({level:"fail",label:`Profile config: ${T.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let f=_i(k.name);f?Do(f)&&!f.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Do(f)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(f.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${k.name})`}),t.push(k.project.workspaceId?{level:"ok",label:`Workspace: ${k.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Mi(e,k.name);if(x?x.projectId&&k.project.projectId&&x.projectId!==k.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${k.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"warn",label:`No d360-category-map.json section for "${k.name}" (created on first /publish)`}),t.push(Ii(or())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${or()}`,fix:"Reinstall document360-writer (broken install)"}),f&&(!Do(f)||f.refreshToken)){let T={profile:k.name,connection:k.connection};try{await Di(T);let b=await Ei(T,"/v3/projects");t.push({level:"ok",label:`API reachable (${k.connection.apiUrl}) \u2014 ${b.length} project(s) visible`})}catch(b){t.push({level:"fail",label:`API call failed: ${b.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function rr(e){let t=[""];for(let r of e){let s=r.level==="ok"?S("\u2713"):r.level==="warn"?E("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?c(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${c("fix:")} ${y(r.fix)}`)}let o=e.filter(r=>r.level==="fail").length,n=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(o===0?S(`\u2713 ${n===0?"All checks passed":`Healthy (${n} warning${n===1?"":"s"})`}`):$(`\u2717 ${o} problem${o===1?"":"s"} found`)),t.push(""),t}async function rt(e,t){console.log(c("Running checks\u2026"));for(let o of rr(await nr(t.cwd)))console.log(o);return{kind:"continue"}}var Mt=rn(()=>{"use strict";M()});import{Command as na}from"commander";import{createRequire as ra}from"node:module";import{AUTH_MODES as sa}from"document360-engine";import{input as ds}from"@inquirer/prompts";import{loginPkce as ps,refreshTokens as ms,toStoredTokens as un,clearTokens as fs,decodeJwtClaims as cn,isExpired as gs,loadTokens as hs,saveTokens as dn,resolveActiveProfile as $t,setProfileProject as ks,readProjectConfig as ws}from"document360-engine";M();import{select as os}from"@inquirer/prompts";import{resolveActiveProfile as ns,setProfileProject as rs,resolveProjectId as ss,listWorkspaces as is}from"document360-engine";async function yt(e,t){let o=ns(e,t),n={profile:o.name,connection:o.connection},r=o.project.projectId??ss(n);return{workspaces:await is(n,r),projectId:r,profile:o.name,environment:o.connection.name,current:o.project.workspaceId}}var ln=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function lo(e,t){let o=t.toLowerCase();return e.find(n=>(n.name??"").toLowerCase()===o)??e.find(n=>(n.name??"").toLowerCase().startsWith(o))??e.find(n=>n.id.startsWith(t))}function xt(e,t,o,n){rs(e,t,{projectId:o,workspaceId:n})}async function an(e,t,o){let n;try{n=await yt(e,o)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=lo(n.workspaces,t);return r?(xt(e,n.profile,n.projectId,r.id),console.log(S(`\u2713 Workspace set to "${r.name??r.id}" for profile "${n.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${n.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function He(e,t){let o;try{o=await yt(e,t)}catch(f){console.log($(`Could not list workspaces: ${f.message}`));return}let{workspaces:n,projectId:r,profile:s,current:u}=o;if(n.length===0){console.log(c("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let f of n)console.log(` ${f.id===u?y("\u25CF"):" "} ${ln(f)} ${c(f.id)}`);console.log(c("Run: d360-writer workspace use <name>"));return}let p=await os({message:"Select the Document360 workspace for this repo:",choices:n.map(f=>({name:`${ln(f)}${f.id===u?" (current)":""}`,value:f.id}))});xt(e,s,r,p);let k=n.find(f=>f.id===p);console.log(S(`\u2713 Workspace set to "${k?.name??p}" for profile "${s}".`))}M();import ls from"picocolors";function as(e=process.env){return e.FORCE_HYPERLINK==="0"||!ls.isColorSupported?!1:e.FORCE_HYPERLINK?!0:!!(e.WT_SESSION||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="WezTerm"||e.TERM_PROGRAM==="ghostty"||e.VTE_VERSION||e.KONSOLE_VERSION)}function cs(e,t=e,o){return as(o)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var us=/https?:\/\/[^\s\x1b]+/g;function Qe(e,t){return e.replace(us,o=>cs(o,o,t))}function pn(e){return{...cn(e.idToken)??{},...cn(e.accessToken)??{}}}function bt(e){let t=pn(e),o=t.email??t.preferred_username??t.sub??"unknown",n=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${o}${n}`}async function vt(e){let t=$t(process.cwd(),e.profile),o=t.connection;console.log(c(`Profile "${t.name}" \u2192 ${o.name} (${o.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let n=await ps(o,{manual:e.manual,promptForRedirect:s=>ds({message:s})},s=>console.log(Qe(s))),r=un(t.name,n);if(dn(r),ao(r,t.name,s=>console.log(c(s))),console.log(""),console.log(S(`\u2713 Logged in to "${t.name}" as ${bt(r)}`)),console.log(c(` access token expires: ${r.expiresAt}`)),console.log(c(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{ws(process.cwd())?.profiles?.[t.name]&&(console.log(""),await He(process.cwd(),t.name))}catch{}}function ao(e,t,o){let r=pn(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if($t(process.cwd(),t).project.projectId)return;ks(process.cwd(),t,{projectId:r}),o(` Project ${r} written to profile "${t}".`)}catch{}}async function mn(e){let t=$t(process.cwd(),e.profile),o=t.connection,n=hs(t.name);if(!n){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(c(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${y(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${bt(n)}`),gs(n))if(n.refreshToken)try{let r=un(t.name,await ms(o,n.refreshToken));dn(r),console.log(S(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(E(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(c(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(E("Session expired (no refresh token).")),console.log(c(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(c(` expires: ${n.expiresAt}`))}async function fn(e){let t=$t(process.cwd(),e.profile);fs(t.name)?console.log(S(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(c(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}M();import{readProjectConfig as gn,writeProjectConfig as ys,resolveActiveProfile as xs,loadTokens as $s,isExpired as bs}from"document360-engine";function Ct(e){let t=gn(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[o,n]of Object.entries(t.profiles)){let r=o===t.defaultProfile?y("\u25CF "):" ",s=n.production?E(" \u26A0 PRODUCTION"):"",u=n.connection.environment??"(inline)",p=$s(o),k=p?bs(p)&&!p.refreshToken?E("expired"):c("logged in"):c("not logged in");console.log(`${r}${y(o)} \u2192 ${u}${s} [${k}]`)}console.log(""),console.log(c("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Pt(e,t){let o=gn(e);if(!o?.profiles?.[t]){let r=o?.profiles?Object.keys(o.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}o.defaultProfile=t,ys(o,e);let n=o.profiles[t].production?E(" \u26A0 PRODUCTION"):"";console.log(S(`\u2713 Default profile is now "${t}"${n}`))}function Tt(e,t){try{let o=xs(e,t);console.log(""),console.log(`Profile ${y(o.name)}${o.production?E(" \u26A0 PRODUCTION"):""}`),console.log(c(` api: ${o.connection.apiUrl}`)),console.log(c(` identity: ${o.connection.authorizationUrl}`)),console.log(c(` clientId: ${o.connection.clientId}`)),console.log(c(` scopes: ${o.connection.scopes.join(" ")}`)),console.log(c(` project: ${o.project.projectId??"(set at login)"}`)),console.log(c(` workspace:${o.project.workspaceId?" "+o.project.workspaceId:" (none)"}`)),console.log("")}catch(o){console.log($(o.message)),process.exitCode=1}}M();import{existsSync as vs,readdirSync as Cs,statSync as Ps}from"node:fs";import{join as Ts}from"node:path";import{apiLogDir as Ss}from"document360-engine";function hn(){let e=Ss();if(console.log(""),console.log(`Document360 API logs: ${y(e)}`),!vs(e)){console.log(c(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Cs(e).filter(o=>o.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(c(" No logs yet \u2014 they appear after the first Document360 API call."));for(let o of t.slice(0,14)){let n=(Ps(Ts(e,o)).size/1024).toFixed(1);console.log(` ${o} ${c(`${n} KB`)}`)}console.log(""),console.log(c("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(c("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}M();import{createSession as Rs,resolveAuth as js,findByName as As,slugify as Is,touchSession as Es,upsertSession as Ds,resolveActiveProfile as Ms}from"document360-engine";async function kn(e,t,o,n,r,s){let u=js(o);u.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${y("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${y("d360-writer --auth subscription")}`),process.exit(2)),u.kind==="subscription"&&console.error(c("Using your Claude subscription (no API key set)."));let p=null;try{p=Ms(e,r)}catch(b){console.error($(`Document360 profile error: ${b.message}`)),process.exit(2)}p.production&&(console.error(E(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(c(" --yes given \u2014 proceeding against production.")));let k;if(n){let b=As(e,n);b||(console.error($(`No saved session matches "${n}" in this repo.`)),console.error(c("List sessions inside the REPL with /resume.")),process.exit(2)),k=b.uuid,console.error(c(`Resuming "${b.name}"`))}let f=Rs({cwd:e,resume:k,profileName:r,allowProdWrites:s===!0}),x=k??null,T=1;for await(let b of f.send(t))switch(b.type){case"session":if(!x){x=b.sessionId;let j=new Date().toISOString();Ds({uuid:x,name:Is(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:j,updatedAt:j})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(Y(` \u2699 ${b.name}`));break;case"result":T=b.ok?0:1,console.error(c(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${b.message}`)),process.exit(1)}x&&Es(x),process.stdout.write(`
|
|
3
|
-
`),process.exit(T)}import{createInterface as
|
|
2
|
+
var Zr=Object.defineProperty;var an=(e,t,o)=>()=>{if(o)throw o[0];try{return e&&(t=e(e=0)),t}catch(n){throw o=[n],n}};var es=(e,t)=>{for(var o in t)Zr(e,o,{get:t[o],enumerable:!0})};import $e from"picocolors";var F,ts,os,ns,cn,et,c,$,D,S,y,X,re,L=an(()=>{"use strict";F="#7f56d9",[ts,os,ns]=[127,86,217],cn=e=>$e.isColorSupported?`\x1B[38;2;${ts};${os};${ns}m${e}\x1B[39m`:e,et=e=>$e.bold(cn(e)),c=e=>$e.dim(e),$=e=>$e.red(e),D=e=>$e.yellow(e),S=e=>$e.green(e),y=cn,X=e=>$e.gray(e),re=e=>$e.bold(e)});var ar={};es(ar,{doctorCommand:()=>at,renderDoctorChecks:()=>lr,runDoctorChecks:()=>ir});import{existsSync as Ei}from"node:fs";import{d360GetAll as Mi,getAccessToken as _i,isExpired as _o,loadProfileMap as Li,loadTokens as Ni,packageSkillsDir as sr,projectConfigPath as Oi,readProjectConfig as Ui,resolveActiveProfile as Wi,resolveAuth as Fi,resolveModelSetting as Bi}from"document360-engine";async function ir(e){let t=[],o=Number(process.versions.node.split(".")[0]);t.push(o>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let n=Fi("auto");t.push(n.kind==="none"?{level:"fail",label:"Claude auth: not configured",fix:"Set ANTHROPIC_API_KEY, or sign in to Claude Code once (subscription reuse)"}:{level:"ok",label:`Claude auth: ${n.kind==="api"?"API key":"subscription"}`});let r=Bi(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=Ui(e);if(!s)return t.push({level:"fail",label:`No ${Oi(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let u=(s.docsDir??"user-docs").replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${u}/, markdown, capture specs, and d360 config`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Docs scope: ${p.length} folder(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Docs scope not set (authoritativeSourceFiles empty)",fix:"Run: /scope to choose which folders back the docs"});let h;try{h=Wi(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(T){return t.push({level:"fail",label:`Profile config: ${T.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let f=Ni(h.name);f?_o(f)&&!f.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):_o(f)?t.push({level:"warn",label:"Document360: token expired \u2014 will auto-refresh on next call"}):t.push({level:"ok",label:`Document360: logged in (until ${new Date(f.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let x=Li(e,h.name);if(x?x.projectId&&h.project.projectId&&x.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${x.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(x.articles).length} articles, ${Object.keys(x.categories).length} categories`}):t.push({level:"warn",label:`No d360-category-map.json section for "${h.name}" (created on first /publish)`}),t.push(Ei(sr())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${sr()}`,fix:"Reinstall document360-writer (broken install)"}),f&&(!_o(f)||f.refreshToken)){let T={profile:h.name,connection:h.connection};try{await _i(T);let v=await Mi(T,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.connection.apiUrl}) \u2014 ${v.length} project(s) visible`})}catch(v){t.push({level:"fail",label:`API call failed: ${v.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function lr(e){let t=[""];for(let r of e){let s=r.level==="ok"?S("\u2713"):r.level==="warn"?D("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?c(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${c("fix:")} ${y(r.fix)}`)}let o=e.filter(r=>r.level==="fail").length,n=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(o===0?S(`\u2713 ${n===0?"All checks passed":`Healthy (${n} warning${n===1?"":"s"})`}`):$(`\u2717 ${o} problem${o===1?"":"s"} found`)),t.push(""),t}async function at(e,t){console.log(c("Running checks\u2026"));for(let o of lr(await ir(t.cwd)))console.log(o);return{kind:"continue"}}var Nt=an(()=>{"use strict";L()});import{Command as la}from"commander";import{createRequire as aa}from"node:module";import{AUTH_MODES as ca}from"document360-engine";import{input as ms}from"@inquirer/prompts";import{loginPkce as fs,refreshTokens as gs,toStoredTokens as mn,clearTokens as hs,decodeJwtClaims as pn,isExpired as ks,loadTokens as ws,saveTokens as fn,resolveActiveProfile as Ct,setProfileProject as ys,readProjectConfig as xs}from"document360-engine";L();import{select as rs}from"@inquirer/prompts";import{resolveActiveProfile as ss,setProfileProject as is,resolveProjectId as ls,listWorkspaces as as}from"document360-engine";async function bt(e,t){let o=ss(e,t),n={profile:o.name,connection:o.connection},r=o.project.projectId??ls(n);return{workspaces:await as(n,r),projectId:r,profile:o.name,environment:o.connection.name,current:o.project.workspaceId}}var un=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function uo(e,t){let o=t.toLowerCase();return e.find(n=>(n.name??"").toLowerCase()===o)??e.find(n=>(n.name??"").toLowerCase().startsWith(o))??e.find(n=>n.id.startsWith(t))}function vt(e,t,o,n){is(e,t,{projectId:o,workspaceId:n})}async function dn(e,t,o){let n;try{n=await bt(e,o)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=uo(n.workspaces,t);return r?(vt(e,n.profile,n.projectId,r.id),console.log(S(`\u2713 Workspace set to "${r.name??r.id}" for profile "${n.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${n.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function qe(e,t){let o;try{o=await bt(e,t)}catch(f){console.log($(`Could not list workspaces: ${f.message}`));return}let{workspaces:n,projectId:r,profile:s,current:u}=o;if(n.length===0){console.log(c("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let f of n)console.log(` ${f.id===u?y("\u25CF"):" "} ${un(f)} ${c(f.id)}`);console.log(c("Run: d360-writer workspace use <name>"));return}let p=await rs({message:"Select the Document360 workspace for this repo:",choices:n.map(f=>({name:`${un(f)}${f.id===u?" (current)":""}`,value:f.id}))});vt(e,s,r,p);let h=n.find(f=>f.id===p);console.log(S(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}L();import cs from"picocolors";function us(e=process.env){return e.FORCE_HYPERLINK==="0"||!cs.isColorSupported?!1:e.FORCE_HYPERLINK?!0:!!(e.WT_SESSION||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="WezTerm"||e.TERM_PROGRAM==="ghostty"||e.VTE_VERSION||e.KONSOLE_VERSION)}function ds(e,t=e,o){return us(o)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var ps=/https?:\/\/[^\s\x1b]+/g;function tt(e,t){return e.replace(ps,o=>ds(o,o,t))}function gn(e){return{...pn(e.idToken)??{},...pn(e.accessToken)??{}}}function Pt(e){let t=gn(e),o=t.email??t.preferred_username??t.sub??"unknown",n=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${o}${n}`}async function Tt(e){let t=Ct(process.cwd(),e.profile),o=t.connection;console.log(c(`Profile "${t.name}" \u2192 ${o.name} (${o.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let n=await fs(o,{manual:e.manual,promptForRedirect:s=>ms({message:s})},s=>console.log(tt(s))),r=mn(t.name,n);if(fn(r),po(r,t.name,s=>console.log(c(s))),console.log(""),console.log(S(`\u2713 Logged in to "${t.name}" as ${Pt(r)}`)),console.log(c(` access token expires: ${r.expiresAt}`)),console.log(c(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{xs(process.cwd())?.profiles?.[t.name]&&(console.log(""),await qe(process.cwd(),t.name))}catch{}}function po(e,t,o){let r=gn(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ct(process.cwd(),t).project.projectId)return;ys(process.cwd(),t,{projectId:r}),o(` Project ${r} written to profile "${t}".`)}catch{}}async function hn(e){let t=Ct(process.cwd(),e.profile),o=t.connection,n=ws(t.name);if(!n){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(c(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${y(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Pt(n)}`),ks(n))if(n.refreshToken)try{let r=mn(t.name,await gs(o,n.refreshToken));fn(r),console.log(S(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(D(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(c(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(D("Session expired (no refresh token).")),console.log(c(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(c(` expires: ${n.expiresAt}`))}async function kn(e){let t=Ct(process.cwd(),e.profile);hs(t.name)?console.log(S(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(c(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}L();import{readProjectConfig as wn,writeProjectConfig as $s,resolveActiveProfile as bs,loadTokens as vs,isExpired as Cs}from"document360-engine";function St(e){let t=wn(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[o,n]of Object.entries(t.profiles)){let r=o===t.defaultProfile?y("\u25CF "):" ",s=n.production?D(" \u26A0 PRODUCTION"):"",u=n.connection.environment??"(inline)",p=vs(o),h=p?Cs(p)&&!p.refreshToken?D("expired"):c("logged in"):c("not logged in");console.log(`${r}${y(o)} \u2192 ${u}${s} [${h}]`)}console.log(""),console.log(c("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Rt(e,t){let o=wn(e);if(!o?.profiles?.[t]){let r=o?.profiles?Object.keys(o.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}o.defaultProfile=t,$s(o,e);let n=o.profiles[t].production?D(" \u26A0 PRODUCTION"):"";console.log(S(`\u2713 Default profile is now "${t}"${n}`))}function jt(e,t){try{let o=bs(e,t);console.log(""),console.log(`Profile ${y(o.name)}${o.production?D(" \u26A0 PRODUCTION"):""}`),console.log(c(` api: ${o.connection.apiUrl}`)),console.log(c(` identity: ${o.connection.authorizationUrl}`)),console.log(c(` clientId: ${o.connection.clientId}`)),console.log(c(` scopes: ${o.connection.scopes.join(" ")}`)),console.log(c(` project: ${o.project.projectId??"(set at login)"}`)),console.log(c(` workspace:${o.project.workspaceId?" "+o.project.workspaceId:" (none)"}`)),console.log("")}catch(o){console.log($(o.message)),process.exitCode=1}}L();import{existsSync as Ps,readdirSync as Ts,statSync as Ss}from"node:fs";import{join as Rs}from"node:path";import{apiLogDir as js}from"document360-engine";function yn(){let e=js();if(console.log(""),console.log(`Document360 API logs: ${y(e)}`),!Ps(e)){console.log(c(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ts(e).filter(o=>o.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(c(" No logs yet \u2014 they appear after the first Document360 API call."));for(let o of t.slice(0,14)){let n=(Ss(Rs(e,o)).size/1024).toFixed(1);console.log(` ${o} ${c(`${n} KB`)}`)}console.log(""),console.log(c("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(c("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}L();import{createSession as As,resolveAuth as Is,findByName as Ds,slugify as Es,touchSession as Ms,upsertSession as _s,resolveActiveProfile as Ls}from"document360-engine";async function xn(e,t,o,n,r,s){let u=Is(o);u.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${y("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${y("d360-writer --auth subscription")}`),process.exit(2)),u.kind==="subscription"&&console.error(c("Using your Claude subscription (no API key set)."));let p=null;try{p=Ls(e,r)}catch(v){console.error($(`Document360 profile error: ${v.message}`)),process.exit(2)}p.production&&(console.error(D(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(c(" --yes given \u2014 proceeding against production.")));let h;if(n){let v=Ds(e,n);v||(console.error($(`No saved session matches "${n}" in this repo.`)),console.error(c("List sessions inside the REPL with /resume.")),process.exit(2)),h=v.uuid,console.error(c(`Resuming "${v.name}"`))}let f=As({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),x=h??null,T=1;for await(let v of f.send(t))switch(v.type){case"session":if(!x){x=v.sessionId;let j=new Date().toISOString();_s({uuid:x,name:Es(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:j,updatedAt:j})}break;case"text":process.stdout.write(v.delta);break;case"tool":console.error(X(` \u2699 ${v.name}`));break;case"result":T=v.ok?0:1,console.error(c(`(${v.inputTokens}\u2192${v.outputTokens} tokens`+(v.costUsd>0?`, $${v.costUsd<.01?v.costUsd.toFixed(4):v.costUsd.toFixed(2)}`:"")+")")),v.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${v.message}`)),process.exit(1)}x&&Ms(x),process.stdout.write(`
|
|
3
|
+
`),process.exit(T)}import{createInterface as Ki}from"node:readline/promises";import{createSession as Oo,resolveAuth as Qi,getSession as Zi,setTitle as el,slugify as tl,touchSession as yr,upsertSession as ol,generateTitle as nl,resolveActiveProfile as xr,resolveModelSetting as rl,readProjectConfig as sl,decodeJwtClaims as kr,isExpired as il,loadTokens as ll}from"document360-engine";L();async function mo(){let e=["",re("document360-writer \u2014 slash commands"),"",` ${y("/help")} ${c("Show this help")}`,` ${y("/init")} ${c("Pick a Document360 environment & scaffold .d360-writer.json")}`,` ${y("/mcp add <name> <type> <ref>")} ${c("Register an MCP server (stdio|http|sse; -H key:value for auth)")}`,` ${y("/mcp list")} ${c("Show registered MCP servers")}`,` ${y("/mcp remove <name>")} ${c("Unregister an MCP server")}`,` ${y("/publish [path|--all]")} ${c("Publish to Document360 (no arg: pick; --all: every candidate)")}`,` ${y("/sync")} ${c("Drift report: local docs vs Document360 (no tokens)")}`,` ${y("/sync pull <path>|--all")} ${c("Pull portal edits into local markdown (diff + confirm)")}`,` ${y("/convert [--scope <f>] [--run]")} ${c("Convert tracked articles to DFM across parallel agents (--scope to limit; --run to start)")}`,` ${y("/scope")} ${c("Choose which repo folders back the docs (analyses + recommends)")}`,` ${y("/audit")} ${c("Gap analysis: code vs docs vs Document360 (incremental)")}`,` ${y("/screenshot <id>")} ${c("Emit a document360-capture-compatible spec")}`,` ${y("/resume [name]")} ${c("Resume a session (no arg: searchable picker)")}`,` ${y("/rename <name>")} ${c("Name the current session")}`,` ${y("/login")} ${c("Sign in to Document360 (browser) without leaving the session")}`,` ${y("/profile [name|add <name> [env]]")} ${c("Switch connection profile, or create one from a preset")}`,` ${y("/model [name|default]")} ${c("Show or set the Claude model (personal setting)")}`,` ${y("/doctor")} ${c("Health-check: auth, profile, workspace, map, API")}`,` ${y("/workspace [name]")} ${c("List or switch the Document360 workspace")}`,` ${y("/allow-prod")} ${c("Authorize writes to a production profile (this session)")}`,` ${y("/clear")} ${c("Reset conversation")}`,` ${y("/exit")} ${c("Quit")}`,"",c("Anything not starting with / is sent to the agent."),c("Reporting a problem? Run `d360-writer logs` from your shell for the API log files."),""];for(let t of e)console.log(t);return{kind:"continue"}}L();import{getSession as Ns}from"document360-engine";async function $n(e,t){let o=t.currentUuid(),n=o?Ns(o):void 0;return console.log(n?c(`
|
|
4
4
|
(conversation reset \u2014 "${n.name}" is still available via /resume)
|
|
5
5
|
`):c(`
|
|
6
6
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
7
|
-
`)),{kind:"clear"}}async function
|
|
7
|
+
`)),{kind:"clear"}}async function fo(){return{kind:"exit"}}L();import{input as ot,confirm as Os}from"@inquirer/prompts";import{basename as bn,join as go}from"node:path";import{existsSync as nt,readFileSync as Us,readdirSync as Ws}from"node:fs";import{writeProjectConfig as vn,readProjectConfig as Fs,projectConfigPath as Cn}from"document360-engine";function Pn(e,t="berlin"){let o=Cn(e);if(nt(o))return{created:!1,path:o,profileName:""};let n={projectId:Sn(e)??bn(e),captureDir:"user-docs/_capture",outputDir:"user-docs/_screenshots",profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:Rn(e)};return vn(n,e),{created:!0,path:o,profileName:t}}async function Tn(){let e=process.cwd(),t=Cn(e);if(nt(t)&&!await Os({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(c("init cancelled.")),{kind:"continue"};let o=Sn(e)??bn(e),n=await ot({message:"Project ID (used to scope sessions, screenshots, etc.):",default:o}),r=await ot({message:"Capture directory (where document360-capture .spec.ts files live):",default:"user-docs/_capture"}),s=await ot({message:"Screenshot output directory:",default:"user-docs/_screenshots"}),u=await ot({message:"Default connection profile name:",default:"berlin"}),p=await ot({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),h={projectId:n,captureDir:r,outputDir:s,profiles:{[u]:{connection:{environment:p},production:!1}},defaultProfile:u,authoritativeSourceFiles:Rn(e)},f=Fs(e);return f?.terminologyGlossary&&(h.terminologyGlossary=f.terminologyGlossary),vn(h,e),console.log(""),console.log(S(`\u2713 Wrote ${t}`)),console.log(""),console.log("Next:"),console.log(` ${y(`d360-writer login --profile ${u}`)} ${c("(sign in; pick the project)")}`),console.log(' Then ask the agent: "analyze this repo and propose a docs structure"'),console.log(""),{kind:"continue"}}function Sn(e){let t=go(e,"package.json");if(!nt(t))return null;try{return JSON.parse(Us(t,"utf8")).name??null}catch{return null}}function Rn(e){let t=[];for(let o of["README.md","ARCHITECTURE.md","CLAUDE.md"])nt(go(e,o))&&t.push(o);for(let o of["src","api","docs"]){let n=go(e,o);nt(n)&&!Bs(n)&&t.push(o)}return t}function Bs(e){try{return Ws(e,{withFileTypes:!0}).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).length>6}catch{return!1}}L();import{readMcpConfig as ho,writeMcpConfig as jn}from"document360-engine";async function At(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Hs(),{kind:"continue"}):t==="add"?(qs(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(zs(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(c("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Hs(){let e=ho(),t=Object.keys(e.servers);if(t.length===0){console.log(c(`
|
|
8
8
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
9
|
-
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let o of t){let n=e.servers[o];if(n.type==="stdio")console.log(` ${y(o)} ${c("(stdio)")} ${n.command} ${(n.args??[]).join(" ")}`);else{let r=Object.keys(n.headers??{}),s=r.length>0?c(` [headers: ${r.join(", ")}]`):"";console.log(` ${y(o)} ${c(`(${n.type})`)} ${n.url}${s}`)}}console.log("")}function
|
|
10
|
-
`)}var
|
|
11
|
-
`)}async function
|
|
12
|
-
`),display:"/audit"}}
|
|
9
|
+
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let o of t){let n=e.servers[o];if(n.type==="stdio")console.log(` ${y(o)} ${c("(stdio)")} ${n.command} ${(n.args??[]).join(" ")}`);else{let r=Object.keys(n.headers??{}),s=r.length>0?c(` [headers: ${r.join(", ")}]`):"";console.log(` ${y(o)} ${c(`(${n.type})`)} ${n.url}${s}`)}}console.log("")}function qs(e){let[t,o,...n]=e;if(!t||!o||n.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(o!=="stdio"&&o!=="http"&&o!=="sse"){console.log($(`Unknown transport: ${o}. Use stdio, http, or sse.`));return}let r=ho(),s;if(o==="stdio")s={type:"stdio",command:n[0],args:n.slice(1)};else{let u={};for(let p=1;p<n.length;p++)if(n[p]==="-H"||n[p]==="--header"){let h=n[++p],f=h?.match(/^([^:=]+)[:=](.+)$/);if(!f){console.log($(`-H expects key:value (no spaces). Got: ${h??"(nothing)"}`));return}u[f[1].trim()]=f[2].trim()}else{console.log($(`Unexpected argument: ${n[p]}. After the URL, only -H key:value is allowed.`));return}s={type:o,url:n[0],headers:Object.keys(u).length>0?u:void 0}}r.servers[t]=s,jn(r),console.log(""),console.log(S(`\u2713 Registered "${t}" (${o})`)),console.log(D(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(c(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function zs(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let o=ho();if(!o.servers[t]){console.log($(`No server named "${t}".`));return}delete o.servers[t],jn(o),console.log(S(`\u2713 Removed "${t}".`)),console.log(c(" Run /clear to drop it from the current session immediately."))}L();import{select as Gs}from"@inquirer/prompts";import{computeSyncStatus as An}from"document360-engine";function Dt(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(`
|
|
10
|
+
`)}var In={"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 In).map(t=>({path:t.path,label:In[t.status]}))}function rt(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(`
|
|
11
|
+
`)}async function Dn(e,t){let o=e[0];if(o==="--all"){console.log(c("Checking what needs publishing\u2026"));try{let n=It((await An({cwd:t?.cwd??process.cwd()})).entries);return n.length===0?(console.log(S("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):{kind:"forward-to-agent",prompt:rt(n.map(r=>r.path)),display:"/publish --all"}}catch(n){return console.log($(`Could not compute sync status: ${n.message}`)),{kind:"continue"}}}if(!o){console.log(c("Checking what needs publishing\u2026"));let n;try{n=It((await An({cwd:t?.cwd??process.cwd()})).entries)}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),console.log(c("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(n.length===0)return console.log(S("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(c(" (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 n)console.log(` ${r.path} ${c(`(${r.label})`)}`);return console.log(c("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Gs({message:"Publish which article?",choices:[...n.length>1?[{name:`All ${n.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...n.map(r=>({name:r.path,value:r.path,description:r.label}))]}))}catch{return console.log(c("Cancelled.")),{kind:"continue"}}if(o==="--all")return{kind:"forward-to-agent",prompt:rt(n.map(r=>r.path)),display:"/publish --all"}}return{kind:"forward-to-agent",prompt:Dt(o),display:`/publish ${o}`}}async function Et(){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.","3. Map changed files 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.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
|
|
12
|
+
`),display:"/audit"}}L();import{checkbox as Vs}from"@inquirer/prompts";import{inventoryRepo as Ys,readProjectConfig as En,writeProjectConfig as Xs}from"document360-engine";function ko(e,t){let o=En(e);o&&(o.authoritativeSourceFiles=t,Xs(o,e))}function Mt(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 Mn(e,t){let o=t?.cwd??process.cwd();if(!En(o))return console.log($("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let n=Ys(o);if(n.length===0)return console.log(c('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(y("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of n)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${c(Mt(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>Vs({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:n.map(s=>({name:`${s.path} (${Mt(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(c("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(c("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};ko(o,r),console.log(S(`\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 ei}from"@inquirer/prompts";import{applyPull as Un,computeSyncStatus as Wn,planPull as ti,D360AuthError as oi}from"document360-engine";L();var _n=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:D,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:y,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:$,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:$,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:X,mark:"X"},{status:"untracked-local",header:"Untracked local articles \u2014 publish to start tracking:",paint:c,mark:"?"},{status:"untracked-remote",header:"Untracked Document360 articles \u2014 no local file maps to them:",paint:c,mark:"?"},{status:"unknown-base",header:"No sync base recorded yet \u2014 the next /publish or /sync pull of each records one:",paint:X,mark:"\xB7"}];function Js(e){return e.path?e.path:`${e.title??"(untitled)"} ${X(`[${e.articleId}]`)}`}function _t(e){let t=[];for(let u of _n){let p=e.entries.filter(h=>h.status===u.status);if(p.length!==0){t.push(""),t.push(re(u.header));for(let h of p)t.push(` ${u.paint(u.mark)} ${u.paint(Js(h))}${h.detail?X(` (${h.detail})`):""}`)}}let o=e.counts["in-sync"]??0,n=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=n===o?S("\u2713 everything in sync"):[o>0?S(`\u2713 ${o} in sync`):null,..._n.map(u=>{let p=e.counts[u.status]??0;return p>0?`${p} ${r[u.status]}`:null})].filter(Boolean).join(X(" \xB7 "));return t.push(s+X(` \xB7 ${n} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as Ks}from"diff";import Ln from"picocolors";var Nn=80,Qs="\x1B[48;2;74;28;28m",Zs="\x1B[48;2;24;66;24m",On="\x1B[49m",wo=e=>String(e).padStart(5);function Ee(e,t,o){let n=v=>{let j=v.replace(/\r\n/g,`
|
|
13
13
|
`);return j.endsWith(`
|
|
14
14
|
`)||j===""?j:j+`
|
|
15
|
-
`},r=n(e),s=n(t);if(r===s)return null;let u=Math.max(20,o-10),p=
|
|
16
|
-
`),o=[],n=0;for(;n<t.length;){let r=t[n];if(/^\s*```/.test(r)){let p=[];for(n++;n<t.length&&!/^\s*```/.test(t[n]);)p.push(t[n++]);n++,o.push({kind:"code",lines:p});continue}if(
|
|
17
|
-
`)}),
|
|
18
|
-
`)},j=[x("\u250C","\u252C","\u2510"),
|
|
19
|
-
`)}function
|
|
15
|
+
`},r=n(e),s=n(t);if(r===s)return null;let u=Math.max(20,o-10),p=Ks("a","b",r,s,"","",{context:3}),h=0,f=0,x=[];p.hunks.forEach((v,j)=>{j>0&&x.push(Ln.gray(" \u2026"));let O=v.oldStart,_=v.newStart;for(let H of v.lines){let B=H[0],ee=H.slice(1).slice(0,u);B==="-"?(f++,x.push(`${Qs}${wo(O++)} - ${ee}${On}`)):B==="+"?(h++,x.push(`${Zs}${wo(_++)} + ${ee}${On}`)):(x.push(Ln.gray(wo(_))+" "+ee),O++,_++)}});let T=x.slice(0,Nn);return{added:h,removed:f,lines:T,hidden:Math.max(0,x.length-Nn)}}async function Fn(e,t){let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await ni(t.cwd),{kind:"continue"};if(o==="pull")return await ri(t,e.slice(1)),{kind:"continue"};console.log($(`Unknown subcommand: /sync ${o}`)),console.log(c("Usage: /sync drift report (local vs Document360)")),console.log(c(" /sync pull <path> pull portal edits into the local file")),console.log(c(" /sync pull --all pull every remote-ahead article"))}catch(n){n instanceof oi?console.log($(n.message)):console.log($(`Sync failed: ${n.message}`))}return{kind:"continue"}}async function ni(e){console.log(c("Checking Document360 for drift\u2026"));let t=await Wn({cwd:e});for(let o of _t(t))console.log(o);console.log("")}async function ri(e,t){let o=t[0];if(!o){console.log($("Usage: /sync pull <article-path> | --all"));return}let n;if(o==="--all"){if(console.log(c("Checking Document360 for drift\u2026")),n=(await Wn({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),n.length===0){console.log(S("\u2713 Nothing is remote-ahead \u2014 no pulls needed.")),console.log(c(" (conflicts are never bulk-pulled; pull them one by one: /sync pull <path>)"));return}console.log(`${re(String(n.length))} article(s) are remote-ahead.`)}else n=[o.replace(/\\/g,"/")];for(let r of n){let s=await ti({cwd:e.cwd,relPath:r});console.log(""),console.log(`${y("\u25CF")} ${re(s.title)} ${X(`(${s.path})`)}`);for(let f of s.notes)console.log(D(` \u26A0 ${f}`));s.overwritesLocalChanges&&console.log(D(" \u26A0 This OVERWRITES local edits made since the last sync."));let u=Ee(s.oldContent,s.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!u){console.log(c(" Local file already matches the remote content \u2014 advancing the sync base only.")),Un({cwd:e.cwd},s);continue}let p=f=>f===1?"":"s";console.log(X(` \u23BF Added ${u.added} line${p(u.added)}, removed ${u.removed} line${p(u.removed)}`));for(let f of u.lines)console.log(f);if(u.hidden>0&&console.log(c(` \u2026 +${u.hidden} more diff lines`)),!await e.withPausedInput(()=>ei({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(c(" Skipped."));continue}Un({cwd:e.cwd},s),console.log(S(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}L();import{statSync as gi}from"node:fs";import{resolve as hi}from"node:path";import{estimateBulkCost as ki,planPartitions as wi,readProjectConfig as yi,resolveModelForOperation as xi,runPartitioned as $i,trackedArticlePaths as bi}from"document360-engine";import N from"picocolors";import Vn from"wrap-ansi";import Co from"string-width";L();import be from"picocolors";import yo from"wrap-ansi";import xo from"string-width";var Bn=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Hn=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),qn=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function si(e){let t=e.replace(/\r/g,"").split(`
|
|
16
|
+
`),o=[],n=0;for(;n<t.length;){let r=t[n];if(/^\s*```/.test(r)){let p=[];for(n++;n<t.length&&!/^\s*```/.test(t[n]);)p.push(t[n++]);n++,o.push({kind:"code",lines:p});continue}if(Bn(r)){o.push({kind:"hr"}),n++;continue}if(r.includes("|")&&n+1<t.length&&Hn(t[n+1])){let p=qn(r);n+=2;let h=[];for(;n<t.length&&t[n].includes("|")&&t[n].trim()!=="";)h.push(qn(t[n++]));o.push({kind:"table",header:p,rows:h});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){o.push({kind:"heading",level:s[1].length,text:s[2]}),n++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;n<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[n]);)p.push(t[n++].replace(/^\s*([-*]|\d+\.)\s+/,""));o.push({kind:"list",items:p});continue}if(r.trim()===""){n++;continue}let u=[];for(;n<t.length&&t[n].trim()!==""&&!/^\s*```/.test(t[n])&&!/^(#{1,6})\s/.test(t[n])&&!/^\s*([-*]|\d+\.)\s+/.test(t[n])&&!Bn(t[n])&&!(t[n].includes("|")&&n+1<t.length&&Hn(t[n+1]));)u.push(t[n++]);o.push({kind:"para",text:u.join(" ")})}return o}function $o(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?be.bold(t.slice(2,-2)):t.startsWith("`")?y(t.slice(1,-1)):be.italic(t.slice(1,-1)))}var ii=(e,t)=>e+" ".repeat(Math.max(0,t-xo(e)));function li(e,t,o){let n=e.length,r=e.map((O,_)=>Math.max(xo(O),...t.map(H=>xo(H[_]??"")))),s=Math.max(24,o),u=3*n+1,p=[...r],h=()=>p.reduce((O,_)=>O+_,0)+u,f=0;for(;h()>s&&f++<1e4;){let O=-1,_=6;for(let H=0;H<n;H++)p[H]>_&&(_=p[H],O=H);if(O===-1)break;p[O]-=1}let x=(O,_,H)=>be.gray(O+p.map(B=>"\u2500".repeat(B+2)).join(_)+H),T=be.gray("\u2502"),v=(O,_)=>{let H=p.map((se,ke)=>{let ie=O[ke]??"",le=_?be.bold(ie):$o(ie);return yo(le,se,{hard:!0}).split(`
|
|
17
|
+
`)}),B=Math.max(...H.map(se=>se.length)),ee=[];for(let se=0;se<B;se++)ee.push(p.map((ke,ie)=>`${T} ${ii(H[ie][se]??"",ke)} `).join("")+T);return ee.join(`
|
|
18
|
+
`)},j=[x("\u250C","\u252C","\u2510"),v(e,!0)];return j.push(t.length===0?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524")),t.forEach((O,_)=>{j.push(v(O,!1)),j.push(_===t.length-1?x("\u2514","\u2534","\u2518"):x("\u251C","\u253C","\u2524"))}),j.join(`
|
|
19
|
+
`)}function ai(e,t){switch(e.kind){case"heading":return be.bold(e.text);case"hr":return be.gray("\u2500".repeat(t));case"para":return yo($o(e.text),t);case"list":return e.items.map(o=>{let[n="",...r]=yo($o(o),Math.max(10,t-4)).split(`
|
|
20
20
|
`);return" \u2022 "+n+r.map(s=>`
|
|
21
21
|
`+s).join("")}).join(`
|
|
22
|
-
`);case"code":return e.lines.map(o=>
|
|
23
|
-
`);case"table":return
|
|
22
|
+
`);case"code":return e.lines.map(o=>be.gray(" "+o)).join(`
|
|
23
|
+
`);case"table":return li(e.header,e.rows,t)}}function bo(e,t){let o=Math.max(20,t);return si(e).map(n=>ai(n,o)).join(`
|
|
24
24
|
|
|
25
|
-
`)}
|
|
26
|
-
`);let r=2,s=3,u
|
|
27
|
-
`);let
|
|
28
|
-
`)}var
|
|
29
|
-
`).flatMap(f=>
|
|
30
|
-
`)),
|
|
31
|
-
`+p.map((f,x)=>n+(x===0?y(" \u276F "):" ")+f+" ".repeat(Math.max(0,s
|
|
25
|
+
`)}L();import ci from"picocolors";var ui=[127,86,217],di=[22,38,43],zn={T:ui,E:di},st=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],vo=([e,t,o])=>`\x1B[38;2;${e};${t};${o}m`,pi=([e,t,o])=>`\x1B[48;2;${e};${t};${o}m`;function Gn(){if(!ci.isColorSupported)return[];let e=st[0].length,t=[];for(let o=0;o<st.length;o+=2){let n="";for(let r=0;r<e;r++){let s=zn[st[o][r]],u=o+1<st.length?zn[st[o+1][r]]:void 0;s&&u?n+=`${vo(s)}${pi(u)}\u2580\x1B[49m\x1B[39m`:s?n+=`${vo(s)}\u2580\x1B[39m`:u?n+=`${vo(u)}\u2584\x1B[39m`:n+=" "}t.push(n)}return t}function it(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function Me(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var ze=(e,t)=>` ${e.padEnd(13)}${t}`;function mi(e,t){let o=[et("\u270E document360-writer")+N.gray(` v${e.version}`),N.gray(" Reads your code, writes your docs."),"",ze("Claude:",`${e.claude}${N.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),ze("Document360:",e.configured?e.loggedOut?N.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?N.gray(` (${e.sessionHint})`):""}`:N.yellow("not set up \u2014 run /init")),ze("Profile:",e.configured?`${e.profile}${N.gray(` (${e.apiUrl})`)}${e.prod?N.bold(N.yellow(" \u26A0 PRODUCTION")):""}`:N.gray("\u2014 (run /init)")),ze("Project:",e.project),ze("Mode:",N.gray(e.mode)),ze("cwd:",N.gray(e.cwd))],n=Gn();if(n.length===0)return o.join(`
|
|
26
|
+
`);let r=2,s=3,u=Co(n[0]);if(!(t>=r+u+s+Math.max(...o.map(x=>Co(x)))))return[...n.map(x=>" "+x),...o].join(`
|
|
27
|
+
`);let h=Math.max(0,Math.floor((o.length-n.length)/2)),f=[];for(let x=0;x<Math.max(n.length+h,o.length);x++){let T=n[x-h]??" ".repeat(u);f.push((" ".repeat(r)+T+" ".repeat(s)+(o[x]??"")).trimEnd())}return f.join(`
|
|
28
|
+
`)}var fi={error:N.red,warn:N.yellow,ok:N.green,info:N.gray};function Po(e,t){let o=Math.max(20,t);switch(e.kind){case"banner":return mi(e.info,o);case"user":{let n="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,o-4),u=50,p=e.text.split(`
|
|
29
|
+
`).flatMap(f=>Vn(f,s,{hard:!0}).split(`
|
|
30
|
+
`)),h=Math.max(0,p.length-u);return h>0&&(p=[...p.slice(0,u),N.dim(`\u2026 +${h} more lines`)]),`
|
|
31
|
+
`+p.map((f,x)=>n+(x===0?y(" \u276F "):" ")+f+" ".repeat(Math.max(0,s-Co(f))+1)+r).join(`
|
|
32
32
|
`)}case"assistant":return`
|
|
33
|
-
`+
|
|
34
|
-
`+
|
|
35
|
-
`)}case"diff":{let n=u=>u===1?"":"s",s=[
|
|
36
|
-
`)}case"link":return e.lines.map(n=>y(
|
|
33
|
+
`+bo(e.text,o);case"tool":{let n=e.arg!==null?N.gray(`${e.sep}(${e.arg})`):"";return`
|
|
34
|
+
`+Vn(N.green("\u25CF ")+N.bold(e.title)+n,o)}case"tool-result":{let n=e.isError?N.red:N.gray,r=e.lines.map((s,u)=>n((u===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(N.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
35
|
+
`)}case"diff":{let n=u=>u===1?"":"s",s=[N.gray(` \u23BF Added ${e.added} line${n(e.added)}, removed ${e.removed} line${n(e.removed)}`),...e.lines];return e.hidden>0&&s.push(N.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
36
|
+
`)}case"link":return e.lines.map(n=>y(tt(` \u2B95 ${n}`))).join(`
|
|
37
37
|
`);case"preview":return`
|
|
38
|
-
`+
|
|
38
|
+
`+et(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
39
39
|
|
|
40
|
-
`+
|
|
41
|
-
`+
|
|
42
|
-
`+(e.ok?
|
|
43
|
-
`)}var
|
|
40
|
+
`+bo(e.text,o);case"note":return`
|
|
41
|
+
`+fi[e.tone](tt(e.text));case"done":return`
|
|
42
|
+
`+(e.ok?N.magenta("\u2736 "):N.red("\u2736 "))+N.gray(`Cooked for ${it(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${Me(e.costUsd)}`:""))}}function Yn(e,t){return e.map(o=>Po(o,t)).join(`
|
|
43
|
+
`)}var To=3;function So(e){let t,o=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?o=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:o}}function Ro(e,t){return t?e.filter(o=>{let n=o.replace(/\\/g,"/");return n===t||n.startsWith(`${t}/`)}):e}function jo(e,t){return t.map(o=>{let n=0;try{n=gi(hi(e,o)).size}catch{n=0}return{path:o,bytes:n}})}function Ao(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
|
|
44
|
+
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
|
|
45
|
+
- Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
|
|
46
|
+
- 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.
|
|
47
|
+
- Work only on these files:
|
|
44
48
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
45
|
-
`)}function
|
|
46
|
-
`),display:`/screenshot ${t}`}:(console.log($("Usage: /screenshot <placeholder-id>")),{kind:"continue"})}var
|
|
47
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(o?.startsWith("mcp__document360__")){let u=
|
|
48
|
-
`);return{lines:s.slice(0,t).map(u=>
|
|
49
|
+
`)}function Io(e,t,o){let n=e.reduce((p,h)=>p+h.paths.length,0),[r,s]=t.usd;return[`Convert ${n} article${n===1?"":"s"} to DFM across ${e.length} partition${e.length===1?"":"s"} (\u2264${o} agents at once):`,...e.map(p=>` \u2022 ${p.label} \u2014 ${p.paths.length} article${p.paths.length===1?"":"s"}`),"",`Estimated cost: ${Me(r)}\u2013${Me(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Do(e,t){let o=e.filter(s=>s.ok),n=e.filter(s=>!s.ok),r=[`Converted ${o.length}/${e.length} partition${e.length===1?"":"s"} \xB7 ${Me(t)} total.`];if(n.length>0){r.push(`${n.length} failed \u2014 re-run /convert to retry:`);for(let s of n)r.push(` \u2717 ${s.label}${s.error?` \u2014 ${s.error}`:""}`)}return r}async function Xn(e,t){if(!yi(t.cwd))return console.log($("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let{scope:o,run:n}=So(e),r=bi(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=Ro(r,o);if(s.length===0)return console.log($(`No tracked articles under "${o}". (${r.length} are tracked overall.)`)),{kind:"continue"};let u=wi(s),p=`/convert${o?` --scope ${o}`:""} --run`,{model:h,forced:f}=xi(t.cwd,"light");if(!n){let x=ki({files:jo(t.cwd,s),op:"convert",model:h});o&&console.log(c(`Scope: ${o} (${s.length} of ${r.length} tracked articles).`));for(let T of Io(u,x,To))console.log(T);return console.log(c(`Model: ${h}${f?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(c(`Run ${p} to start.`)),console.log(""),{kind:"continue"}}console.log(c(`Converting ${s.length} articles across ${u.length} partitions (\u2264${To} agents at once) on ${h}\u2026`)),console.log(c(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let x of $i({cwd:t.cwd,partitions:u,promptFor:Ao,concurrency:To,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:h}))if(x.type==="partition_status")x.status==="running"?console.log(c(` \u25B8 ${x.label} \u2014 converting\u2026`)):x.status==="done"?console.log(S(` \u2713 ${x.label}`)):console.log($(` \u2717 ${x.label}`));else if(x.type==="run_done"){console.log("");for(let T of Do(x.results,x.totalCostUsd))console.log(x.ok?S(T):D(T))}}catch(x){console.log($(`Convert run failed: ${x.message}`))}return console.log(""),{kind:"continue"}}L();import{search as vi}from"@inquirer/prompts";import{findByName as Ci,getSession as Pi,listSessions as Ti,relativeTime as Kn}from"document360-engine";async function Qn(e,t){let o=Ti(t.cwd).filter(n=>n.uuid!==t.currentUuid());if(o.length===0)return console.log(c("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let n=e.join(" "),r=Ci(t.cwd,n);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${n}".`)),Jn(o),{kind:"continue"})}if(!process.stdin.isTTY)return Jn(o),console.log(c("Run: /resume <name>")),{kind:"continue"};try{let n=await t.withPausedInput(()=>vi({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let u=(s??"").toLowerCase();return o.filter(p=>!u||p.name.toLowerCase().includes(u)||p.firstPrompt.toLowerCase().includes(u)).map(p=>({name:`${p.name} ${Kn(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Pi(n);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Jn(e){console.log("");for(let t of e.slice(0,15))console.log(` ${y(t.name)} ${c(Kn(t.updatedAt))}`),console.log(` ${c(t.firstPrompt.slice(0,80))}`);console.log("")}L();import{renameSession as Si}from"document360-engine";async function Zn(e,t){let o=e.join(" ").trim();if(!o)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let n=t.currentUuid();return n?(Si(n,o)?console.log(S(`\u2713 Session renamed to "${o}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(console.log($("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as er,readProjectConfig as Ri,writeProjectConfig as ji}from"document360-engine";L();function Eo(e,t,o){if(!t)return"Usage: /profile add <name> [environment]";let n=Ri(e);if(!n)return"No .d360-writer.json \u2014 run /init first.";if(n.profiles?.[t])return`Profile "${t}" already exists.`;let r=o??t;return er().includes(r)?(n.profiles={...n.profiles,[t]:{connection:{environment:r},production:!1}},ji(n,e),null):`Unknown environment "${r}". Known: ${er().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function tr(e,t){let o=e[0];if(!o)return St(t.cwd),{kind:"continue"};if(o==="add"){let n=Eo(t.cwd,e[1],e[2]);return n?(console.log($(n)),{kind:"continue"}):(console.log(S(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${y(`/profile ${e[1]}`)} then ${y("/login")}`),{kind:"continue"})}return Rt(t.cwd,o),jt(t.cwd,o),console.log(c(" Restarting agent for the new profile\u2026")),{kind:"clear"}}L();import{select as Ai}from"@inquirer/prompts";import{readProjectConfig as Ii,readUserConfig as or,resolveModelSetting as Mo,writeUserConfig as nr}from"document360-engine";var ce=[{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 Lt(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),o=ce.findIndex(n=>n.value!==null&&(n.value===t||n.label.toLowerCase()===t||t.includes(n.label.toLowerCase())));return o>=0?o:0}function Di(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 lt(e,t){let o=()=>{let s=Mo(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=or();return s.defaultModel?(delete s.defaultModel,nr(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Mo(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:o()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}nr({...or(),defaultModel:t});let n=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=Ii(e)?.defaultModel;return r&&n.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:n,changed:!0,effective:o()}}async function rr(e,t){let o=e[0]?.trim();if(!o){let u=Mo(t.cwd);if(!process.stdin.isTTY)return console.log(`${re("Model:")} ${y(u.model??"Claude Code default")}`),console.log(c(` source: ${Di(u)}`)),console.log(c(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Lt(u),h;try{h=await t.withPausedInput(()=>Ai({message:`Select model (current: ${u.model??"Claude Code default"})`,default:ce[p].value,choices:ce.map((v,j)=>({name:`${v.label}${j===p?" \u2714":""}`,value:v.value,description:v.desc}))}))}catch{return console.log(c("Cancelled.")),{kind:"continue"}}let{lines:f,changed:x,effective:T}=lt(t.cwd,h??"default");for(let v of f)console.log(v.startsWith("\u26A0")?D(v):v.startsWith("\u2713")?S(v):c(v));return x&&await t.setModel(T),{kind:"continue"}}let{lines:n,changed:r,effective:s}=lt(t.cwd,o);for(let u of n)console.log(u.startsWith("\u26A0")?D(u):u.startsWith("\u2713")?S(u):c(u));return r&&await t.setModel(s),{kind:"continue"}}Nt();async function cr(e,t){return await t.withPausedInput(()=>qe(t.cwd)),{kind:"clear"}}L();import{resolveActiveProfile as Hi}from"document360-engine";async function ur(e,t){let o=!1;try{o=Hi(t.cwd).production}catch{}return o?(console.log(D("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(c("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}L();var dr=async(e,t)=>{try{await t.withPausedInput(()=>Tt({}))}catch(o){console.log($(`Login failed: ${o.message}`))}return{kind:"continue"}};L();async function Ot(e){let t=e[0];return t?{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for placeholder id: ${t}`,"","Steps you must follow:","1. Locate the SCREENSHOT HTML comment block with this id across user-docs/**/*.md.","2. Translate the placeholder.steps into Playwright actions using STABLE selectors only (data-testid > aria-label > role+name > visible text). If no stable selector is available for a required action, write `test.skip(...)` plus a TODO comment naming the React component that needs a data-testid.",'3. Write the spec file to <captureDir>/<id>.spec.ts. Use `import { test } from "@playwright/test"` and `import { waitPastLogin, dumpAnnotations, type Placeholder } from "document360-capture/helpers"`.',"4. Use process.env.CAPTURE_START_URL and process.env.CAPTURE_AUTH_BOUNDARY (these are injected at run time by document360-capture; do not hardcode them).","5. Report the path of the generated spec and any TODOs from missing selectors."].join(`
|
|
50
|
+
`),display:`/screenshot ${t}`}:(console.log($("Usage: /screenshot <placeholder-id>")),{kind:"continue"})}var pr={help:mo,"?":mo,clear:$n,exit:fo,quit:fo,init:Tn,mcp:At,publish:Dn,audit:Et,scope:Mn,sync:Fn,convert:Xn,resume:Qn,rename:Zn,profile:tr,model:rr,doctor:at,workspace:cr,"allow-prod":ur,login:dr,screenshot:Ot};function mr(e){let t=e.trim();if(!t.startsWith("/"))return null;let o=t.slice(1).split(/\s+/),n=(o[0]??"").toLowerCase();return n?{name:n,args:o.slice(1)}:null}L();var qi={Bash:"command",PowerShell:"command",Read:"file_path",Write:"file_path",Edit:"file_path",NotebookEdit:"notebook_path",Glob:"pattern",Grep:"pattern",WebFetch:"url",WebSearch:"query",Agent:"description",Task:"description",Skill:"skill"},gr=160,No=200,hr=40;function Z(e,t){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:o.slice(0,t-1)+"\u2026"}function fr(e){let t=Object.entries(e).filter(([,n])=>n!=null&&n!=="");if(t.length===0)return null;let o=t.slice(0,4).map(([n,r])=>`${n}: ${Z(typeof r=="string"?r:JSON.stringify(r),hr)}`);return t.length>4&&o.push("\u2026"),Z(o.join(", "),gr)}var ve=e=>typeof e=="string"&&e?e:null,Lo=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function zi(e){let t=ve(e)?.replace(/\\/g,"/");if(!t)return null;let o=t.split("/").filter(Boolean);if(o.length<2)return null;let n=o[o.length-2],r=n.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?n:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Gi(e,t){let o=(n,r)=>({title:`Document360: ${n}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let n=ve(t.title);if(!n)return null;let r=zi(t.local_path);return o("Create article",`"${Z(n,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let n=ve(t.title),r=Lo(t.article_id);return o("Update article",n?`"${Z(n,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return o("Fork article (new draft)",Lo(t.article_id)?`id ${Lo(t.article_id)}\u2026`:null);case"d360_publish_article":{let n=t.version_number;return o("Publish article LIVE",typeof n=="number"?`v${n}`:null)}case"d360_unpublish_article":return o("Unpublish article",null);case"d360_create_category":return o("Create category",ve(t.name)?`"${Z(ve(t.name),60)}"`:null);case"d360_upload_drive_file":{let n=ve(t.file_path);return o("Upload image",n?Z(n.replace(/\\/g,"/").split("/").pop()??n,60):null)}case"d360_sync_status":return o("Check sync status",null);default:return null}}function Ut(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),u=s.join("__");if(r==="document360"){let f=Gi(u,t);if(f)return f}let p=u.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:fr(t)}}let o=qi[e],n=o?t[o]:void 0;return typeof n=="string"&&n?{title:e,sep:"",arg:Z(n,gr)}:{title:e,sep:"",arg:fr(t)}}function Vi(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let o of["name","title","slug","id"])if(typeof t[o]=="string"&&t[o])return t[o];return null}function Yi(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let o=t.map(Vi).filter(r=>r!==null),n=`${t.length} item${t.length===1?"":"s"}`;return o.length===0?[n]:[n,...o.map(r=>Z(r,No))]}if(t!==null&&typeof t=="object"){let o=Object.entries(t).filter(([,n])=>n!==null&&(typeof n=="string"||typeof n=="number"||typeof n=="boolean")).slice(0,6).map(([n,r])=>`${n}: ${Z(String(r),hr)}`);return o.length>0?[Z(o.join(" \xB7 "),No)]:null}return null}function Xi(e){let t=ve(e)?.replace(/\\/g,"/");if(!t)return null;let o=t.split("/").filter(Boolean);return o.length>1?o.slice(1).join("/"):t}function Ji(e,t,o){switch(e){case"d360_create_article":{let n=Xi(t?.local_path);return[`\u2713 draft created${n?` \xB7 ${n}`:""}`]}case"d360_update_article":return["\u2713 draft updated"];case"d360_fork_article":return["\u2713 forked to a new draft"];case"d360_publish_article":return["\u2713 PUBLISHED LIVE \u2014 visible to readers"];case"d360_unpublish_article":return["\u2713 reverted to draft (removed from readers)"];case"d360_create_category":{let n=ve(t?.name);return[`\u2713 category created${n?` \xB7 "${n}"`:""}`]}case"d360_upload_drive_file":{let n=o.match(/https?:\/\/\S+/);return[`\u2713 uploaded${n?` \xB7 ${Z(n[0],120)}`:""}`]}default:return null}}function Wt(e,t=4,o,n){let r=e.replace(/\r\n/g,`
|
|
51
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(o?.startsWith("mcp__document360__")){let u=Ji(o.slice(18),n,r);if(u)return{lines:u,hidden:0}}let s=Yi(r)??r.split(`
|
|
52
|
+
`);return{lines:s.slice(0,t).map(u=>Z(u,No)),hidden:Math.max(0,s.length-t)}}function Ft(e,t,o,n="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${n}/${o}`}function Bt(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let o=JSON.parse(t),r=(Array.isArray(o)?o[0]:o)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function Ht(e){try{let t=JSON.parse(e),n=(Array.isArray(t)?t[0]:t)?.url;return typeof n=="string"&&/^https?:\/\//.test(n)?n:null}catch{return null}}var al=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function cl(e,t,o,n){if(al.test(e))try{let r=xr(n),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,u=Bt(t,o),p=Ht(o);e.endsWith("publish_article")&&p&&console.log(y(` \u2B95 Live: ${p}`)),u&&s&&console.log(y(` \u2B95 Preview: ${Ft(r.connection.portalUrl,s,u,r.project.languageCode??"en")}`))}catch{}}async function $r(e=process.cwd(),t="auto",o){let n=Qi(t);n.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${y("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${y('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${y("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${y("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),ul(e,o),n.kind==="subscription"&&(n.stored?console.log(c(" Using your Claude subscription (no API key set).")):console.log(c(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=Oo({cwd:e,profileName:o,allowProdWrites:r}),u={uuid:null,firstPrompt:null,titleFired:!1},p=Ki({input:process.stdin,output:process.stdout}),h=[],f=null,x=!1;p.on("line",j=>{if(f){let O=f;f=null,O(j)}else h.push(j)}),p.on("close",()=>{if(x=!0,f){let j=f;f=null,j(null)}});function T(){return h.length>0?Promise.resolve(h.shift()):x?Promise.resolve(null):(process.stdout.write(y("> ")),new Promise(j=>{f=j}))}let v={cwd:e,profileName:o,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Oo({cwd:e,profileName:o,allowProdWrites:r}),u={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>u.uuid,setModel:async j=>s.setModel(j),withPausedInput:async j=>{p.pause();try{return await j()}finally{p.resume()}}};try{for(;;){let j=await T();if(j===null)break;let O=j.trim();if(O){if(O.startsWith("/")){let _=mr(O);if(!_)continue;let H=pr[_.name];if(!H){console.log($(`Unknown command: /${_.name}`)),console.log(c("Type /help for the list."));continue}let B=await H(_.args,v);if(B.kind==="exit")break;if(B.kind==="clear"){v.restartAgent();continue}if(B.kind==="allow-prod"){r=!0,v.restartAgent(),console.log(S("\u2713 Production writes authorized for this session.")),console.log("");continue}if(B.kind==="resume"){s.close(),s=Oo({cwd:e,resume:B.uuid,profileName:o,allowProdWrites:r});let ee=Zi(B.uuid);u={uuid:B.uuid,firstPrompt:ee?.firstPrompt??null,titleFired:!0},yr(B.uuid),console.log(S(`\u2713 Resumed "${B.name}"`)),console.log("");continue}B.kind==="forward-to-agent"&&(u.firstPrompt||(u.firstPrompt=B.display??B.prompt),await wr(s,B.prompt,n,u,e));continue}u.firstPrompt||(u.firstPrompt=O),await wr(s,O,n,u,e)}}}finally{s.close(),p.close()}}function ul(e,t){console.log(""),console.log(et("document360-writer")),console.log(c(` cwd: ${e}`));let o=rl(e);console.log(c(` model: ${o.model??"auto (engine right-sizes per task)"}${o.model?` (${o.source})`:""}`)),console.log(dl(e,t)),sl(e)||console.log(D(" First run: /init \u2192 /login \u2192 /workspace, then ask for a docs analysis.")),console.log(c(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function dl(e,t){try{let o=xr(e,t),n=o.production?D(" \u26A0 PRODUCTION"):"",r=ll(o.name);if(!r)return c(` Document360: profile "${o.name}"${n} \u2014 not logged in (d360-writer login)`);let s={...kr(r.idToken)??{},...kr(r.accessToken)??{}},u=s.email??s.preferred_username??"signed in";return il(r)&&!r.refreshToken?D(` Document360: profile "${o.name}"${n} \u2014 session expired (d360-writer login)`):c(` Document360: ${u} \xB7 profile "${o.name}"${n}`)}catch(o){return c(` Document360: ${o.message.split(".")[0]}`)}}function pl(){console.error(""),console.error(`Sign in with your Claude subscription: run ${y("claude")} once, then retry.`),console.error(` (No Claude Code? ${y("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${y("https://console.anthropic.com/settings/keys")}`)}function ml(e,t,o){e.uuid=t;let n=new Date().toISOString();ol({uuid:t,name:tl(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:o,firstPrompt:e.firstPrompt??"",createdAt:n,updatedAt:n})}function fl(e,t){e.titleFired=!0;let o=e.uuid,n=e.firstPrompt;!o||!n||nl(n,t).then(r=>{r&&el(o,r)}).catch(()=>{})}async function wr(e,t,o,n,r){let s=new Map;for await(let u of e.send(t))gl(u,n,r,o,s)}function gl(e,t,o,n,r){switch(e.type){case"session":t.uuid||ml(t,e.sessionId,o);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Ut(e.name,e.input);s&&(process.stdout.write(`
|
|
49
53
|
|
|
50
|
-
`),console.log(`${S("\u25CF")} ${
|
|
51
|
-
`),console.log(c(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(
|
|
52
|
-
`)){let u=s.trim().replace(
|
|
53
|
-
`)}function
|
|
54
|
-
`)||e.length>200}function
|
|
55
|
-
`).length;return`[Pasted text #${e} +${o} line${o===1?"":"s"}]`}function
|
|
56
|
-
`)){if(s.length===0)n.push({start:r,end:r});else for(let u=0;u<s.length;u+=o)n.push({start:r+u,end:r+Math.min(u+o,s.length)});r+=s.length+1}return n.length>0?n:[{start:0,end:0}]}function
|
|
57
|
-
`),s=0;for(let u=r.length-1;u>=0;u--){let p=r[u];if(s+=Math.max(1,Math.ceil(p.length/n)),s>=t){let
|
|
58
|
-
`),truncated:u>0||
|
|
59
|
-
`)){let s=n+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(o=s+1),n=s+1}return o}import{Fragment as
|
|
54
|
+
`),console.log(`${S("\u25CF")} ${re(s.title)}${s.arg!==null?X(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Ee(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let u=p=>p===1?"":"s";console.log(X(` \u23BF Added ${s.added} line${u(s.added)}, removed ${s.removed} line${u(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(c(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let u=Wt(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:X;u.lines.forEach((h,f)=>console.log(p((f===0?" \u23BF ":" ")+h))),u.hidden>0&&console.log(c(` \u2026 +${u.hidden} lines`)),e.isError||cl(s.name,s.input,e.output,o);break}case"result":process.stdout.write(`
|
|
55
|
+
`),console.log(c(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(yr(t.uuid),t.titleFired||fl(t,o));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),n.kind==="subscription"&&e.kind==="auth"&&pl();break}}import{render as ra}from"ink";import{resolveAuth as sa}from"document360-engine";import{useCallback as G,useEffect as Ge,useMemo as Vt,useRef as Y,useState as M}from"react";import{Box as V,Text as b,useApp as wl,useInput as yl,useStdout as xl}from"ink";import{existsSync as $l,readFileSync as Mr,readdirSync as bl}from"node:fs";import{basename as _r,isAbsolute as vl,join as Xt}from"node:path";import{createSession as Lr,loginPkce as Cl,toStoredTokens as Pl,saveTokens as Tl,getAccessToken as Sl,resolveActiveProfile as ue,resolveProjectId as Rl,getArticle as jl,decodeJwtClaims as Ve,isExpired as Ce,loadTokens as _e,setTitle as Al,slugify as Il,touchSession as Uo,upsertSession as Dl,generateTitle as Nr,findByName as El,listSessions as Ml,renameSession as _l,suggestNextAction as Ll,readProjectConfig as ge,writeProjectConfig as Nl,resolveModelSetting as Bo,loadProfileMap as Or,applyPull as Ol,computeSyncStatus as Wo,planPull as Ul,inventoryRepo as Wl,knownEnvironments as Fl,resolveEnvironment as Bl,planPartitions as Hl,trackedArticlePaths as ql,runPartitioned as zl,estimateBulkCost as Gl,resolveModelForOperation as Vl}from"document360-engine";Nt();var qt=[{name:"help",usage:"/help",desc:"Show available commands"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser) without leaving the session"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch connection (picker; s = session only)"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API"},{name:"init",usage:"/init",desc:"Pick an environment & scaffold .d360-writer.json"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Manage MCP servers"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)"},{name:"sync",usage:"/sync [pull <path>|--all]",desc:"Drift report local vs Document360; pull portal edits"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM across parallel agents (preview; --scope to limit; --run to start)"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (analyses + recommends)"},{name:"audit",usage:"/audit",desc:"Gap analysis: code vs docs vs Document360 (incremental)"},{name:"screenshot",usage:"/screenshot <id>",desc:"Emit a capture spec for a placeholder"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)"},{name:"exit",usage:"/exit",desc:"Quit"}];function br(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return qt.filter(o=>o.name.startsWith(t))}function vr(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}var hl=/^(?:\d+[.)]|[-*•])\s+/;function Cr(e,t,o=4){let n=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
56
|
+
`)){let u=s.trim().replace(hl,""),p=u.match(/^`([^`]+)`$/);p&&(u=p[1].trim());let h=u.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!n.has(h[1].toLowerCase()))continue;let f=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(f)||r.push(f),r.length>=o)break}return r}L();var kl=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Pr(e){return e.replace(/\r\n?/g,`
|
|
57
|
+
`)}function Tr(e){return e.includes(`
|
|
58
|
+
`)||e.length>200}function Sr(e,t){let o=t.split(`
|
|
59
|
+
`).length;return`[Pasted text #${e} +${o} line${o===1?"":"s"}]`}function Rr(e,t){return e.replace(kl,o=>t.get(o)??o)}function jr(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function zt(e,t){let o=Math.max(1,t),n=[],r=0;for(let s of e.split(`
|
|
60
|
+
`)){if(s.length===0)n.push({start:r,end:r});else for(let u=0;u<s.length;u+=o)n.push({start:r+u,end:r+Math.min(u+o,s.length)});r+=s.length+1}return n.length>0?n:[{start:0,end:0}]}function Gt(e,t){let o=0;for(let n=0;n<e.length&&e[n].start<=t;n++)o=n;return o}function Ar(e,t,o){let n=Gt(e,t),r=n+o;if(r<0||r>=e.length)return t;let s=Math.min(t,e[n].end)-e[n].start;return Math.min(e[r].start+s,e[r].end)}function Ir(e,t,o){let n=e[Gt(e,t)];return o==="start"?n.start:n.end}function Dr(e,t,o){let n=Math.max(1,o),r=e.split(`
|
|
61
|
+
`),s=0;for(let u=r.length-1;u>=0;u--){let p=r[u];if(s+=Math.max(1,Math.ceil(p.length/n)),s>=t){let h=s-t;return{text:[h>0?p.slice(h*n):p,...r.slice(u+1)].join(`
|
|
62
|
+
`),truncated:u>0||h>0}}}return{text:e,truncated:!1}}function Er(e){let t=!1,o=0,n=0;for(let r of e.split(`
|
|
63
|
+
`)){let s=n+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(o=s+1),n=s+1}return o}import{Fragment as Fo,jsx as C,jsxs as E}from"react/jsx-runtime";var Yl={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""};function Xl(e,t,o,n){let r=o.kind==="api"?"API key":o.kind==="subscription"?"subscription":"not configured",s=Bo(e),u=ge(e),p=(u?.docsDir??"user-docs").replace(/\/+$/,""),h=u?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${p}/ + config`,f={version:t,claude:r,model:s.model??"Claude Code default model",modelSource:Yl[s.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:u!==null,mode:h};if(u===null)return f;try{let x=ue(e,n);f.profile=x.name,f.apiUrl=x.connection.apiUrl,f.prod=x.production,f.project=x.project.projectId??"(chosen at login)";let T=_e(x.name);if(T){let v={...Ve(T.idToken)??{},...Ve(T.accessToken)??{}},j=v.email??v.preferred_username??"signed in";Ce(T)?T.refreshToken&&(f.who=j,f.loggedOut=!1,f.sessionHint="session expired \u2014 refreshing\u2026"):(f.who=j,f.loggedOut=!1,f.sessionHint=`session valid until ${new Date(T.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return f}function Jl(e,t){try{let o=ue(e,t),n=_e(o.name);if(!n)return{text:`profile "${o.name}" \u2014 not logged in (/login)`,prod:o.production};let r={...Ve(n.idToken)??{},...Ve(n.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ce(n)&&!n.refreshToken?{text:`profile "${o.name}" \u2014 session expired (/login)`,prod:o.production}:{text:`${s} \xB7 profile "${o.name}"`,prod:o.production}}catch(o){return{text:o.message.split(".")[0],prod:!1}}}var Ur=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],Jt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Kl="Ask me to write or update an article\u2026";function Yt({ch:e,dim:t}){let[o,n]=M(!0);return Ge(()=>{let r=setInterval(()=>n(s=>!s),530);return()=>clearInterval(r)},[]),C(b,{inverse:o,color:t&&!o?"gray":void 0,children:e})}var Ql=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Wr(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Zl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fr(e){try{return bl(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ea(e,t){let o=t??[];return o.length===0?["src","api","services","packages","modules"].some(n=>Fr(Xt(e,n))):o.some(n=>!n.includes("/")&&!n.endsWith(".md")&&Fr(Xt(e,n)))}function ta({startTime:e,chars:t}){let[o,n]=M(0);Ge(()=>{let h=setInterval(()=>n(f=>f+1),120);return()=>clearInterval(h)},[]);let r=Jt[o%Jt.length],s=Ur[Math.floor(o/16)%Ur.length],u=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return E(V,{children:[C(b,{color:F,children:` ${r} ${s}\u2026 `}),C(b,{color:"gray",children:`(${it(u)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var oa=12e4;function na({p:e}){let[t,o]=M(0);Ge(()=>{let h=setInterval(()=>o(f=>f+1),150);return()=>clearInterval(h)},[]);let n=Jt[t%Jt.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),u=Math.round(e.chars/4),p=Date.now()-e.lastAt>=oa;return E(V,{flexDirection:"column",children:[E(V,{children:[C(b,{color:F,children:` ${n} Converting `}),C(b,{color:"gray",children:`${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${u} tokens \xB7 ${it(r)} \xB7 esc to stop`})]}),e.active.length>0&&C(b,{dimColor:!0,children:` \u25B8 ${e.active.join(", ")} \xB7 last activity ${s}s ago`}),p&&C(b,{color:"yellow",children:` \u26A0 no activity for ${it(s)} \u2014 press esc to stop if it's wedged`})]})}function Br({cwd:e,auth:t,profileName:o,version:n}){let{exit:r}=wl(),[s,u]=M(o),[p,h]=M(null),[f,x]=M({text:"",pos:0}),T=f.text,v=G(a=>{x(l=>{let i=typeof a=="function"?a(l.text):a;return{text:i,pos:i.length}})},[]),j=G(a=>{x(l=>({text:l.text.slice(0,l.pos)+a+l.text.slice(l.pos),pos:l.pos+a.length}))},[]),O=G(()=>{x(a=>{if(a.pos===0)return a;let l=a.text.slice(0,a.pos),i=jr(l)??l.slice(0,-1);return{text:i+a.text.slice(a.pos),pos:i.length}})},[]),[_,H]=M(!1),[B,ee]=M(!1),[se,ke]=M(0),[ie,le]=M(null),[Ye,J]=M([]),ct=Y(0),[Gr,Kt]=M(!1),[Vr,Qt]=M(0),ut=Y(0),[Xe,Le]=M(0),[Ne,dt]=M(null),zo=Y(new Map),Yr=Y(0),Zt=Y([]),te=Y(null);te.current===null&&(te.current=Lr({cwd:e,profileName:s,allowProdWrites:!1}));let Pe=Y({uuid:null,firstPrompt:null,titleFired:!1}),pt=Y(new Map),eo=Y(!1),to=Y([]),we=Y([]),[Te,Se]=M(null),[de,Oe]=M(null),[ye,Ue]=M(null),[K,We]=M(null),[pe,Fe]=M(null),[oe,Re]=M(null),[Q,Be]=M(null),[Go,oo]=M([]),je=Y([]),mt=Y(!1),Je=Y(null),[Vo,Ke]=M(null),ft=Y(!1),gt=Y(null),[ne,Ae]=M(null),[ht,Yo]=M(0),[Xo,no]=M(0),[Xr,Jo]=M(0),ro=Vt(()=>{try{return Bo(e).model??"auto"}catch{return null}},[e,Xr]),{stdout:ae}=xl(),[,Jr]=M(0),Ko=Y(`${ae.columns??80}x${ae.rows??24}`),xe=G(()=>Math.max(20,(ae.columns??80)-1),[ae]),d=G(a=>{Zt.current.push(a),console.log(Po(a,xe()))},[xe]);Ge(()=>{if(d({kind:"banner",info:Xl(e,n,t,s)}),!ge(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
60
64
|
1. /init \u2014 pick your Document360 environment & scaffold config
|
|
61
65
|
2. /login signs in to that environment
|
|
62
66
|
3. /workspace picks where articles go
|
|
63
|
-
Press 1 to start.`}),
|
|
64
|
-
`)});return;case"exit":case"quit":
|
|
65
|
-
`:"",
|
|
66
|
-
Model: ${A.model}${A.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:
|
|
67
|
-
`)+
|
|
68
|
-
`)})}}catch(
|
|
69
|
-
`)});return}if(m==="pull"){let g=h[1];if(!g){d({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(g==="--all"){if(d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await Oo({cwd:e,profileName:s})).entries.filter(O=>O.status==="remote-ahead"&&O.path).map(O=>O.path),w.length===0){d({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 w=[g.replace(/\\/g,"/")];let R=[];for(let I of w)R.push(await Nl({cwd:e,profileName:s,relPath:I}));he.current=R,ht();return}d({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${m} \u2014 use /sync or /sync pull <path>|--all.`})}catch(g){d({kind:"note",tone:"error",text:`Sync failed: ${g.message}`})}return}case"scope":{if(!me(e)){d({kind:"note",tone:"error",text:"No .d360-writer.json here. Run /init first."});return}let m=Ol(e);if(m.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}We({cursor:0,rows:m.map(g=>({...g,checked:g.recommended}))});return}case"audit":case"screenshot":{if(i==="screenshot"&&!h[0]){d({kind:"note",tone:"error",text:"Usage: /screenshot <id>"});return}let g=await(i==="audit"?At:_t)(h,void 0);g.kind==="forward-to-agent"&&g.prompt&&await Ae(g.prompt,{display:g.display,echoDisplay:!0});return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,ht,d,pe,Ae]),kt=z(a=>{let l=(a??T).trim();if(b(""),at(null),Me(0),l.startsWith("/")){let h=g=>g.trim().split(/\s+/).slice(1).join(" "),m=h(l);X(g=>g.filter(w=>w.trim()!==l&&!(m&&h(w)===m)))}if(!l||Zo(l))return;Kt.current.push(l);let i=Pr(l,Ho.current);l.startsWith("/")?en(i):Ae(i,{display:l})},[T,Zo,en,Ae]),tn=z(a=>{if(a.length>1){if(a.includes("\x1B"))return;let l=br(a);if(vr(l)){let i=Cr(++Gr.current,l);Ho.current.set(i,l),j(i)}else j(l);return}j(a)},[j]),Fe=Math.max(10,je-6),on=qt(()=>Bt(f.text,Fe),[f.text,Fe]),so=z(a=>x(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+a))})),[]),wt=z(a=>x(l=>({...l,pos:Sr(Bt(l.text,Fe),l.pos,a)})),[Fe]),Je=z(a=>x(l=>({...l,pos:Rr(Bt(l.text,Fe),l.pos,a)})),[Fe]),Xr=["\x1B[H","\x1B[1~","\x1BOH"],Jr=["\x1B[F","\x1B[4~","\x1BOF"],nn=z((a,l)=>l.leftArrow?(so(-1),!0):l.rightArrow?(so(1),!0):a&&Xr.includes(a)?(Je("start"),!0):a&&Jr.includes(a)?(Je("end"),!0):l.ctrl&&a==="a"?(Je("start"),!0):l.ctrl&&a==="e"?(Je("end"),!0):!1,[so,Je]);return kl((a,l)=>{if(l.ctrl&&a==="c"){ee.current?.close(),r();return}if(!F){if(D){if(l.escape){if(Ve.current){Ve.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),Ve.current.abort());return}ut.current||(ut.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ee.current?.interrupt());return}if(l.return){let i=T.trim();if(!i)return;Se.current.push(i),Qt([...Se.current]),b("");return}if(nn(a,l))return;if(l.upArrow){wt(-1);return}if(l.downArrow){wt(1);return}if(l.backspace||l.delete){N();return}a&&!l.ctrl&&!l.meta&&tn(a);return}if(Ce){if(l.upArrow){Pe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Pe(i=>i&&{...i,cursor:Math.min(ae.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=ae.length){Pe(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=ae[Ce.cursor];Pe(null);let{lines:h,changed:m,effective:g}=nt(e,i.value??"default");for(let w of h)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});m&&(Yo(w=>w+1),ee.current?.setModel(g));return}if(a==="s"){let i=ae[Ce.cursor];Pe(null),ee.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){Pe(null);return}return}if(ue){if(l.upArrow){Le(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Le(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=ue.rows.length){Le(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return||a==="s"){let i=ue.rows[ue.cursor];Le(null),ro(i.name,l.return===!0);return}if(l.escape){Le(null);return}return}if(ke){if(l.upArrow){Ne(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ne(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=ke.rows.length){Ne(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=ke.rows[ke.cursor].name;if(Ne(null),!bn(e,i).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 "${i}").`});let m=!1;try{let g=De(i);m=!!g&&!(be(g)&&!g.refreshToken)}catch{}m?(d({kind:"note",tone:"info",text:`Already signed in to ${i} \u2014 next: pick a workspace.`}),X(["/workspace"])):(d({kind:"note",tone:"info",text:`Next: sign in to Document360 (${i}).`}),X(["/login"])),ge(g=>g+1);return}if(l.escape){Ne(null);return}return}if(J){if(l.upArrow){Oe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Oe(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=J.rows.length){Oe(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=J.rows[J.cursor],{profile:h,projectId:m}=J;Oe(null),Qo(h,m,i);return}if(l.escape){Oe(null);return}return}if(K){if(l.upArrow){We(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){We(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a===" "){We(i=>i&&{...i,rows:i.rows.map((h,m)=>m===i.cursor?{...h,checked:!h.checked}:h)});return}if(l.return){let i=K.rows.filter(h=>h.checked).map(h=>h.path);if(We(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}fo(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let h of i)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(l.escape){We(null);return}return}if(de){if(l.upArrow){Ue(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ue(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=de.rows.length){Ue(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=de.rows[de.cursor],h=de.rows.filter(m=>m.path!=="--all").map(m=>m.path);Ue(null),Ae(i.path==="--all"?tt(h):jt(i.path),{display:i.path==="--all"?"/publish --all":`/publish ${i.path}`,echoDisplay:!0});return}if(l.escape){Ue(null);return}return}if(te){if(l.escape){Te(null);return}if(l.upArrow){Te(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Te(i=>i&&{...i,cursor:Math.min(Math.max(0,ft.length-1),i.cursor+1)});return}if(l.return){let i=ft[te.cursor];if(i){Te(null);try{d({kind:"preview",name:Er(i),text:Or(Ir(Gt(e,i),"utf8"))})}catch(h){d({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(l.backspace||l.delete){Te(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(a&&!l.ctrl&&!l.meta&&a.length===1){Te(i=>i&&{...i,query:i.query+a,cursor:0});return}return}if(oe){if(l.escape){Re(null);return}if(l.upArrow){Re(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Re(i=>i&&{...i,cursor:Math.min(Math.max(0,gt.length-1),i.cursor+1)});return}if(l.return){let i=gt[oe.cursor];i&&(Re(null),pe(i.uuid),ve.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},No(i.uuid),d({kind:"note",tone:"ok",text:`Resumed "${i.name}".`}));return}if(l.backspace||l.delete){Re(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(a&&!l.ctrl&&!l.meta&&a.length===1){Re(i=>i&&{...i,query:i.query+a,cursor:0});return}return}if(l.tab&&!T&&se){b(se),ie(null),it.current++;return}if(!T&&Ge.length>0&&a&&/^[1-9]$/.test(a)){let i=Ge[Number(a)-1];if(i){b(i);return}}if(!nn(a,l)){if(Jo){if(l.upArrow){Me(i=>Math.max(0,i-1));return}if(l.downArrow){Me(i=>Math.min(Xe.length-1,i+1));return}if(l.tab){b("/"+(Xe[Ye]?.name??"")+" "),Me(0);return}if(l.return){let i=Xe[Ye];if(i){let h=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(xr(i.usage)&&!h){b("/"+i.name+" "),Me(0);return}kt("/"+i.name+(h?" "+h:""));return}}}else{if(l.upArrow){if(T!==""&&_e===null){wt(-1);return}let i=Kt.current;if(!i.length)return;let h=_e===null?i.length-1:Math.max(0,_e-1);at(h),b(i[h]??"");return}if(l.downArrow){if(T!==""&&_e===null){wt(1);return}let i=Kt.current;if(_e===null)return;let h=_e+1;h>=i.length?(at(null),b("")):(at(h),b(i[h]??""));return}}if(l.return){kt();return}if(l.backspace||l.delete){N();return}if(l.escape){b(""),Me(0),ie(null),X([]);return}a&&!l.ctrl&&!l.meta&&tn(a)}}}),st(()=>{if(D||F)return;let a=Se.current.shift();a!==void 0&&(Qt([...Se.current]),kt(a))},[D,F,kt]),L(V,{flexDirection:"column",width:je,children:[oo!==null&&L(V,{marginTop:1,flexDirection:"column",children:[oo.truncated&&C(v,{dimColor:!0,children:"\u2026"}),C(v,{children:oo.text})]}),D&&C(Zl,{startTime:lt.current,chars:zr}),C(V,{borderStyle:"round",borderColor:Xo.prod?"yellow":W,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?on.map((a,l)=>{let i=f.text.slice(a.start,a.end),h=l===Ht(on,f.pos),m=Math.min(f.pos,a.end)-a.start;return L(v,{children:[C(v,{color:W,children:l===0?"> ":" "}),h?L(Uo,{children:[i.slice(0,m),C(zt,{ch:i[m]??" "}),i.slice(m+1)]}):i||" "]},`${l}-${a.start}`)}):L(v,{children:[C(v,{color:W,children:"> "}),se&&!D?L(Uo,{children:[C(zt,{ch:se[0],dim:!0}),C(v,{color:"gray",children:se.slice(1)}),C(v,{dimColor:!0,children:" (tab)"})]}):to.isSetup||!qr?L(Uo,{children:[C(zt,{ch:to.text[0],dim:!0}),C(v,{color:"gray",children:to.text.slice(1)})]}):C(zt,{ch:" "})]})}),qo.length>0&&C(V,{flexDirection:"column",paddingX:1,children:qo.map((a,l)=>C(v,{color:"gray",children:`\u29D7 queued: ${a}`},`${l}-${a.slice(0,24)}`))}),Ce?L(V,{flexDirection:"column",paddingX:1,children:[C(v,{color:W,bold:!0,children:"Select model"}),C(v,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),ae.map((a,l)=>L(v,{color:l===Ce.cursor?W:void 0,children:[l===Ce.cursor?"\u276F ":" ",`${l+1}. ${a.label}${l===Ce.current?" \u2714":""}`.padEnd(16),C(v,{color:"gray",children:a.desc})]},a.label)),C(v,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):ue?L(V,{flexDirection:"column",paddingX:1,children:[C(v,{color:W,bold:!0,children:"Switch connection profile"}),ue.rows.map((a,l)=>L(v,{color:l===ue.cursor?W:void 0,children:[l===ue.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===ue.current?" \u2714":""}`.padEnd(20),C(v,{color:"gray",children:`${a.env} \xB7 ${a.who??"not signed in"}`}),a.prod?C(v,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},a.name)),C(v,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):ke?L(V,{flexDirection:"column",paddingX:1,children:[C(v,{color:W,bold:!0,children:"Pick your Document360 environment"}),ke.rows.map((a,l)=>L(v,{color:l===ke.cursor?W:void 0,children:[l===ke.cursor?"\u276F ":" ",`${l+1}. ${a.name}`.padEnd(16),C(v,{color:"gray",children:a.apiUrl})]},a.name)),C(v,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):J?L(V,{flexDirection:"column",paddingX:1,children:[C(v,{color:W,bold:!0,children:"Switch workspace"}),C(v,{dimColor:!0,children:`environment ${J.environment} \xB7 project ${J.projectId.slice(0,8)}\u2026`}),J.rows.map((a,l)=>L(v,{color:l===J.cursor?W:void 0,children:[l===J.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===J.current?" \u2714":""}`.padEnd(30),C(v,{color:"gray",children:a.type??""})]},a.id)),C(v,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):K?(()=>{let l=Math.min(Math.max(0,K.cursor-Math.floor(7)),Math.max(0,K.rows.length-14)),i=K.rows.slice(l,l+14),h=K.rows.filter(m=>m.checked).length;return L(V,{flexDirection:"column",paddingX:1,children:[C(v,{color:W,bold:!0,children:`Which folders back the user docs? (${h} selected of ${K.rows.length})`}),l>0?C(v,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((m,g)=>{let w=l+g;return L(v,{color:w===K.cursor?W:void 0,children:[w===K.cursor?"\u276F ":" ",m.checked?"\u25C9 ":"\u25CB ",m.path.padEnd(Math.min(48,je-34)),C(v,{color:"gray",children:It(m)})]},m.path)}),l+14<K.rows.length?C(v,{dimColor:!0,children:` \u2193 ${K.rows.length-l-14} more`}):null,C(v,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():de?L(V,{flexDirection:"column",paddingX:1,children:[C(v,{color:W,bold:!0,children:"Publish which article?"}),de.rows.map((a,l)=>L(v,{color:l===de.cursor?W:void 0,children:[l===de.cursor?"\u276F ":" ",`${l+1}. ${a.path}`.padEnd(Math.min(56,je-30)),C(v,{color:"gray",children:a.label})]},a.path)),C(v,{dimColor:!0,children:"enter publish (draft) \xB7 esc cancel"})]}):te?L(V,{flexDirection:"column",paddingX:1,children:[C(v,{color:W,bold:!0,children:`Preview article${te.query?` \u2014 filter: ${te.query}`:" (type to filter)"}`}),ft.length===0?C(v,{color:"gray",children:"no articles match"}):ft.map((a,l)=>L(v,{color:l===te.cursor?W:void 0,children:[l===te.cursor?"\u276F ":" ",a]},a)),C(v,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):oe?L(V,{flexDirection:"column",paddingX:1,children:[C(v,{color:W,bold:!0,children:`Resume session${oe.query?` \u2014 filter: ${oe.query}`:" (type to filter)"}`}),gt.length===0?C(v,{color:"gray",children:"no sessions match"}):gt.map((a,l)=>L(v,{color:l===oe.cursor?W:void 0,children:[l===oe.cursor?"\u276F ":" ",a.name.slice(0,28).padEnd(30),C(v,{color:l===oe.cursor?W:"gray",children:a.firstPrompt.slice(0,Math.max(10,je-40))})]},a.uuid)),C(v,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Jo?C(V,{flexDirection:"column",children:Xe.map((a,l)=>L(v,{color:l===Ye?W:void 0,children:[l===Ye?"\u276F ":" ",a.usage.padEnd(22)," ",C(v,{color:l===Ye?W:"gray",children:a.name==="model"&&eo?`${a.desc} (currently ${eo})`:a.desc})]},a.name))}):!T&&Ge.length>0?L(V,{flexDirection:"column",paddingX:1,children:[Ge.map((a,l)=>L(v,{children:[C(v,{color:W,children:l+1})," ",a.slice(0,Math.max(20,je-5))]},a)),C(v,{dimColor:!0,children:`press 1-${Ge.length} to fill the command \xB7 esc dismiss`})]}):C(V,{paddingX:1,children:L(v,{color:"gray",children:[Xo.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${eo??"model n/a"}${mt>0?` \xB7 ${mt<1e3?`${mt} tokens`:`${(mt/1e3).toFixed(1)}k tokens`}`:""}${Go>0?` \xB7 ${Ee(Go)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}M();import{jsx as oa}from"react/jsx-runtime";async function Fr(e=process.cwd(),t="auto",o,n="0.0.0"){let r=ta(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${y("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${y("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=ea(oa(Wr,{cwd:e,auth:r,profileName:o,version:n}));await s(),process.stdout.write(`
|
|
70
|
-
`),process.exit(0)}var
|
|
67
|
+
Press 1 to start.`}),J(["/init"]);return}try{let a=ue(e,s),l=_e(a.name);l&&Ce(l)&&l.refreshToken?Sl({profile:a.name,connection:a.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ke(i=>i+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),J(["/login"])}):(!l||Ce(l))&&(d({kind:"note",tone:"warn",text:`Profile "${a.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),J(["/login"]))}catch{}try{let a=ge(e),l=ue(e,s),i=_e(l.name);a&&i&&!Ce(i)&&ea(e,a.authoritativeSourceFiles)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),J(["/scope"]))}catch{}},[]),Ge(()=>{let a=null,l=null,i=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null;let k=`${ae.columns??80}x${ae.rows??24}`;k!==Ko.current&&(Ko.current=k,Jr(m=>m+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Yn(Zt.current,xe())+"\x1B[?2026l")},80))},400)};return ae.on("resize",i),()=>{a&&clearTimeout(a),l&&clearTimeout(l),ae.off("resize",i)}},[ae,xe]);let Ie=Math.max(20,(ae.columns??80)-1),Qo=Vt(()=>Jl(e,s),[e,s,se]),so=Vt(()=>{if(!ge(e))return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};try{let a=ue(e,s),l=_e(a.name);if(!(!!l&&!(Ce(l)&&!l.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${a.name}")\u2026`,isSetup:!0};if(!a.project.workspaceId)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return{text:Kl,isSetup:!1}},[e,s,se]),Qe=br(T),Zo=Qe.length>0&&!_,io=p!==null?Dr(p,8,Ie):null,kt=oe?oe.paths.filter(a=>!oe.query||a.toLowerCase().includes(oe.query.toLowerCase())).slice(0,8):[],wt=ne?ne.sessions.filter(a=>{let l=ne.query.toLowerCase();return!l||a.name.toLowerCase().includes(l)||a.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],me=G((a,l)=>{te.current?.close(),te.current=Lr({cwd:e,resume:a,profileName:l??s,allowProdWrites:eo.current}),a||(Pe.current={uuid:null,firstPrompt:null,titleFired:!1}),Yo(0),no(0)},[e,s]),en=G((a,l,i)=>{if(Ql.test(a))try{let k=ue(e,s),m=typeof l.project_id=="string"&&l.project_id||k.project.projectId,g=Bt(l,i),w=[],R=Ht(i);a.endsWith("publish_article")&&R&&w.push(`Live: ${R}`),g&&m&&w.push(`Preview: ${Ft(k.connection.portalUrl,m,g,k.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),De=G(async(a,l)=>{Kt(!0),le(null),J([]);let i=++ct.current;d({kind:"user",text:l?.echoDisplay&&l.display?l.display:a});let k=Pe.current;k.firstPrompt||(k.firstPrompt=l?.display??a),ut.current=Date.now(),Qt(0),H(!0),pt.current.clear();let m="",g="",w=null,R=()=>{w||(w=setTimeout(()=>{w=null,h(g.length>0?g:null)},60))},I=()=>{w&&clearTimeout(w),w=null,h(null)},U=()=>{if(g.trim()){let P=g.trimEnd();d({kind:"assistant",text:P})}g="",I()};try{for await(let P of te.current.send(a))if(P.type==="session"){if(!k.uuid){k.uuid=P.sessionId;let A=new Date().toISOString();Dl({uuid:P.sessionId,name:Il(k.firstPrompt??"session"),renamed:!1,titled:!1,cwd:e,firstPrompt:k.firstPrompt??"",createdAt:A,updatedAt:A})}}else if(P.type==="text"){g+=P.delta,m+=P.delta;let A=Er(g);if(A>0){let q=g.slice(0,A).trimEnd();q&&d({kind:"assistant",text:q}),g=g.slice(A)}R(),Qt(q=>q+P.delta.length)}else if(P.type==="tool"){let A=Ut(P.name,P.input);A&&(U(),d({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),pt.current.set(P.id,{name:P.name,input:P.input}))}else if(P.type==="article_diff"){let A=Ee(P.oldContent,P.newContent,xe());A&&(U(),d({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(P.type==="tool_result"){P.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(P.output)&&(ft.current=!0);let A=pt.current.get(P.id);if(A){pt.current.delete(P.id),U();let q=Wt(P.output,4,P.isError?void 0:A.name,A.input);d({kind:"tool-result",lines:q.lines,hidden:q.hidden,isError:P.isError}),P.isError||en(A.name,A.input,P.output)}}else if(P.type==="result"){U(),Yo(q=>q+P.outputTokens),no(q=>q+P.costUsd),d({kind:"done",seconds:Math.round((Date.now()-ut.current)/1e3),tokens:P.outputTokens,costUsd:P.costUsd,ok:P.ok});let A=P.ok?Cr(m,qt.map(q=>q.name)):[];if(A.length>0?J(A):P.ok&&m.trim()&&Ll(a,m,e).then(q=>{q&&ct.current===i&&le(q)}).catch(()=>{}),k.uuid&&(Uo(k.uuid),!k.titleFired)){k.titleFired=!0;let q=k.uuid,W=k.firstPrompt;W&&Nr(W,e).then(z=>z&&Al(q,z)).catch(()=>{})}}else P.type==="error"&&(U(),P.kind==="auth"&&(ft.current=!0),d({kind:"note",text:`agent error: ${P.message}`,tone:"error"}))}finally{H(!1),I(),ft.current&&(ft.current=!1,gt.current=l?.display??a,J(["/login"])),mt.current&&(mt.current=!1,je.current.length>0&&(d({kind:"note",tone:"info",text:`(${je.current.length} queued message(s) discarded)`}),je.current=[],oo([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,en,xe]),lo=G(a=>{let l=_e(a);if(!l||Ce(l)&&!l.refreshToken)return null;let i={...Ve(l.idToken)??{},...Ve(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),ao=G((a,l)=>{if(l){let i=ge(e);i&&(i.defaultProfile=a,Nl(i,e))}u(a),me(void 0,a),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${a}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),lo(a)||(d({kind:"note",tone:"warn",text:`Profile "${a}" is not signed in \u2014 do you want to log in now? (press 1)`}),J(["/login"])),ke(i=>i+1)},[e,d,me,lo]),tn=G((a,l,i)=>{vt(e,a,l,i.id),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),me(),Or(e,a)||(d({kind:"note",tone:"info",text:"Setup complete. Press tab to start with a docs analysis."}),le("analyze this repo and propose a docs structure"))},[e,d,me]),yt=G(()=>{let a=we.current[0];if(!a)return;d({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let i of a.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${i}`});a.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let l=Ee(a.oldContent,a.newContent,xe());d(l?{kind:"diff",added:l.added,removed:l.removed,lines:l.lines,hidden:l.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[d,xe]),on=G(a=>{if(we.current.length===0)return!1;let l=a.trim().toLowerCase();if(l==="y"||l==="yes"){let i=we.current.shift();try{Ol({cwd:e,profileName:s},i),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${i.path} (sync base advanced).`}),we.current.length===0&&J(k=>k.length>0?k:["/sync"])}catch(k){d({kind:"note",tone:"error",text:`Pull failed: ${k.message}`})}}else if(l==="n"||l==="no"){let i=we.current.shift();d({kind:"note",tone:"info",text:`Skipped ${i.path}.`})}else{let i=we.current.length;return we.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${i} article(s) left untouched).`}),!0}return yt(),!0},[e,s,yt,d]),nn=G(async a=>{let l=a.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),k=l.slice(1);switch(Kt(!0),i){case"help":d({kind:"note",tone:"info",text:qt.map(m=>` ${m.usage.padEnd(22)} ${m.desc}`).join(`
|
|
68
|
+
`)});return;case"exit":case"quit":te.current?.close(),r();return;case"clear":me(),Zt.current=[],Kt(!1),le(null),ct.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let m;try{m=ue(e,s)}catch(g){d({kind:"note",tone:"error",text:g.message});return}d({kind:"note",tone:"info",text:`Profile "${m.name}" \u2192 ${m.connection.name} (${m.connection.apiUrl})${m.production?" \u26A0 PRODUCTION":""}`}),ee(!0);try{let g=await Cl(m.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},R=>d({kind:"note",tone:"info",text:R})),w=Pl(m.name,g);Tl(w),po(w,m.name,R=>d({kind:"note",tone:"info",text:R})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${m.name}" as ${Pt(w)}`}),m.project.workspaceId||(d({kind:"note",tone:"info",text:"Next: pick the workspace your articles publish to."}),J(["/workspace"])),gt.current&&(le(gt.current),gt.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(g){d({kind:"note",tone:"error",text:`Login failed: ${g.message}`})}finally{ee(!1),ke(g=>g+1)}return}case"allow-prod":{let m=!1;try{m=ue(e,s).production}catch{}if(!m){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}eo.current=!0,me(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let m=k.join(" ").trim(),g=Pe.current.uuid;if(!g){d({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!m){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Pe.current.firstPrompt??"";Nr(w,e).then(R=>{R?(le(`/rename ${R}`),d({kind:"note",tone:"info",text:`Suggestion: "${R}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}_l(g,m),d({kind:"note",tone:"ok",text:`Session renamed to "${m}".`});return}case"profile":{let m=k[0],g=ge(e);if(!m){let w=Object.entries(g?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let R=w.map(([P,A])=>({name:P,env:A.connection?.environment??"custom",prod:A.production===!0,who:lo(P)})),I=s??g?.defaultProfile,U=Math.max(0,R.findIndex(P=>P.name===I));Oe({cursor:U,current:U,rows:R});return}if(m==="add"){let w=Eo(e,k[1],k[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${k[1]}" created (environment: ${k[2]??k[1]}).`}),ao(k[1],!1);return}if(!g?.profiles?.[m]){d({kind:"note",tone:"error",text:`Unknown profile "${m}". Create it: /profile add ${m} <environment>`});return}ao(m,!0);return}case"doctor":await at(k,{cwd:e});return;case"mcp":await At(k);return;case"init":{if(ge(e)){d({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 m=Fl().map(g=>({name:g,apiUrl:Bl(g).apiUrl}));Ue({cursor:0,rows:m});return}case"resume":{let m=k.join(" ").trim(),g=Ml(e).filter(R=>R.uuid!==Pe.current.uuid);if(!m){if(!g.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ae({query:"",cursor:0,sessions:g});return}let w=El(e,m);if(!w){d({kind:"note",tone:"error",text:`No session matches "${m}".`});return}me(w.uuid),Pe.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},Uo(w.uuid),d({kind:"note",tone:"ok",text:`Resumed "${w.name}".`});return}case"workspace":{let m=k.join(" ").trim(),g;try{g=await bt(e,s)}catch(R){d({kind:"note",tone:"error",text:`Could not list workspaces: ${R.message}`});return}if(!m){let R=g.workspaces.map(U=>({id:U.id,name:U.name??U.id,type:U.workspace_type}));if(R.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let I=Math.max(0,R.findIndex(U=>U.id===g.current));We({cursor:I,current:I,rows:R,profile:g.profile,projectId:g.projectId,environment:g.environment});return}let w=uo(g.workspaces,m);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${m}".`});return}tn(g.profile,g.projectId,w);return}case"publish":{if(k[0]&&k[0]!=="--all"){await De(Dt(k[0]),{display:`/publish ${k[0]}`,echoDisplay:!0});return}let m=k[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let g=await Wo({cwd:e,profileName:s}),w=It(g.entries);if(w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let I=g.counts["unknown-base"]??0;I>0&&d({kind:"note",tone:"info",text:`(${I} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(m){await De(rt(w.map(I=>I.path)),{display:"/publish --all",echoDisplay:!0});return}let R=w.length>1?[{path:"--all",label:`publish all ${w.length} candidates in one run`},...w]:w;Fe({cursor:0,rows:R})}catch(g){d({kind:"note",tone:"error",text:`Could not compute sync status: ${g.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let m=k.join(" ").trim();if(!m){let w=[];try{w=Object.keys(Or(e,ue(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Re({query:"",cursor:0,paths:w});return}let g=vl(m)?m:Xt(e,m);if($l(g)){try{d({kind:"preview",name:_r(g),text:Wr(Mr(g,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${g}: ${w.message}`})}return}if(Zl.test(m)){try{let w=ue(e,s),R={profile:w.name,connection:w.connection},I=w.project.projectId??Rl(R),U=await jl(R,I,m);d({kind:"preview",name:U.title??m,text:U.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${m}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let m=k[0]?.trim();if(!m){let I=Lt(Bo(e));Se({cursor:I,current:I});return}let{lines:g,changed:w,effective:R}=lt(e,m);for(let I of g)d({kind:"note",tone:I.startsWith("\u26A0")?"warn":I.startsWith("\u2713")?"ok":"info",text:I});w&&(Jo(I=>I+1),te.current?.setModel(R));return}case"convert":{if(!ge(e)){d({kind:"note",tone:"error",text:"No .d360-writer.json here. Run /init first."});return}let{scope:m,run:g}=So(k),w=ql(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let R=Ro(w,m);if(R.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${m}". (${w.length} are tracked overall.)`});return}let I=Hl(R),U=3,P=`/convert${m?` --scope ${m}`:""} --run`,A=Vl(e,"light");if(!g){let W=Gl({files:jo(e,R),op:"convert",model:A.model}),z=m?`Scope: ${m} (${R.length} of ${w.length} tracked)
|
|
69
|
+
`:"",fe=`
|
|
70
|
+
Model: ${A.model}${A.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:z+Io(I,W,U).join(`
|
|
71
|
+
`)+fe}),J([P]);return}ut.current=Date.now(),Qt(0),H(!0);let q=new AbortController;Je.current=q,Ke({total:I.length,done:0,active:[],tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${R.length} articles across ${I.length} partitions (\u2264${U} agents at once) on ${A.model}\u2026 (esc to stop)`});try{for await(let W of zl({cwd:e,partitions:I,promptFor:Ao,concurrency:U,profileName:s,allowProdWrites:eo.current,model:A.model,signal:q.signal}))if(W.type==="partition_status")W.status==="running"?(Ke(z=>z&&{...z,active:[...z.active,W.label],lastAt:Date.now()}),d({kind:"note",tone:"info",text:` \u25B8 ${W.label} \u2014 converting\u2026`})):(Ke(z=>z&&{...z,active:z.active.filter(fe=>fe!==W.label),done:z.done+1,lastAt:Date.now()}),d({kind:"note",tone:W.status==="done"?"ok":"error",text:` ${W.status==="done"?"\u2713":"\u2717"} ${W.label}`}));else if(W.type==="partition_event")Ke(z=>{if(!z)return z;let fe={...z,lastAt:Date.now()};return W.event.type==="tool"?fe.tools=z.tools+1:W.event.type==="text"&&(fe.chars=z.chars+W.event.delta.length),fe});else if(W.type==="run_done"){no(fe=>fe+W.totalCostUsd);let z=W.aborted?"Stopped. ":"";d({kind:"note",tone:W.aborted?"warn":W.ok?"ok":"warn",text:z+Do(W.results,W.totalCostUsd).join(`
|
|
72
|
+
`)})}}catch(W){d({kind:"note",tone:"error",text:`Convert run failed: ${W.message}`})}finally{Je.current=null,Ke(null),H(!1)}return}case"sync":{let m=(k[0]??"status").toLowerCase();try{if(m==="status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let g=await Wo({cwd:e,profileName:s});d({kind:"note",tone:"info",text:_t(g).join(`
|
|
73
|
+
`)});return}if(m==="pull"){let g=k[1];if(!g){d({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(g==="--all"){if(d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await Wo({cwd:e,profileName:s})).entries.filter(U=>U.status==="remote-ahead"&&U.path).map(U=>U.path),w.length===0){d({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 w=[g.replace(/\\/g,"/")];let R=[];for(let I of w)R.push(await Ul({cwd:e,profileName:s,relPath:I}));we.current=R,yt();return}d({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${m} \u2014 use /sync or /sync pull <path>|--all.`})}catch(g){d({kind:"note",tone:"error",text:`Sync failed: ${g.message}`})}return}case"scope":{if(!ge(e)){d({kind:"note",tone:"error",text:"No .d360-writer.json here. Run /init first."});return}let m=Wl(e);if(m.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}Be({cursor:0,rows:m.map(g=>({...g,checked:g.recommended}))});return}case"audit":case"screenshot":{if(i==="screenshot"&&!k[0]){d({kind:"note",tone:"error",text:"Usage: /screenshot <id>"});return}let g=await(i==="audit"?Et:Ot)(k,void 0);g.kind==="forward-to-agent"&&g.prompt&&await De(g.prompt,{display:g.display,echoDisplay:!0});return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,yt,d,me,De]),xt=G(a=>{let l=(a??T).trim();if(v(""),dt(null),Le(0),l.startsWith("/")){let k=g=>g.trim().split(/\s+/).slice(1).join(" "),m=k(l);J(g=>g.filter(w=>w.trim()!==l&&!(m&&k(w)===m)))}if(!l||on(l))return;to.current.push(l);let i=Rr(l,zo.current);l.startsWith("/")?nn(i):De(i,{display:l})},[T,on,nn,De]),rn=G(a=>{if(a.length>1){if(a.includes("\x1B"))return;let l=Pr(a);if(Tr(l)){let i=Sr(++Yr.current,l);zo.current.set(i,l),j(i)}else j(l);return}j(a)},[j]),He=Math.max(10,Ie-6),sn=Vt(()=>zt(f.text,He),[f.text,He]),co=G(a=>x(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+a))})),[]),$t=G(a=>x(l=>({...l,pos:Ar(zt(l.text,He),l.pos,a)})),[He]),Ze=G(a=>x(l=>({...l,pos:Ir(zt(l.text,He),l.pos,a)})),[He]),Kr=["\x1B[H","\x1B[1~","\x1BOH"],Qr=["\x1B[F","\x1B[4~","\x1BOF"],ln=G((a,l)=>l.leftArrow?(co(-1),!0):l.rightArrow?(co(1),!0):a&&Kr.includes(a)?(Ze("start"),!0):a&&Qr.includes(a)?(Ze("end"),!0):l.ctrl&&a==="a"?(Ze("start"),!0):l.ctrl&&a==="e"?(Ze("end"),!0):!1,[co,Ze]);return yl((a,l)=>{if(l.ctrl&&a==="c"){te.current?.close(),r();return}if(!B){if(_){if(l.escape){if(Je.current){Je.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),Je.current.abort());return}mt.current||(mt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),te.current?.interrupt());return}if(l.return){let i=T.trim();if(!i)return;je.current.push(i),oo([...je.current]),v("");return}if(ln(a,l))return;if(l.upArrow){$t(-1);return}if(l.downArrow){$t(1);return}if(l.backspace||l.delete){O();return}a&&!l.ctrl&&!l.meta&&rn(a);return}if(Te){if(l.upArrow){Se(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Se(i=>i&&{...i,cursor:Math.min(ce.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=ce.length){Se(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=ce[Te.cursor];Se(null);let{lines:k,changed:m,effective:g}=lt(e,i.value??"default");for(let w of k)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});m&&(Jo(w=>w+1),te.current?.setModel(g));return}if(a==="s"){let i=ce[Te.cursor];Se(null),te.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){Se(null);return}return}if(de){if(l.upArrow){Oe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Oe(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=de.rows.length){Oe(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return||a==="s"){let i=de.rows[de.cursor];Oe(null),ao(i.name,l.return===!0);return}if(l.escape){Oe(null);return}return}if(ye){if(l.upArrow){Ue(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ue(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=ye.rows.length){Ue(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=ye.rows[ye.cursor].name;if(Ue(null),!Pn(e,i).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 "${i}").`});let m=!1;try{let g=_e(i);m=!!g&&!(Ce(g)&&!g.refreshToken)}catch{}m?(d({kind:"note",tone:"info",text:`Already signed in to ${i} \u2014 next: pick a workspace.`}),J(["/workspace"])):(d({kind:"note",tone:"info",text:`Next: sign in to Document360 (${i}).`}),J(["/login"])),ke(g=>g+1);return}if(l.escape){Ue(null);return}return}if(K){if(l.upArrow){We(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){We(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=K.rows.length){We(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=K.rows[K.cursor],{profile:k,projectId:m}=K;We(null),tn(k,m,i);return}if(l.escape){We(null);return}return}if(Q){if(l.upArrow){Be(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Be(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a===" "){Be(i=>i&&{...i,rows:i.rows.map((k,m)=>m===i.cursor?{...k,checked:!k.checked}:k)});return}if(l.return){let i=Q.rows.filter(k=>k.checked).map(k=>k.path);if(Be(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}ko(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let k of i)d({kind:"note",tone:"info",text:` ${k}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Be(null);return}return}if(pe){if(l.upArrow){Fe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Fe(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=pe.rows.length){Fe(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=pe.rows[pe.cursor],k=pe.rows.filter(m=>m.path!=="--all").map(m=>m.path);Fe(null),De(i.path==="--all"?rt(k):Dt(i.path),{display:i.path==="--all"?"/publish --all":`/publish ${i.path}`,echoDisplay:!0});return}if(l.escape){Fe(null);return}return}if(oe){if(l.escape){Re(null);return}if(l.upArrow){Re(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Re(i=>i&&{...i,cursor:Math.min(Math.max(0,kt.length-1),i.cursor+1)});return}if(l.return){let i=kt[oe.cursor];if(i){Re(null);try{d({kind:"preview",name:_r(i),text:Wr(Mr(Xt(e,i),"utf8"))})}catch(k){d({kind:"note",tone:"error",text:`Could not read ${i}: ${k.message}`})}}return}if(l.backspace||l.delete){Re(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(a&&!l.ctrl&&!l.meta&&a.length===1){Re(i=>i&&{...i,query:i.query+a,cursor:0});return}return}if(ne){if(l.escape){Ae(null);return}if(l.upArrow){Ae(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ae(i=>i&&{...i,cursor:Math.min(Math.max(0,wt.length-1),i.cursor+1)});return}if(l.return){let i=wt[ne.cursor];i&&(Ae(null),me(i.uuid),Pe.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},Uo(i.uuid),d({kind:"note",tone:"ok",text:`Resumed "${i.name}".`}));return}if(l.backspace||l.delete){Ae(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(a&&!l.ctrl&&!l.meta&&a.length===1){Ae(i=>i&&{...i,query:i.query+a,cursor:0});return}return}if(l.tab&&!T&&ie){v(ie),le(null),ct.current++;return}if(!T&&Ye.length>0&&a&&/^[1-9]$/.test(a)){let i=Ye[Number(a)-1];if(i){v(i);return}}if(!ln(a,l)){if(Zo){if(l.upArrow){Le(i=>Math.max(0,i-1));return}if(l.downArrow){Le(i=>Math.min(Qe.length-1,i+1));return}if(l.tab){v("/"+(Qe[Xe]?.name??"")+" "),Le(0);return}if(l.return){let i=Qe[Xe];if(i){let k=T.trim().slice(1).split(/\s+/).slice(1).join(" ");if(vr(i.usage)&&!k){v("/"+i.name+" "),Le(0);return}xt("/"+i.name+(k?" "+k:""));return}}}else{if(l.upArrow){if(T!==""&&Ne===null){$t(-1);return}let i=to.current;if(!i.length)return;let k=Ne===null?i.length-1:Math.max(0,Ne-1);dt(k),v(i[k]??"");return}if(l.downArrow){if(T!==""&&Ne===null){$t(1);return}let i=to.current;if(Ne===null)return;let k=Ne+1;k>=i.length?(dt(null),v("")):(dt(k),v(i[k]??""));return}}if(l.return){xt();return}if(l.backspace||l.delete){O();return}if(l.escape){v(""),Le(0),le(null),J([]);return}a&&!l.ctrl&&!l.meta&&rn(a)}}}),Ge(()=>{if(_||B)return;let a=je.current.shift();a!==void 0&&(oo([...je.current]),xt(a))},[_,B,xt]),E(V,{flexDirection:"column",width:Ie,children:[io!==null&&E(V,{marginTop:1,flexDirection:"column",children:[io.truncated&&C(b,{dimColor:!0,children:"\u2026"}),C(b,{children:io.text})]}),_&&(Vo?C(na,{p:Vo}):C(ta,{startTime:ut.current,chars:Vr})),C(V,{borderStyle:"round",borderColor:Qo.prod?"yellow":F,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:T?sn.map((a,l)=>{let i=f.text.slice(a.start,a.end),k=l===Gt(sn,f.pos),m=Math.min(f.pos,a.end)-a.start;return E(b,{children:[C(b,{color:F,children:l===0?"> ":" "}),k?E(Fo,{children:[i.slice(0,m),C(Yt,{ch:i[m]??" "}),i.slice(m+1)]}):i||" "]},`${l}-${a.start}`)}):E(b,{children:[C(b,{color:F,children:"> "}),ie&&!_?E(Fo,{children:[C(Yt,{ch:ie[0],dim:!0}),C(b,{color:"gray",children:ie.slice(1)}),C(b,{dimColor:!0,children:" (tab)"})]}):so.isSetup||!Gr?E(Fo,{children:[C(Yt,{ch:so.text[0],dim:!0}),C(b,{color:"gray",children:so.text.slice(1)})]}):C(Yt,{ch:" "})]})}),Go.length>0&&C(V,{flexDirection:"column",paddingX:1,children:Go.map((a,l)=>C(b,{color:"gray",children:`\u29D7 queued: ${a}`},`${l}-${a.slice(0,24)}`))}),Te?E(V,{flexDirection:"column",paddingX:1,children:[C(b,{color:F,bold:!0,children:"Select model"}),C(b,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),ce.map((a,l)=>E(b,{color:l===Te.cursor?F:void 0,children:[l===Te.cursor?"\u276F ":" ",`${l+1}. ${a.label}${l===Te.current?" \u2714":""}`.padEnd(16),C(b,{color:"gray",children:a.desc})]},a.label)),C(b,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):de?E(V,{flexDirection:"column",paddingX:1,children:[C(b,{color:F,bold:!0,children:"Switch connection profile"}),de.rows.map((a,l)=>E(b,{color:l===de.cursor?F:void 0,children:[l===de.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===de.current?" \u2714":""}`.padEnd(20),C(b,{color:"gray",children:`${a.env} \xB7 ${a.who??"not signed in"}`}),a.prod?C(b,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},a.name)),C(b,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):ye?E(V,{flexDirection:"column",paddingX:1,children:[C(b,{color:F,bold:!0,children:"Pick your Document360 environment"}),ye.rows.map((a,l)=>E(b,{color:l===ye.cursor?F:void 0,children:[l===ye.cursor?"\u276F ":" ",`${l+1}. ${a.name}`.padEnd(16),C(b,{color:"gray",children:a.apiUrl})]},a.name)),C(b,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):K?E(V,{flexDirection:"column",paddingX:1,children:[C(b,{color:F,bold:!0,children:"Switch workspace"}),C(b,{dimColor:!0,children:`environment ${K.environment} \xB7 project ${K.projectId.slice(0,8)}\u2026`}),K.rows.map((a,l)=>E(b,{color:l===K.cursor?F:void 0,children:[l===K.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===K.current?" \u2714":""}`.padEnd(30),C(b,{color:"gray",children:a.type??""})]},a.id)),C(b,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):Q?(()=>{let l=Math.min(Math.max(0,Q.cursor-Math.floor(7)),Math.max(0,Q.rows.length-14)),i=Q.rows.slice(l,l+14),k=Q.rows.filter(m=>m.checked).length;return E(V,{flexDirection:"column",paddingX:1,children:[C(b,{color:F,bold:!0,children:`Which folders back the user docs? (${k} selected of ${Q.rows.length})`}),l>0?C(b,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((m,g)=>{let w=l+g;return E(b,{color:w===Q.cursor?F:void 0,children:[w===Q.cursor?"\u276F ":" ",m.checked?"\u25C9 ":"\u25CB ",m.path.padEnd(Math.min(48,Ie-34)),C(b,{color:"gray",children:Mt(m)})]},m.path)}),l+14<Q.rows.length?C(b,{dimColor:!0,children:` \u2193 ${Q.rows.length-l-14} more`}):null,C(b,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():pe?E(V,{flexDirection:"column",paddingX:1,children:[C(b,{color:F,bold:!0,children:"Publish which article?"}),pe.rows.map((a,l)=>E(b,{color:l===pe.cursor?F:void 0,children:[l===pe.cursor?"\u276F ":" ",`${l+1}. ${a.path}`.padEnd(Math.min(56,Ie-30)),C(b,{color:"gray",children:a.label})]},a.path)),C(b,{dimColor:!0,children:"enter publish (draft) \xB7 esc cancel"})]}):oe?E(V,{flexDirection:"column",paddingX:1,children:[C(b,{color:F,bold:!0,children:`Preview article${oe.query?` \u2014 filter: ${oe.query}`:" (type to filter)"}`}),kt.length===0?C(b,{color:"gray",children:"no articles match"}):kt.map((a,l)=>E(b,{color:l===oe.cursor?F:void 0,children:[l===oe.cursor?"\u276F ":" ",a]},a)),C(b,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ne?E(V,{flexDirection:"column",paddingX:1,children:[C(b,{color:F,bold:!0,children:`Resume session${ne.query?` \u2014 filter: ${ne.query}`:" (type to filter)"}`}),wt.length===0?C(b,{color:"gray",children:"no sessions match"}):wt.map((a,l)=>E(b,{color:l===ne.cursor?F:void 0,children:[l===ne.cursor?"\u276F ":" ",a.name.slice(0,28).padEnd(30),C(b,{color:l===ne.cursor?F:"gray",children:a.firstPrompt.slice(0,Math.max(10,Ie-40))})]},a.uuid)),C(b,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Zo?C(V,{flexDirection:"column",children:Qe.map((a,l)=>E(b,{color:l===Xe?F:void 0,children:[l===Xe?"\u276F ":" ",a.usage.padEnd(22)," ",C(b,{color:l===Xe?F:"gray",children:a.name==="model"&&ro?`${a.desc} (currently ${ro})`:a.desc})]},a.name))}):!T&&Ye.length>0?E(V,{flexDirection:"column",paddingX:1,children:[Ye.map((a,l)=>E(b,{children:[C(b,{color:F,children:l+1})," ",a.slice(0,Math.max(20,Ie-5))]},a)),C(b,{dimColor:!0,children:`press 1-${Ye.length} to fill the command \xB7 esc dismiss`})]}):C(V,{paddingX:1,children:E(b,{color:"gray",children:[Qo.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ro??"model n/a"}${ht>0?` \xB7 ${ht<1e3?`${ht} tokens`:`${(ht/1e3).toFixed(1)}k tokens`}`:""}${Xo>0?` \xB7 ${Me(Xo)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}L();import{jsx as ia}from"react/jsx-runtime";async function Hr(e=process.cwd(),t="auto",o,n="0.0.0"){let r=sa(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${y("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${y("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=ra(ia(Br,{cwd:e,auth:r,profileName:o,version:n}));await s(),process.stdout.write(`
|
|
74
|
+
`),process.exit(0)}var ua=aa(import.meta.url),qr=ua("../package.json"),he=new la;function Ho(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}he.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=>{Ho(e),await Tt({profile:e.profile,manual:e.manual})});he.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ho(e),await kn({profile:e.profile})});he.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Ho(e),await hn({profile:e.profile})});var qo=he.command("profile").description("Manage connection profiles for the current repo");qo.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>St(process.cwd()));qo.command("use <name>").description("Set the default profile for this repo").action(e=>Rt(process.cwd(),e));qo.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>jt(process.cwd(),e));var zr=he.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");zr.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>qe(process.cwd(),e.profile));zr.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await dn(process.cwd(),e,t.profile)});he.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>yn());he.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(()=>(Nt(),ar)),o=await t(process.cwd());for(let n of e(o))console.log(n);process.exitCode=o.some(n=>n.level==="fail")?1:0});he.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(qr.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(ca.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 xn(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 $r(e.cwd,e.auth,e.profile):await Hr(e.cwd,e.auth,e.profile,qr.version)});he.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|
|
@@ -13,7 +13,8 @@ export declare function sizeTargets(cwd: string, paths: string[]): {
|
|
|
13
13
|
path: string;
|
|
14
14
|
bytes: number;
|
|
15
15
|
}[];
|
|
16
|
-
/** The agent prompt for one partition.
|
|
16
|
+
/** The agent prompt for one partition. Mechanical + scoped + efficient — keep the agent from
|
|
17
|
+
over-exploring (the main driver of slow convert runs): no source reads, no re-verification. */
|
|
17
18
|
export declare function buildConvertPrompt(partition: Partition): string;
|
|
18
19
|
/** Preview lines for bare `/convert`: the partition plan + the cost band, before any spend. */
|
|
19
20
|
export declare function previewLines(partitions: Partition[], estimate: CostEstimate, concurrency: number): string[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "document360-writer",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.16",
|
|
4
4
|
"description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"@inquirer/prompts": "^8.4.3",
|
|
35
35
|
"commander": "^14.0.3",
|
|
36
36
|
"diff": "^8.0.4",
|
|
37
|
-
"document360-engine": "^0.2.
|
|
37
|
+
"document360-engine": "^0.2.9",
|
|
38
38
|
"ink": "^5.2.1",
|
|
39
39
|
"picocolors": "^1.1.1",
|
|
40
40
|
"react": "^18.3.1",
|