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