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