document360-writer 0.4.40 → 0.4.42
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 +61 -61
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,53 +1,53 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var pi=Object.defineProperty;var Yn=(e,t,o)=>()=>{if(o)throw o[0];try{return e&&(t=e(e=0)),t}catch(n){throw o=[n],n}};var fi=(e,t)=>{for(var o in t)pi(e,o,{get:t[o],enumerable:!0})};import Ae from"picocolors";var B,mi,gi,hi,Xn,mt,f,$,L,E,R,Q,Pe,H=Yn(()=>{"use strict";B="#7f56d9",[mi,gi,hi]=[127,86,217],Xn=e=>Ae.isColorSupported?`\x1B[38;2;${mi};${gi};${hi}m${e}\x1B[39m`:e,mt=e=>Ae.bold(Xn(e)),f=e=>Ae.dim(e),$=e=>Ae.red(e),L=e=>Ae.yellow(e),E=e=>Ae.green(e),R=Xn,Q=e=>Ae.gray(e),Pe=e=>Ae.bold(e)});var es={};fi(es,{doctorCommand:()=>bt,renderDoctorChecks:()=>Zr,runDoctorChecks:()=>Qr});import{existsSync as na}from"node:fs";import{d360GetAll as ra,getAccessToken as sa,isExpired as rn,loadProfileMap as ia,loadTokens as la,packageSkillsDir as Kr,projectConfigPath as aa,readProjectConfig as ca,resolveActiveProfile as ua,resolveAuth as da,resolveModelSetting as pa}from"document360-engine";async function Qr(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=da("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=pa(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=ca(e);if(!s)return t.push({level:"fail",label:`No ${aa(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/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let u=s.authoritativeSourceFiles??[];t.push(u.length>0?{level:"ok",label:`Sources: docs grounded in ${u.length} path(s) (${u.slice(0,3).join(", ")}${u.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let m;try{m=ua(e),t.push({level:"ok",label:`Profile: ${m.name} (${m.connection.name})${m.production?" \u26A0 PRODUCTION":""}`})}catch(D){return t.push({level:"fail",label:`Profile config: ${D.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let h=la(m.name);h?rn(h)&&!h.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):rn(h)?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(h.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${m.name})`}),t.push(m.project.workspaceId?{level:"ok",label:`Workspace: ${m.project.workspaceName??m.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let w=ia(e,m.name);if(w?w.projectId&&m.project.projectId&&w.projectId!==m.project.projectId?t.push({level:"fail",label:`Category map projectId (${w.projectId}) \u2260 profile projectId (${m.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(w.articles).length} articles, ${Object.keys(w.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${m.name}" (created on first /publish)`}),t.push(na(Kr())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Kr()}`,fix:"Reinstall document360-writer (broken install)"}),h&&(!rn(h)||h.refreshToken)){let D={profile:m.name,connection:m.connection};try{await sa(D);let b=await ra(D,"/v3/projects");t.push({level:"ok",label:`API reachable (${m.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 Zr(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?L("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${R(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"})`}`):$(`\u2717 ${o} problem${o===1?"":"s"} found`)),t.push(""),t}async function bt(e,t){console.log(f("Running checks\u2026"));for(let o of Zr(await Qr(t.cwd)))console.log(o);return{kind:"continue"}}var to=Yn(()=>{"use strict";H()});import{Command as au}from"commander";import{createRequire as cu}from"node:module";import{AUTH_MODES as uu}from"document360-engine";import{input as Si}from"@inquirer/prompts";import{loginPkce as Ti,refreshTokens as Ri,toStoredTokens as Qn,clearTokens as ji,decodeJwtClaims as Kn,isExpired as Ai,loadTokens as Ei,saveTokens as Zn,resolveActiveProfile as Wt,setProfileProject as Di,readProjectConfig as Ii}from"document360-engine";H();import{select as ki}from"@inquirer/prompts";import{resolveActiveProfile as yi,setProfileProject as wi,resolveProjectId as $i,listWorkspaces as xi}from"document360-engine";async function Ot(e,t){let o=yi(e,t),n={profile:o.name,connection:o.connection},r=o.project.projectId??$i(n);return{workspaces:await xi(n,r),projectId:r,profile:o.name,environment:o.connection.name,current:o.project.workspaceId}}var Vn=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function To(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 Ut(e,t,o,n,r){wi(e,t,{projectId:o,workspaceId:n,workspaceName:r})}async function Jn(e,t,o){let n;try{n=await Ot(e,o)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=To(n.workspaces,t);return r?(Ut(e,n.profile,n.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${n.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${n.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function tt(e,t){let o;try{o=await Ot(e,t)}catch(h){console.log($(`Could not list workspaces: ${h.message}`));return}let{workspaces:n,projectId:r,profile:s,current:c}=o;if(n.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let h of n)console.log(` ${h.id===c?R("\u25CF"):" "} ${Vn(h)} ${f(h.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let u=await ki({message:"Select the Document360 workspace for this repo:",choices:n.map(h=>({name:`${Vn(h)}${h.id===c?" (current)":""}`,value:h.id}))}),m=n.find(h=>h.id===u);Ut(e,s,r,u,m?.name),console.log(E(`\u2713 Workspace set to "${m?.name??u}" for profile "${s}".`))}H();import bi from"picocolors";function vi(e=process.env){return e.FORCE_HYPERLINK==="0"||!bi.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 Ci(e,t=e,o){return vi(o)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Pi=/https?:\/\/[^\s\x1b]+/g;function gt(e,t){return e.replace(Pi,o=>Ci(o,o,t))}function er(e){return{...Kn(e.idToken)??{},...Kn(e.accessToken)??{}}}function Ft(e){let t=er(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 Ht(e){let t=Wt(process.cwd(),e.profile),o=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${o.name} (${o.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let n=await Ti(o,{manual:e.manual,promptForRedirect:s=>Si({message:s})},s=>console.log(gt(s))),r=Qn(t.name,n);if(Zn(r),Ro(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Ft(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{Ii(process.cwd())?.profiles?.[t.name]&&(console.log(""),await tt(process.cwd(),t.name))}catch{}}function Ro(e,t,o){let r=er(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Wt(process.cwd(),t).project.projectId)return;Di(process.cwd(),t,{projectId:r}),o(` Project ${r} written to profile "${t}".`)}catch{}}async function tr(e){let t=Wt(process.cwd(),e.profile),o=t.connection,n=Ei(t.name);if(!n){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${R(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Ft(n)}`),Ai(n))if(n.refreshToken)try{let r=Qn(t.name,await Ri(o,n.refreshToken));Zn(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${n.expiresAt}`))}async function or(e){let t=Wt(process.cwd(),e.profile);ji(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as nr,writeProjectConfig as _i,resolveActiveProfile as Ni,loadTokens as Mi,isExpired as Li}from"document360-engine";function Bt(e){let t=nr(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[o,n]of Object.entries(t.profiles)){let r=o===t.defaultProfile?R("\u25CF "):" ",s=n.production?L(" \u26A0 PRODUCTION"):"",c=n.connection.environment??"(inline)",u=Mi(o),m=u?Li(u)&&!u.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${R(o)} \u2192 ${c}${s} [${m}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function qt(e,t){let o=nr(e);if(!o?.profiles?.[t]){let r=o?.profiles?Object.keys(o.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}o.defaultProfile=t,_i(o,e);let n=o.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${n}`))}function zt(e,t){try{let o=Ni(e,t);console.log(""),console.log(`Profile ${R(o.name)}${o.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${o.connection.apiUrl}`)),console.log(f(` identity: ${o.connection.authorizationUrl}`)),console.log(f(` clientId: ${o.connection.clientId}`)),console.log(f(` scopes: ${o.connection.scopes.join(" ")}`)),console.log(f(` project: ${o.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${o.project.workspaceId?" "+o.project.workspaceId:" (none)"}`)),console.log("")}catch(o){console.log($(o.message)),process.exitCode=1}}H();import{existsSync as Oi,readdirSync as Ui,statSync as Wi}from"node:fs";import{join as Fi}from"node:path";import{apiLogDir as Hi}from"document360-engine";function rr(){let e=Hi();if(console.log(""),console.log(`Document360 API logs: ${R(e)}`),!Oi(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ui(e).filter(o=>o.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let o of t.slice(0,14)){let n=(Wi(Fi(e,o)).size/1024).toFixed(1);console.log(` ${o} ${f(`${n} KB`)}`)}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}H();import{createSession as Bi,resolveAuth as qi,findByName as zi,slugify as Gi,touchSession as Yi,upsertSession as Xi,resolveActiveProfile as Vi}from"document360-engine";async function sr(e,t,o,n,r,s){let c=qi(o);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${R("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${R("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let u=null;try{u=Vi(e,r)}catch(b){console.error($(`Document360 profile error: ${b.message}`)),process.exit(2)}u.production&&(console.error(L(`\u26A0 Profile "${u.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let m;if(n){let b=zi(e,n);b||(console.error($(`No saved session matches "${n}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),m=b.uuid,console.error(f(`Resuming "${b.name}"`))}let h=Bi({cwd:e,resume:m,profileName:r,allowProdWrites:s===!0}),w=m??null,D=1;for await(let b of h.send(t))switch(b.type){case"session":if(!w){w=b.sessionId;let C=new Date().toISOString();Xi({uuid:w,name:Gi(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:C,updatedAt:C})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(Q(` \u2699 ${b.name}`));break;case"result":D=b.ok?0:1,console.error(f(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${b.message}`)),process.exit(1)}w&&Yi(w),process.stdout.write(`
|
|
3
|
-
`),process.exit(
|
|
2
|
+
var fi=Object.defineProperty;var Xn=(e,t,o)=>()=>{if(o)throw o[0];try{return e&&(t=e(e=0)),t}catch(n){throw o=[n],n}};var mi=(e,t)=>{for(var o in t)fi(e,o,{get:t[o],enumerable:!0})};import Ae from"picocolors";var B,gi,hi,ki,Vn,mt,f,$,L,E,R,Q,Pe,H=Xn(()=>{"use strict";B="#7f56d9",[gi,hi,ki]=[127,86,217],Vn=e=>Ae.isColorSupported?`\x1B[38;2;${gi};${hi};${ki}m${e}\x1B[39m`:e,mt=e=>Ae.bold(Vn(e)),f=e=>Ae.dim(e),$=e=>Ae.red(e),L=e=>Ae.yellow(e),E=e=>Ae.green(e),R=Vn,Q=e=>Ae.gray(e),Pe=e=>Ae.bold(e)});var ts={};mi(ts,{doctorCommand:()=>vt,renderDoctorChecks:()=>es,runDoctorChecks:()=>Zr});import{existsSync as ra}from"node:fs";import{d360GetAll as sa,getAccessToken as ia,isExpired as ln,loadProfileMap as la,loadTokens as aa,packageSkillsDir as Qr,projectConfigPath as ca,readProjectConfig as ua,resolveActiveProfile as da,resolveAuth as pa,resolveModelSetting as fa}from"document360-engine";async function Zr(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=pa("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=fa(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=ua(e);if(!s)return t.push({level:"fail",label:`No ${ca(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/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let d=s.authoritativeSourceFiles??[];t.push(d.length>0?{level:"ok",label:`Sources: docs grounded in ${d.length} path(s) (${d.slice(0,3).join(", ")}${d.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let g;try{g=da(e),t.push({level:"ok",label:`Profile: ${g.name} (${g.connection.name})${g.production?" \u26A0 PRODUCTION":""}`})}catch(I){return t.push({level:"fail",label:`Profile config: ${I.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let k=aa(g.name);k?ln(k)&&!k.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):ln(k)?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(k.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.workspaceName??g.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let w=la(e,g.name);if(w?w.projectId&&g.project.projectId&&w.projectId!==g.project.projectId?t.push({level:"fail",label:`Category map projectId (${w.projectId}) \u2260 profile projectId (${g.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(w.articles).length} articles, ${Object.keys(w.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${g.name}" (created on first /publish)`}),t.push(ra(Qr())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Qr()}`,fix:"Reinstall document360-writer (broken install)"}),k&&(!ln(k)||k.refreshToken)){let I={profile:g.name,connection:g.connection};try{await ia(I);let b=await sa(I,"/v3/projects");t.push({level:"ok",label:`API reachable (${g.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 es(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?L("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${R(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"})`}`):$(`\u2717 ${o} problem${o===1?"":"s"} found`)),t.push(""),t}async function vt(e,t){console.log(f("Running checks\u2026"));for(let o of es(await Zr(t.cwd)))console.log(o);return{kind:"continue"}}var oo=Xn(()=>{"use strict";H()});import{Command as cu}from"commander";import{createRequire as uu}from"node:module";import{AUTH_MODES as du}from"document360-engine";import{input as Ti}from"@inquirer/prompts";import{loginPkce as Ri,refreshTokens as ji,toStoredTokens as Zn,clearTokens as Ai,decodeJwtClaims as Qn,isExpired as Ei,loadTokens as Di,saveTokens as er,resolveActiveProfile as Ft,setProfileProject as Ii,readProjectConfig as _i}from"document360-engine";H();import{select as yi}from"@inquirer/prompts";import{resolveActiveProfile as wi,setProfileProject as $i,resolveProjectId as xi,listWorkspaces as bi}from"document360-engine";async function gt(e,t){let o=wi(e,t),n={profile:o.name,connection:o.connection},r=o.project.projectId??xi(n);return{workspaces:await bi(n,r),projectId:r,profile:o.name,environment:o.connection.name,current:o.project.workspaceId}}var Jn=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function jo(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 Wt(e,t,o,n,r){$i(e,t,{projectId:o,workspaceId:n,workspaceName:r})}async function Kn(e,t,o){let n;try{n=await gt(e,o)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=jo(n.workspaces,t);return r?(Wt(e,n.profile,n.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${n.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${n.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function tt(e,t){let o;try{o=await gt(e,t)}catch(k){console.log($(`Could not list workspaces: ${k.message}`));return}let{workspaces:n,projectId:r,profile:s,current:c}=o;if(n.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let k of n)console.log(` ${k.id===c?R("\u25CF"):" "} ${Jn(k)} ${f(k.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let d=await yi({message:"Select the Document360 workspace for this repo:",choices:n.map(k=>({name:`${Jn(k)}${k.id===c?" (current)":""}`,value:k.id}))}),g=n.find(k=>k.id===d);Wt(e,s,r,d,g?.name),console.log(E(`\u2713 Workspace set to "${g?.name??d}" for profile "${s}".`))}H();import vi from"picocolors";function Ci(e=process.env){return e.FORCE_HYPERLINK==="0"||!vi.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 Pi(e,t=e,o){return Ci(o)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Si=/https?:\/\/[^\s\x1b]+/g;function ht(e,t){return e.replace(Si,o=>Pi(o,o,t))}function tr(e){return{...Qn(e.idToken)??{},...Qn(e.accessToken)??{}}}function Ht(e){let t=tr(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 Bt(e){let t=Ft(process.cwd(),e.profile),o=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${o.name} (${o.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let n=await Ri(o,{manual:e.manual,promptForRedirect:s=>Ti({message:s})},s=>console.log(ht(s))),r=Zn(t.name,n);if(er(r),Ao(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${Ht(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{_i(process.cwd())?.profiles?.[t.name]&&(console.log(""),await tt(process.cwd(),t.name))}catch{}}function Ao(e,t,o){let r=tr(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Ft(process.cwd(),t).project.projectId)return;Ii(process.cwd(),t,{projectId:r}),o(` Project ${r} written to profile "${t}".`)}catch{}}async function or(e){let t=Ft(process.cwd(),e.profile),o=t.connection,n=Di(t.name);if(!n){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${R(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Ht(n)}`),Ei(n))if(n.refreshToken)try{let r=Zn(t.name,await ji(o,n.refreshToken));er(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(L(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(L("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${n.expiresAt}`))}async function nr(e){let t=Ft(process.cwd(),e.profile);Ai(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}H();import{readProjectConfig as rr,writeProjectConfig as Ni,resolveActiveProfile as Mi,loadTokens as Li,isExpired as Oi}from"document360-engine";function qt(e){let t=rr(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[o,n]of Object.entries(t.profiles)){let r=o===t.defaultProfile?R("\u25CF "):" ",s=n.production?L(" \u26A0 PRODUCTION"):"",c=n.connection.environment??"(inline)",d=Li(o),g=d?Oi(d)&&!d.refreshToken?L("expired"):f("logged in"):f("not logged in");console.log(`${r}${R(o)} \u2192 ${c}${s} [${g}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function zt(e,t){let o=rr(e);if(!o?.profiles?.[t]){let r=o?.profiles?Object.keys(o.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}o.defaultProfile=t,Ni(o,e);let n=o.profiles[t].production?L(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${n}`))}function Gt(e,t){try{let o=Mi(e,t);console.log(""),console.log(`Profile ${R(o.name)}${o.production?L(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${o.connection.apiUrl}`)),console.log(f(` identity: ${o.connection.authorizationUrl}`)),console.log(f(` clientId: ${o.connection.clientId}`)),console.log(f(` scopes: ${o.connection.scopes.join(" ")}`)),console.log(f(` project: ${o.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${o.project.workspaceId?" "+o.project.workspaceId:" (none)"}`)),console.log("")}catch(o){console.log($(o.message)),process.exitCode=1}}H();import{existsSync as Ui,readdirSync as Wi,statSync as Fi}from"node:fs";import{join as Hi}from"node:path";import{apiLogDir as Bi}from"document360-engine";function sr(){let e=Bi();if(console.log(""),console.log(`Document360 API logs: ${R(e)}`),!Ui(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Wi(e).filter(o=>o.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let o of t.slice(0,14)){let n=(Fi(Hi(e,o)).size/1024).toFixed(1);console.log(` ${o} ${f(`${n} KB`)}`)}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}H();import{createSession as qi,resolveAuth as zi,findByName as Gi,slugify as Yi,touchSession as Xi,upsertSession as Vi,resolveActiveProfile as Ji}from"document360-engine";async function ir(e,t,o,n,r,s){let c=zi(o);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${R("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${R("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let d=null;try{d=Ji(e,r)}catch(b){console.error($(`Document360 profile error: ${b.message}`)),process.exit(2)}d.production&&(console.error(L(`\u26A0 Profile "${d.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let g;if(n){let b=Gi(e,n);b||(console.error($(`No saved session matches "${n}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),g=b.uuid,console.error(f(`Resuming "${b.name}"`))}let k=qi({cwd:e,resume:g,profileName:r,allowProdWrites:s===!0}),w=g??null,I=1;for await(let b of k.send(t))switch(b.type){case"session":if(!w){w=b.sessionId;let C=new Date().toISOString();Vi({uuid:w,name:Yi(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:C,updatedAt:C})}break;case"text":process.stdout.write(b.delta);break;case"tool":console.error(Q(` \u2699 ${b.name}`));break;case"result":I=b.ok?0:1,console.error(f(`(${b.inputTokens}\u2192${b.outputTokens} tokens`+(b.costUsd>0?`, $${b.costUsd<.01?b.costUsd.toFixed(4):b.costUsd.toFixed(2)}`:"")+")")),b.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${b.message}`)),process.exit(1)}w&&Xi(w),process.stdout.write(`
|
|
3
|
+
`),process.exit(I)}import{createInterface as Ya}from"node:readline/promises";import{createSession as wn,resolveAuth as Xa,getSession as Va,setTitle as Ja,slugify as Ka,touchSession as Cs,upsertSession as Qa,generateTitle as Za,resolveActiveProfile as Ps,resolveModelSetting as ec,readProjectConfig as tc,decodeJwtClaims as bs,isExpired as oc,loadTokens as nc}from"document360-engine";var kt=[{name:"init",usage:"/init",desc:"Pick an environment & scaffold .d360-writer.json",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"write",usage:"/write [--all|--scope <cat>|<path>] [--run]",desc:"Author the planned articles in parallel (bare = preview + cost; --run starts)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit",desc:"Gap analysis: code vs docs vs Document360 (what changed)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all]",desc:"Drift report local vs Document360; pull portal edits",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Ki=[{key:"start",label:"Start here"},{key:"docs",label:"Write & screenshots"},{key:"publish",label:"Publish & keep in sync"},{key:"setup",label:"Setup & health"},{key:"session",label:"Session"}];function Yt(){let e=Math.max(...kt.map(o=>o.usage.length))+2,t=["document360-writer \u2014 commands","",'New here? /init \u2192 "write the docs for this repo" \u2192 /publish',""," Screenshots are optional \u2014 add them anytime:"," /screenshot --all \u2192 d360-capture capture \u2192 re-/publish"];for(let{key:o,label:n}of Ki){t.push("",n);for(let r of kt.filter(s=>s.group===o))t.push(` ${r.usage.padEnd(e)}${r.desc}`)}return t.push("","Tip: anything not starting with / is sent to the agent."),t}function lr(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return kt.filter(o=>o.name.startsWith(t))}function ar(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function Eo(){console.log("");for(let e of Yt())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}H();import{getSession as Qi}from"document360-engine";async function cr(e,t){let o=t.currentUuid(),n=o?Qi(o):void 0;return console.log(n?f(`
|
|
4
4
|
(conversation reset \u2014 "${n.name}" is still available via /resume)
|
|
5
5
|
`):f(`
|
|
6
6
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
7
|
-
`)),{kind:"clear"}}async function
|
|
8
|
-
`),"utf8")}async function
|
|
7
|
+
`)),{kind:"clear"}}async function Do(){return{kind:"exit"}}H();import{input as yt,confirm as Zi}from"@inquirer/prompts";import{basename as ur,join as Xt}from"node:path";import{existsSync as ot,readFileSync as el,readdirSync as tl,writeFileSync as ol}from"node:fs";import{writeProjectConfig as dr,readProjectConfig as nl,projectConfigPath as pr,writerDir as rl}from"document360-engine";function fr(e,t="berlin"){let o=pr(e);if(ot(o))return{created:!1,path:o,profileName:""};let n={projectId:hr(e)??ur(e),captureDir:"user-docs/_capture",outputDir:"user-docs/_screenshots",profiles:{[t]:{connection:{environment:t},production:!1}},defaultProfile:t,authoritativeSourceFiles:kr(e)};return dr(n,e),mr(e),{created:!0,path:o,profileName:t}}function mr(e){let t=Xt(rl(e),".gitignore");ot(t)||ol(t,["# Local/transient \u2014 the config files here ARE meant to be committed.",".sessions/","cache/",""].join(`
|
|
8
|
+
`),"utf8")}async function gr(){let e=process.cwd(),t=pr(e);if(ot(t)&&!await Zi({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(f("init cancelled.")),{kind:"continue"};let o=hr(e)??ur(e),n=await yt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:o}),r=await yt({message:"Capture directory (where document360-capture .spec.ts files live):",default:"user-docs/_capture"}),s=await yt({message:"Screenshot output directory:",default:"user-docs/_screenshots"}),c=await yt({message:"Default connection profile name:",default:"berlin"}),d=await yt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),g={projectId:n,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:d},production:!1}},defaultProfile:c,authoritativeSourceFiles:kr(e)},k=nl(e);return k?.terminologyGlossary&&(g.terminologyGlossary=k.terminologyGlossary),dr(g,e),mr(e),console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log("Next:"),console.log(` ${R(`d360-writer login --profile ${c}`)} ${f("(sign in; pick the project)")}`),console.log(' Then ask the agent: "analyze this repo and propose a docs structure"'),console.log(""),{kind:"continue"}}function hr(e){let t=Xt(e,"package.json");if(!ot(t))return null;try{return JSON.parse(el(t,"utf8")).name??null}catch{return null}}function kr(e){let t=[];for(let o of["README.md","ARCHITECTURE.md","CLAUDE.md"])ot(Xt(e,o))&&t.push(o);for(let o of["src","api","docs"]){let n=Xt(e,o);ot(n)&&!sl(n)&&t.push(o)}return t}function sl(e){try{return tl(e,{withFileTypes:!0}).filter(o=>o.isDirectory()&&!o.name.startsWith(".")).length>6}catch{return!1}}H();import{readMcpConfig as Io,writeMcpConfig as yr}from"document360-engine";async function Vt(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(il(),{kind:"continue"}):t==="add"?(ll(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(al(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(f("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function il(){let e=Io(),t=Object.keys(e.servers);if(t.length===0){console.log(f(`
|
|
9
9
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
10
|
-
`));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(` ${R(o)} ${f("(stdio)")} ${n.command} ${(n.args??[]).join(" ")}`);else{let r=Object.keys(n.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${R(o)} ${f(`(${n.type})`)} ${n.url}${s}`)}}console.log("")}function
|
|
11
|
-
`)}var
|
|
12
|
-
`)}async function
|
|
13
|
-
`),display:"/audit"}}H();import{checkbox as
|
|
10
|
+
`));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(` ${R(o)} ${f("(stdio)")} ${n.command} ${(n.args??[]).join(" ")}`);else{let r=Object.keys(n.headers??{}),s=r.length>0?f(` [headers: ${r.join(", ")}]`):"";console.log(` ${R(o)} ${f(`(${n.type})`)} ${n.url}${s}`)}}console.log("")}function ll(e){let[t,o,...n]=e;if(!t||!o||n.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(o!=="stdio"&&o!=="http"&&o!=="sse"){console.log($(`Unknown transport: ${o}. Use stdio, http, or sse.`));return}let r=Io(),s;if(o==="stdio")s={type:"stdio",command:n[0],args:n.slice(1)};else{let c={};for(let d=1;d<n.length;d++)if(n[d]==="-H"||n[d]==="--header"){let g=n[++d],k=g?.match(/^([^:=]+)[:=](.+)$/);if(!k){console.log($(`-H expects key:value (no spaces). Got: ${g??"(nothing)"}`));return}c[k[1].trim()]=k[2].trim()}else{console.log($(`Unexpected argument: ${n[d]}. 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,yr(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${o})`)),console.log(L(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(f(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function al(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let o=Io();if(!o.servers[t]){console.log($(`No server named "${t}".`));return}delete o.servers[t],yr(o),console.log(E(`\u2713 Removed "${t}".`)),console.log(f(" Run /clear to drop it from the current session immediately."))}H();import{select as cl}from"@inquirer/prompts";import{computeSyncStatus as wr}from"document360-engine";function Kt(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(`
|
|
11
|
+
`)}var $r={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Jt(e){return e.filter(t=>t.path!==null&&t.status in $r).map(t=>({path:t.path,label:$r[t.status]}))}function wt(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(`
|
|
12
|
+
`)}async function xr(e,t){let o=e[0];if(o==="--all"){console.log(f("Checking what needs publishing\u2026"));try{let n=Jt((await wr({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:wt(n.map(r=>r.path)),display:"/publish --all"}}catch(n){return console.log($(`Could not compute sync status: ${n.message}`)),{kind:"continue"}}}if(!o){console.log(f("Checking what needs publishing\u2026"));let n;try{n=Jt((await wr({cwd:t?.cwd??process.cwd()})).entries)}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),console.log(f("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(f(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let r of n)console.log(` ${r.path} ${f(`(${r.label})`)}`);return console.log(f("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>cl({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(f("Cancelled.")),{kind:"continue"}}if(o==="--all")return{kind:"forward-to-agent",prompt:wt(n.map(r=>r.path)),display:"/publish --all"}}return{kind:"forward-to-agent",prompt:Kt(o),display:`/publish ${o}`}}async function Qt(){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(`
|
|
13
|
+
`),display:"/audit"}}H();import{checkbox as ul}from"@inquirer/prompts";import{inventoryRepo as dl,readProjectConfig as br,writeProjectConfig as pl}from"document360-engine";function _o(e,t){let o=br(e);o&&(o.authoritativeSourceFiles=t,pl(o,e))}function Zt(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 vr(e,t){let o=t?.cwd??process.cwd();if(!br(o))return console.log($("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let n=dl(o);if(n.length===0)return console.log(f('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(R("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of n)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${f(Zt(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>ul({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:n.map(s=>({name:`${s.path} (${Zt(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(f("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};_o(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"}}H();import{confirm as kl}from"@inquirer/prompts";import{applyPull as Rr,computeSyncStatus as jr,planPull as yl,D360AuthError as wl}from"document360-engine";H();var Cr=[{status:"conflict",header:"Conflicts \u2014 both sides changed; pick a direction (/sync pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Local ahead \u2014 push with /publish <path>:",paint:L,mark:"M"},{status:"remote-ahead",header:"Remote ahead \u2014 pull with /sync pull <path>:",paint:R,mark:"M"},{status:"deleted-local",header:"Deleted locally \u2014 still on Document360 (pull to restore, or remove from the map):",paint:$,mark:"D"},{status:"deleted-remote",header:"Deleted on Document360 \u2014 still local (publish to recreate, or delete the file):",paint:$,mark:"D"},{status:"orphaned",header:"Orphaned map entries \u2014 gone on both sides (remove from d360-category-map.json):",paint:Q,mark:"X"},{status:"untracked-local",header:"Untracked local articles \u2014 publish to start tracking:",paint:f,mark:"?"},{status:"untracked-remote",header:"Untracked Document360 articles \u2014 no local file maps to them:",paint:f,mark:"?"},{status:"unknown-base",header:"No sync base recorded yet \u2014 the next /publish or /sync pull of each records one:",paint:Q,mark:"\xB7"}];function fl(e){return e.path?e.path:`${e.title??"(untitled)"} ${Q(`[${e.articleId}]`)}`}function eo(e){let t=[];for(let c of Cr){let d=e.entries.filter(g=>g.status===c.status);if(d.length!==0){t.push(""),t.push(Pe(c.header));for(let g of d)t.push(` ${c.paint(c.mark)} ${c.paint(fl(g))}${g.detail?Q(` (${g.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,...Cr.map(c=>{let d=e.counts[c.status]??0;return d>0?`${d} ${r[c.status]}`:null})].filter(Boolean).join(Q(" \xB7 "));return t.push(s+Q(` \xB7 ${n} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as ml}from"diff";import Pr from"picocolors";var Sr=80,gl="\x1B[48;2;74;28;28m",hl="\x1B[48;2;24;66;24m",Tr="\x1B[49m",No=e=>String(e).padStart(5);function Fe(e,t,o){let n=b=>{let C=b.replace(/\r\n/g,`
|
|
14
14
|
`);return C.endsWith(`
|
|
15
15
|
`)||C===""?C:C+`
|
|
16
|
-
`},r=n(e),s=n(t);if(r===s)return null;let c=Math.max(20,o-10),
|
|
17
|
-
`),o=[],n=0;for(;n<t.length;){let r=t[n];if(/^\s*```/.test(r)){let
|
|
18
|
-
`)}),G=Math.max(...z.map(me=>me.length)),
|
|
19
|
-
`)},C=[w("\u250C","\u252C","\u2510"),b(e,!0)];return C.push(t.length===0?w("\u2514","\u2534","\u2518"):w("\u251C","\u253C","\u2524")),t.forEach((x,
|
|
20
|
-
`)}function
|
|
16
|
+
`},r=n(e),s=n(t);if(r===s)return null;let c=Math.max(20,o-10),d=ml("a","b",r,s,"","",{context:3}),g=0,k=0,w=[];d.hunks.forEach((b,C)=>{C>0&&w.push(Pr.gray(" \u2026"));let x=b.oldStart,_=b.newStart;for(let z of b.lines){let G=z[0],ae=z.slice(1).slice(0,c);G==="-"?(k++,w.push(`${gl}${No(x++)} - ${ae}${Tr}`)):G==="+"?(g++,w.push(`${hl}${No(_++)} + ${ae}${Tr}`)):(w.push(Pr.gray(No(_))+" "+ae),x++,_++)}});let I=w.slice(0,Sr);return{added:g,removed:k,lines:I,hidden:Math.max(0,w.length-Sr)}}async function Ar(e,t){let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await $l(t.cwd),{kind:"continue"};if(o==="pull")return await xl(t,e.slice(1)),{kind:"continue"};console.log($(`Unknown subcommand: /sync ${o}`)),console.log(f("Usage: /sync drift report (local vs Document360)")),console.log(f(" /sync pull <path> pull portal edits into the local file")),console.log(f(" /sync pull --all pull every remote-ahead article"))}catch(n){n instanceof wl?console.log($(n.message)):console.log($(`Sync failed: ${n.message}`))}return{kind:"continue"}}async function $l(e){console.log(f("Checking Document360 for drift\u2026"));let t=await jr({cwd:e});for(let o of eo(t))console.log(o);console.log("")}async function xl(e,t){let o=t[0];if(!o){console.log($("Usage: /sync pull <article-path> | --all"));return}let n;if(o==="--all"){if(console.log(f("Checking Document360 for drift\u2026")),n=(await jr({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(f(" (conflicts are never bulk-pulled; pull them one by one: /sync pull <path>)"));return}console.log(`${Pe(String(n.length))} article(s) are remote-ahead.`)}else n=[o.replace(/\\/g,"/")];for(let r of n){let s=await yl({cwd:e.cwd,relPath:r});console.log(""),console.log(`${R("\u25CF")} ${Pe(s.title)} ${Q(`(${s.path})`)}`);for(let k of s.notes)console.log(L(` \u26A0 ${k}`));s.overwritesLocalChanges&&console.log(L(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=Fe(s.oldContent,s.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!c){console.log(f(" Local file already matches the remote content \u2014 advancing the sync base only.")),Rr({cwd:e.cwd},s);continue}let d=k=>k===1?"":"s";console.log(Q(` \u23BF Added ${c.added} line${d(c.added)}, removed ${c.removed} line${d(c.removed)}`));for(let k of c.lines)console.log(k);if(c.hidden>0&&console.log(f(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>kl({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(f(" Skipped."));continue}Rr({cwd:e.cwd},s),console.log(E(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}H();import{statSync as Dl}from"node:fs";import{resolve as Il}from"node:path";import{estimateBulkCost as _l,planPartitions as Nl,readProjectConfig as Ml,resolveModelForOperation as Ll,runPartitioned as Ol,trackedArticlePaths as Ul}from"document360-engine";import q from"picocolors";import Mr from"wrap-ansi";import Fo from"string-width";H();import Ee from"picocolors";import Mo from"wrap-ansi";import Lo from"string-width";var Er=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),Dr=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),Ir=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function bl(e){let t=e.replace(/\r/g,"").split(`
|
|
17
|
+
`),o=[],n=0;for(;n<t.length;){let r=t[n];if(/^\s*```/.test(r)){let d=[];for(n++;n<t.length&&!/^\s*```/.test(t[n]);)d.push(t[n++]);n++,o.push({kind:"code",lines:d});continue}if(Er(r)){o.push({kind:"hr"}),n++;continue}if(r.includes("|")&&n+1<t.length&&Dr(t[n+1])){let d=Ir(r);n+=2;let g=[];for(;n<t.length&&t[n].includes("|")&&t[n].trim()!=="";)g.push(Ir(t[n++]));o.push({kind:"table",header:d,rows:g});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 d=[];for(;n<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[n]);)d.push(t[n++].replace(/^\s*([-*]|\d+\.)\s+/,""));o.push({kind:"list",items:d});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])&&!Er(t[n])&&!(t[n].includes("|")&&n+1<t.length&&Dr(t[n+1]));)c.push(t[n++]);o.push({kind:"para",text:c.join(" ")})}return o}function Oo(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Ee.bold(t.slice(2,-2)):t.startsWith("`")?R(t.slice(1,-1)):Ee.italic(t.slice(1,-1)))}var vl=(e,t)=>e+" ".repeat(Math.max(0,t-Lo(e)));function Cl(e,t,o){let n=e.length,r=e.map((x,_)=>Math.max(Lo(x),...t.map(z=>Lo(z[_]??"")))),s=Math.max(24,o),c=3*n+1,d=[...r],g=()=>d.reduce((x,_)=>x+_,0)+c,k=0;for(;g()>s&&k++<1e4;){let x=-1,_=6;for(let z=0;z<n;z++)d[z]>_&&(_=d[z],x=z);if(x===-1)break;d[x]-=1}let w=(x,_,z)=>Ee.gray(x+d.map(G=>"\u2500".repeat(G+2)).join(_)+z),I=Ee.gray("\u2502"),b=(x,_)=>{let z=d.map((me,we)=>{let ge=x[we]??"",he=_?Ee.bold(ge):Oo(ge);return Mo(he,me,{hard:!0}).split(`
|
|
18
|
+
`)}),G=Math.max(...z.map(me=>me.length)),ae=[];for(let me=0;me<G;me++)ae.push(d.map((we,ge)=>`${I} ${vl(z[ge][me]??"",we)} `).join("")+I);return ae.join(`
|
|
19
|
+
`)},C=[w("\u250C","\u252C","\u2510"),b(e,!0)];return C.push(t.length===0?w("\u2514","\u2534","\u2518"):w("\u251C","\u253C","\u2524")),t.forEach((x,_)=>{C.push(b(x,!1)),C.push(_===t.length-1?w("\u2514","\u2534","\u2518"):w("\u251C","\u253C","\u2524"))}),C.join(`
|
|
20
|
+
`)}function Pl(e,t){switch(e.kind){case"heading":return Ee.bold(e.text);case"hr":return Ee.gray("\u2500".repeat(t));case"para":return Mo(Oo(e.text),t);case"list":return e.items.map(o=>{let[n="",...r]=Mo(Oo(o),Math.max(10,t-4)).split(`
|
|
21
21
|
`);return" \u2022 "+n+r.map(s=>`
|
|
22
22
|
`+s).join("")}).join(`
|
|
23
23
|
`);case"code":return e.lines.map(o=>Ee.gray(" "+o)).join(`
|
|
24
|
-
`);case"table":return
|
|
24
|
+
`);case"table":return Cl(e.header,e.rows,t)}}function Uo(e,t){let o=Math.max(20,t);return bl(e).map(n=>Pl(n,o)).join(`
|
|
25
25
|
|
|
26
|
-
`)}H();import
|
|
27
|
-
`);let r=2,s=3,c=
|
|
28
|
-
`);let
|
|
29
|
-
`)}var
|
|
30
|
-
`).flatMap(
|
|
31
|
-
`)),
|
|
32
|
-
`+
|
|
26
|
+
`)}H();import Sl from"picocolors";var Tl=[127,86,217],Rl=[22,38,43],_r={T:Tl,E:Rl},$t=["..TTTTTT....","..TTTTTTT...","..TTTTTTTT..","..TTETTETT..","..TTETTETT..","..TTTTTTTT..","..TTTTTTT...","..TTTTTT....","...T..T....."],Wo=([e,t,o])=>`\x1B[38;2;${e};${t};${o}m`,jl=([e,t,o])=>`\x1B[48;2;${e};${t};${o}m`;function Nr(){if(!Sl.isColorSupported)return[];let e=$t[0].length,t=[];for(let o=0;o<$t.length;o+=2){let n="";for(let r=0;r<e;r++){let s=_r[$t[o][r]],c=o+1<$t.length?_r[$t[o+1][r]]:void 0;s&&c?n+=`${Wo(s)}${jl(c)}\u2580\x1B[49m\x1B[39m`:s?n+=`${Wo(s)}\u2580\x1B[39m`:c?n+=`${Wo(c)}\u2584\x1B[39m`:n+=" "}t.push(n)}return t}function xt(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function fe(e){return e<=0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function rt(e){return e<1e3?`${e} tokens`:e<1e6?`${(e/1e3).toFixed(1)}k tokens`:`${(e/1e6).toFixed(2)}M tokens`}var nt=(e,t)=>` ${e.padEnd(13)}${t}`;function Al(e,t){let o=[mt("\u270E document360-writer")+q.gray(` v${e.version}`),q.gray(" Reads your code, writes your docs."),"",nt("Claude:",`${e.claude}${q.gray(` \xB7 ${e.model}${e.modelSource?` (${e.modelSource})`:""}`)}`),nt("Document360:",e.configured?e.loggedOut?q.yellow("not logged in \u2014 run /login"):`${e.who??""}${e.sessionHint?q.gray(` (${e.sessionHint})`):""}`:q.yellow("not set up \u2014 run /init")),nt("Profile:",e.configured?`${e.profile}${q.gray(` (${e.apiUrl})`)}${e.prod?q.bold(q.yellow(" \u26A0 PRODUCTION")):""}`:q.gray("\u2014 (run /init)")),nt("Project:",e.project),nt("Mode:",q.gray(e.mode)),nt("cwd:",q.gray(e.cwd))],n=Nr();if(n.length===0)return o.join(`
|
|
27
|
+
`);let r=2,s=3,c=Fo(n[0]);if(!(t>=r+c+s+Math.max(...o.map(w=>Fo(w)))))return[...n.map(w=>" "+w),...o].join(`
|
|
28
|
+
`);let g=Math.max(0,Math.floor((o.length-n.length)/2)),k=[];for(let w=0;w<Math.max(n.length+g,o.length);w++){let I=n[w-g]??" ".repeat(c);k.push((" ".repeat(r)+I+" ".repeat(s)+(o[w]??"")).trimEnd())}return k.join(`
|
|
29
|
+
`)}var El={error:q.red,warn:q.yellow,ok:q.green,info:q.gray};function Ho(e,t){let o=Math.max(20,t);switch(e.kind){case"banner":return Al(e.info,o);case"user":{let n="\x1B[48;2;42;42;46m",r="\x1B[49m",s=Math.max(10,o-4),c=50,d=e.text.split(`
|
|
30
|
+
`).flatMap(k=>Mr(k,s,{hard:!0}).split(`
|
|
31
|
+
`)),g=Math.max(0,d.length-c);return g>0&&(d=[...d.slice(0,c),q.dim(`\u2026 +${g} more lines`)]),`
|
|
32
|
+
`+d.map((k,w)=>n+(w===0?R(" \u276F "):" ")+k+" ".repeat(Math.max(0,s-Fo(k))+1)+r).join(`
|
|
33
33
|
`)}case"assistant":return`
|
|
34
|
-
`+
|
|
35
|
-
`+
|
|
34
|
+
`+Uo(e.text,o);case"tool":{let n=e.arg!==null?q.gray(`${e.sep}(${e.arg})`):"";return`
|
|
35
|
+
`+Mr(q.green("\u25CF ")+q.bold(e.title)+n,o)}case"tool-result":{let n=e.isError?q.red:q.gray,r=e.lines.map((s,c)=>n((c===0?" \u23BF ":" ")+s));return e.hidden>0&&r.push(q.dim(` \u2026 +${e.hidden} lines`)),r.join(`
|
|
36
36
|
`)}case"diff":{let n=c=>c===1?"":"s",s=[q.gray(` \u23BF Added ${e.added} line${n(e.added)}, removed ${e.removed} line${n(e.removed)}`),...e.lines];return e.hidden>0&&s.push(q.dim(` \u2026 +${e.hidden} more diff lines`)),s.join(`
|
|
37
|
-
`)}case"link":return e.lines.map(n=>R(
|
|
37
|
+
`)}case"link":return e.lines.map(n=>R(ht(` \u2B95 ${n}`))).join(`
|
|
38
38
|
`);case"preview":return`
|
|
39
39
|
`+mt(`\u25A3 Preview \u2014 ${e.name}`)+`
|
|
40
40
|
|
|
41
|
-
`+
|
|
42
|
-
`+
|
|
43
|
-
`+(e.ok?q.magenta("\u2736 "):q.red("\u2736 "))+q.gray(`Cooked for ${
|
|
44
|
-
`)}var
|
|
41
|
+
`+Uo(e.text,o);case"note":return`
|
|
42
|
+
`+El[e.tone](ht(e.text));case"done":return`
|
|
43
|
+
`+(e.ok?q.magenta("\u2736 "):q.red("\u2736 "))+q.gray(`Cooked for ${xt(e.seconds)} \xB7 ${e.tokens} tokens`+(e.costUsd>0?` \xB7 ${fe(e.costUsd)}`:""))}}function Lr(e,t){return e.map(o=>Ho(o,t)).join(`
|
|
44
|
+
`)}var Bo=3;function qo(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 zo(e,t){return t?e.filter(o=>{let n=o.replace(/\\/g,"/");return n===t||n.startsWith(`${t}/`)}):e}function Go(e,t){return t.map(o=>{let n=0;try{n=Dl(Il(e,o)).size}catch{n=0}return{path:o,bytes:n}})}function Yo(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:
|
|
45
45
|
- 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.
|
|
46
46
|
- 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.
|
|
47
47
|
- 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.
|
|
48
48
|
- Work only on these files:
|
|
49
49
|
`+e.paths.map(t=>`- ${t}`).join(`
|
|
50
|
-
`)}function
|
|
50
|
+
`)}function Xo(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: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Each article is rewritten and re-published as a DRAFT. Run /convert --run to start."]}function Vo(e,t,o){let n=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),c=e.reduce((x,_)=>x+n(_),0),d=r.reduce((x,_)=>x+n(_),0),g=e.reduce((x,_)=>x+_.costUsd,0),k=e.reduce((x,_)=>x+_.outputTokens,0),w=o==="api"?`${fe(g)} total`:rt(k),I=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=x=>`${x} article${x===1?"":"s"}`,C=[];if(s.length===0)C.push(`Converted ${b(c)} (${I}) successfully \xB7 ${w}.`);else{C.push(`Converted ${d}/${b(c)} (${I}) \xB7 ${w}.`),C.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /convert to retry:`);for(let x of s)C.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return C}async function Or(e,t){if(!Ml(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{scope:o,run:n}=qo(e),r=Ul(t.cwd,t.profileName);if(r.length===0)return console.log($("No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert.")),{kind:"continue"};let s=zo(r,o);if(s.length===0)return console.log($(`No tracked articles under "${o}". (${r.length} are tracked overall.)`)),{kind:"continue"};let c=Nl(s),d=`/convert${o?` --scope ${o}`:""} --run`,{model:g,forced:k}=Ll(t.cwd,"light");if(!n){let w=_l({files:Go(t.cwd,s),op:"convert",model:g});o&&console.log(f(`Scope: ${o} (${s.length} of ${r.length} tracked articles).`));for(let I of Xo(c,w,Bo))console.log(I);return console.log(f(`Model: ${g}${k?" (forced)":" \u2014 mechanical work; /model to override"}.`)),console.log(f(`Run ${d} to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Converting ${s.length} articles across ${c.length} partitions (\u2264${Bo} agents at once) on ${g}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let w of Ol({cwd:t.cwd,partitions:c,promptFor:Yo,concurrency:Bo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:g}))if(w.type==="partition_status")w.status==="running"?console.log(f(` \u25B8 ${w.label} \u2014 converting\u2026`)):w.status==="done"?console.log(E(` \u2713 ${w.label}`)):console.log($(` \u2717 ${w.label}`));else if(w.type==="run_done"){console.log("");let I=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let b of Vo(w.results,c,I))console.log(w.ok?E(b):L(b))}}catch(w){console.log($(`Convert run failed: ${w.message}`))}return console.log(""),{kind:"continue"}}H();import{statSync as Ur}from"node:fs";import{resolve as Wr}from"node:path";import{estimateBulkCost as Wl,planPartitions as Fl,readDocsPlan as Hl,readProjectConfig as Fr,resolveModelForOperation as Bl,runPartitioned as ql}from"document360-engine";var Jo=5;function Ko(e){let t,o,n=!1;for(let s=0;s<e.length;s++){let c=e[s];if(c==="--run"||c==="--yes")n=!0;else{if(c==="--all")continue;c==="--scope"?t=e[++s]:c?.startsWith("--scope=")?t=c.slice(8):c&&!c.startsWith("--")&&(o=c)}}let r=s=>s?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0;return{scope:r(t),path:r(o),run:n}}function zl(e,t){let o=e.replace(/\\/g,"/").replace(/\/+$/,""),n=`${t.replace(/\/+$/,"")}/`;return o.startsWith(n)?o.slice(n.length):o}function Gl(e,t){return t?e.filter(o=>{let n=o.replace(/\\/g,"/");return n===t||n.startsWith(`${t}/`)}):e}function Yl(e,t,o){return o.filter(n=>{try{return Ur(Wr(e,t,n)).size===0}catch{return!0}})}function Qo(e,t,o){let n=new Map(t.map(r=>[r.path,r]));return o.map(r=>{let s=1;for(let c of n.get(r)?.sources??[])try{s+=Ur(Wr(e,c)).size}catch{}return{path:r,bytes:s}})}function Zo(e,t){return`Run the write-article skill to author EACH documentation article listed below. For each path:
|
|
51
51
|
- It is relative to ${t}/. Look up its entry (matching "path") in .d360-writer/plan.json for its purpose and the source files it draws from (AGENT-PLAN.md has the same table).
|
|
52
52
|
- Read ONLY those source files plus any shared context you genuinely need, and ground every statement in them. Never invent UI labels, routes, or behaviour \u2014 if the source does not say it, omit it.
|
|
53
53
|
- Write the finished article to ${t}/<path>, following the write-article structure and the project terminologyGlossary. Add the \`sources:\` frontmatter listing the files you actually read.
|
|
@@ -55,42 +55,42 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
55
55
|
- Each article is independent. Do NOT write, edit, or publish any article not in this list, and do NOT publish to Document360 \u2014 these are local drafts.
|
|
56
56
|
Articles:
|
|
57
57
|
`+e.paths.map(o=>`- ${o}`).join(`
|
|
58
|
-
`)}function Qo(e,t,o){let n=e.reduce((c,u)=>c+u.paths.length,0),[r,s]=t.usd;return[`Write ${n} article${n===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${o} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${pe(r)}\u2013${pe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function Zo(e,t,o){let n=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),c=e.reduce((x,I)=>x+n(I),0),u=r.reduce((x,I)=>x+n(I),0),m=e.reduce((x,I)=>x+I.costUsd,0),h=e.reduce((x,I)=>x+I.outputTokens,0),w=o==="api"?`${pe(m)} total`:rt(h),D=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=x=>`${x} article${x===1?"":"s"}`,C=[];if(s.length===0)C.push(`Wrote ${b(c)} (${D}) successfully \xB7 ${w}.`),C.push("Review them in the docs tree, then /publish when ready.");else{C.push(`Wrote ${u}/${b(c)} (${D}) \xB7 ${w}.`),C.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let x of s)C.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return C}function en(e,t,o){let n=(Wr(e)?.docsDir??"user-docs").replace(/\/+$/,""),r=t.map(u=>u.path);if(o.path){let u=ql(o.path,n);return r.includes(u)?{docsDir:n,targets:[u],planCount:r.length}:{docsDir:n,targets:[],planCount:r.length,reason:`"${u}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=zl(r,o.scope);if(o.scope&&s.length===0)return{docsDir:n,targets:[],planCount:r.length,reason:`No planned articles under "${o.scope}".`};let c=Gl(e,n,s);if(c.length===0){let u=o.scope?` under "${o.scope}"`:"";return{docsDir:n,targets:[],planCount:r.length,reason:`All planned articles${u} are already written. Use /write <path> to rewrite one.`}}return{docsDir:n,targets:c,planCount:r.length}}async function Fr(e,t){if(!Wr(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Fl(t.cwd);if(o.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:n,path:r,run:s}=Vo(e),{docsDir:c,targets:u,reason:m}=en(t.cwd,o,{scope:n,path:r});if(u.length===0)return console.log(m?L(m):L("Nothing to write.")),{kind:"continue"};let h=Wl(u),{model:w,forced:D}=Hl(t.cwd,"standard");if(!s&&!!!r){let C=Ul({files:Jo(t.cwd,o,u),op:"write",model:w});n&&console.log(f(`Scope: ${n} (${u.length} pending).`));for(let x of Qo(h,C,Xo))console.log(x);return console.log(f(`Model: ${w}${D?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${n?` --scope ${n}`:" --all"} --run to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${u.length} article${u.length===1?"":"s"} across ${h.length} partition${h.length===1?"":"s"} (\u2264${Xo} agents at once) on ${w}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let C of Bl({cwd:t.cwd,partitions:h,promptFor:x=>Ko(x,c),concurrency:Xo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:w}))if(C.type==="partition_status")C.status==="running"?console.log(f(` \u25B8 ${C.label} \u2014 writing\u2026`)):C.status==="done"?console.log(E(` \u2713 ${C.label}`)):console.log($(` \u2717 ${C.label}`));else if(C.type==="run_done"){console.log("");let x=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let I of Zo(C.results,h,x))console.log(C.ok?E(I):L(I))}}catch(C){console.log($(`Write run failed: ${C.message}`))}return console.log(""),{kind:"continue"}}H();import{search as Yl}from"@inquirer/prompts";import{findByName as Xl,getSession as Vl,listSessions as Jl,relativeTime as Br}from"document360-engine";async function qr(e,t){let o=Jl(t.cwd).filter(n=>n.uuid!==t.currentUuid());if(o.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let n=e.join(" "),r=Xl(t.cwd,n);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${n}".`)),Hr(o),{kind:"continue"})}if(!process.stdin.isTTY)return Hr(o),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let n=await t.withPausedInput(()=>Yl({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return o.filter(u=>!c||u.name.toLowerCase().includes(c)||u.firstPrompt.toLowerCase().includes(c)).map(u=>({name:`${u.name} ${Br(u.updatedAt)}`,value:u.uuid,description:u.firstPrompt.slice(0,100)}))}})),r=Vl(n);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Hr(e){console.log("");for(let t of e.slice(0,15))console.log(` ${R(t.name)} ${f(Br(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}H();import{renameSession as Kl}from"document360-engine";function tn(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function zr(e,t){let o=tn(e.join(" "));if(!o)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let n=t.currentUuid();return n?(Kl(n,o)?console.log(E(`\u2713 Session renamed to "${o}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(console.log($("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Gr,readProjectConfig as Ql,writeProjectConfig as Zl}from"document360-engine";H();function on(e,t,o){if(!t)return"Usage: /profile add <name> [environment]";let n=Ql(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 Gr().includes(r)?(n.profiles={...n.profiles,[t]:{connection:{environment:r},production:!1}},Zl(n,e),null):`Unknown environment "${r}". Known: ${Gr().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Yr(e,t){let o=e[0];if(!o)return Bt(t.cwd),{kind:"continue"};if(o==="add"){let n=on(t.cwd,e[1],e[2]);return n?(console.log($(n)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${R(`/profile ${e[1]}`)} then ${R("/login")}`),{kind:"continue"})}return qt(t.cwd,o),zt(t.cwd,o),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}H();import{select as ea}from"@inquirer/prompts";import{readProjectConfig as ta,readUserConfig as Xr,resolveModelSetting as nn,writeUserConfig as Vr}from"document360-engine";var ye=[{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 eo(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),o=ye.findIndex(n=>n.value!==null&&(n.value===t||n.label.toLowerCase()===t||t.includes(n.label.toLowerCase())));return o>=0?o:0}function oa(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 xt(e,t){let o=()=>{let s=nn(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Xr();return s.defaultModel?(delete s.defaultModel,Vr(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${nn(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}}Vr({...Xr(),defaultModel:t});let n=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ta(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 Jr(e,t){let o=e[0]?.trim();if(!o){let c=nn(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${R(c.model??"Claude Code default")}`),console.log(f(` source: ${oa(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let u=eo(c),m;try{m=await t.withPausedInput(()=>ea({message:`Select model (current: ${c.model??"Claude Code default"})`,default:ye[u].value,choices:ye.map((b,C)=>({name:`${b.label}${C===u?" \u2714":""}`,value:b.value,description:b.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:h,changed:w,effective:D}=xt(t.cwd,m??"default");for(let b of h)console.log(b.startsWith("\u26A0")?L(b):b.startsWith("\u2713")?E(b):f(b));return w&&await t.setModel(D),{kind:"continue"}}let{lines:n,changed:r,effective:s}=xt(t.cwd,o);for(let c of n)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?E(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}to();async function ts(e,t){return await t.withPausedInput(()=>tt(t.cwd)),{kind:"clear"}}H();import{select as fa}from"@inquirer/prompts";import{resolveActiveProfile as ma,setProfileProject as ga,listProjects as ha}from"document360-engine";async function sn(e,t){let o=ma(e,t),n={profile:o.name,connection:o.connection};return{projects:await ha(n),profile:o.name,environment:o.connection.name,current:o.project.projectId}}var os=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function ns(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 ln(e,t,o){ga(e,t,{projectId:o,workspaceId:void 0,workspaceName:void 0})}async function rs(e,t){let o;try{o=await sn(e,t)}catch(m){console.log($(`Could not list projects: ${m.message}`));return}let{projects:n,profile:r,current:s}=o;if(n.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let m of n)console.log(` ${m.id===s?R("\u25CF"):" "} ${os(m)} ${f(m.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await fa({message:"Select the Document360 project for this repo:",choices:n.map(m=>({name:`${os(m)}${m.id===s?" (current)":""}`,value:m.id}))});ln(e,r,c);let u=n.find(m=>m.id===c);console.log(E(`\u2713 Project set to "${u?.name??c}" for profile "${r}". Next: pick a workspace.`))}async function ss(e,t){return await t.withPausedInput(()=>rs(t.cwd,t.profileName)),{kind:"clear"}}H();import{resolveActiveProfile as ka}from"document360-engine";async function is(e,t){let o=!1;try{o=ka(t.cwd).production}catch{}return o?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}H();var ls=async(e,t)=>{try{await t.withPausedInput(()=>Ht({}))}catch(o){console.log($(`Login failed: ${o.message}`))}return{kind:"continue"}};H();import{resolveActiveProfile as ya,clearTokens as wa,clearProfileProject as $a}from"document360-engine";async function as(e,t){let o;try{o=ya(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let n=wa(o);return $a(t.cwd,o),console.log(n?E(`\u2713 Signed out of "${o}" and cleared its project/workspace selection.`):f(`Profile "${o}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as cs}from"node:fs";import{isAbsolute as xa,join as ba,resolve as va}from"node:path";import{readProjectConfig as Ca,screenshotPlaceholderIds as Pa}from"document360-engine";var us=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function an(e){let t=!e.includes("--no-setup"),o=e.filter(r=>r!=="--no-setup");if(o[0]==="--list")return{mode:"list",scope:o[1]?us(o[1]):void 0};let n=o[0];return!n||n==="--all"?{mode:"all",setup:t}:/[\\/]/.test(n)||n.endsWith(".md")?{mode:"scope",scope:us(n),setup:t}:{mode:"single",id:n}}function cn(e,t){let o=Ca(e),n=o?.captureDir??"user-docs/_capture",r=o?.outputDir??"user-docs/_screenshots",s=(c,u)=>xa(c)?ba(c,u):va(e,c,u);return Pa(e,{scope:t}).map(({id:c,file:u})=>{let m=cs(s(r,`${c}.png`))?"captured":cs(s(n,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:u,state:m}})}var Sa={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Ta={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function un(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(u=>u.file===s))r.push(` ${Sa[c.state]} ${c.id.padEnd(34)} ${Ta[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function ds(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(`
|
|
58
|
+
`)}function en(e,t,o){let n=e.reduce((c,d)=>c+d.paths.length,0),[r,s]=t.usd;return[`Write ${n} article${n===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${o} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${fe(r)}\u2013${fe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write --run to start."]}function tn(e,t,o){let n=x=>t[x.index]?.paths.length??0,r=e.filter(x=>x.ok),s=e.filter(x=>!x.ok),c=e.reduce((x,_)=>x+n(_),0),d=r.reduce((x,_)=>x+n(_),0),g=e.reduce((x,_)=>x+_.costUsd,0),k=e.reduce((x,_)=>x+_.outputTokens,0),w=o==="api"?`${fe(g)} total`:rt(k),I=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,b=x=>`${x} article${x===1?"":"s"}`,C=[];if(s.length===0)C.push(`Wrote ${b(c)} (${I}) successfully \xB7 ${w}.`),C.push("Review them in the docs tree, then /publish when ready.");else{C.push(`Wrote ${d}/${b(c)} (${I}) \xB7 ${w}.`),C.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let x of s)C.push(` \u2717 ${x.label}${x.error?` \u2014 ${x.error}`:""}`)}return C}function on(e,t,o){let n=(Fr(e)?.docsDir??"user-docs").replace(/\/+$/,""),r=t.map(d=>d.path);if(o.path){let d=zl(o.path,n);return r.includes(d)?{docsDir:n,targets:[d],planCount:r.length}:{docsDir:n,targets:[],planCount:r.length,reason:`"${d}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Gl(r,o.scope);if(o.scope&&s.length===0)return{docsDir:n,targets:[],planCount:r.length,reason:`No planned articles under "${o.scope}".`};let c=Yl(e,n,s);if(c.length===0){let d=o.scope?` under "${o.scope}"`:"";return{docsDir:n,targets:[],planCount:r.length,reason:`All planned articles${d} are already written. Use /write <path> to rewrite one.`}}return{docsDir:n,targets:c,planCount:r.length}}async function Hr(e,t){if(!Fr(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Hl(t.cwd);if(o.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:n,path:r,run:s}=Ko(e),{docsDir:c,targets:d,reason:g}=on(t.cwd,o,{scope:n,path:r});if(d.length===0)return console.log(g?L(g):L("Nothing to write.")),{kind:"continue"};let k=Fl(d),{model:w,forced:I}=Bl(t.cwd,"standard");if(!s&&!!!r){let C=Wl({files:Qo(t.cwd,o,d),op:"write",model:w});n&&console.log(f(`Scope: ${n} (${d.length} pending).`));for(let x of en(k,C,Jo))console.log(x);return console.log(f(`Model: ${w}${I?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(f(`Run /write${n?` --scope ${n}`:" --all"} --run to start.`)),console.log(""),{kind:"continue"}}console.log(f(`Writing ${d.length} article${d.length===1?"":"s"} across ${k.length} partition${k.length===1?"":"s"} (\u2264${Jo} agents at once) on ${w}\u2026`)),console.log(f(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let C of ql({cwd:t.cwd,partitions:k,promptFor:x=>Zo(x,c),concurrency:Jo,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:w}))if(C.type==="partition_status")C.status==="running"?console.log(f(` \u25B8 ${C.label} \u2014 writing\u2026`)):C.status==="done"?console.log(E(` \u2713 ${C.label}`)):console.log($(` \u2717 ${C.label}`));else if(C.type==="run_done"){console.log("");let x=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let _ of tn(C.results,k,x))console.log(C.ok?E(_):L(_))}}catch(C){console.log($(`Write run failed: ${C.message}`))}return console.log(""),{kind:"continue"}}H();import{search as Xl}from"@inquirer/prompts";import{findByName as Vl,getSession as Jl,listSessions as Kl,relativeTime as qr}from"document360-engine";async function zr(e,t){let o=Kl(t.cwd).filter(n=>n.uuid!==t.currentUuid());if(o.length===0)return console.log(f("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let n=e.join(" "),r=Vl(t.cwd,n);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${n}".`)),Br(o),{kind:"continue"})}if(!process.stdin.isTTY)return Br(o),console.log(f("Run: /resume <name>")),{kind:"continue"};try{let n=await t.withPausedInput(()=>Xl({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return o.filter(d=>!c||d.name.toLowerCase().includes(c)||d.firstPrompt.toLowerCase().includes(c)).map(d=>({name:`${d.name} ${qr(d.updatedAt)}`,value:d.uuid,description:d.firstPrompt.slice(0,100)}))}})),r=Jl(n);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Br(e){console.log("");for(let t of e.slice(0,15))console.log(` ${R(t.name)} ${f(qr(t.updatedAt))}`),console.log(` ${f(t.firstPrompt.slice(0,80))}`);console.log("")}H();import{renameSession as Ql}from"document360-engine";function nn(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function Gr(e,t){let o=nn(e.join(" "));if(!o)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let n=t.currentUuid();return n?(Ql(n,o)?console.log(E(`\u2713 Session renamed to "${o}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(console.log($("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Yr,readProjectConfig as Zl,writeProjectConfig as ea}from"document360-engine";H();function rn(e,t,o){if(!t)return"Usage: /profile add <name> [environment]";let n=Zl(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 Yr().includes(r)?(n.profiles={...n.profiles,[t]:{connection:{environment:r},production:!1}},ea(n,e),null):`Unknown environment "${r}". Known: ${Yr().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Xr(e,t){let o=e[0];if(!o)return qt(t.cwd),{kind:"continue"};if(o==="add"){let n=rn(t.cwd,e[1],e[2]);return n?(console.log($(n)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${R(`/profile ${e[1]}`)} then ${R("/login")}`),{kind:"continue"})}return zt(t.cwd,o),Gt(t.cwd,o),console.log(f(" Restarting agent for the new profile\u2026")),{kind:"clear"}}H();import{select as ta}from"@inquirer/prompts";import{readProjectConfig as oa,readUserConfig as Vr,resolveModelSetting as sn,writeUserConfig as Jr}from"document360-engine";var ye=[{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 to(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),o=ye.findIndex(n=>n.value!==null&&(n.value===t||n.label.toLowerCase()===t||t.includes(n.label.toLowerCase())));return o>=0?o:0}function na(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 bt(e,t){let o=()=>{let s=sn(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Vr();return s.defaultModel?(delete s.defaultModel,Jr(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${sn(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}}Jr({...Vr(),defaultModel:t});let n=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=oa(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 Kr(e,t){let o=e[0]?.trim();if(!o){let c=sn(t.cwd);if(!process.stdin.isTTY)return console.log(`${Pe("Model:")} ${R(c.model??"Claude Code default")}`),console.log(f(` source: ${na(c)}`)),console.log(f(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let d=to(c),g;try{g=await t.withPausedInput(()=>ta({message:`Select model (current: ${c.model??"Claude Code default"})`,default:ye[d].value,choices:ye.map((b,C)=>({name:`${b.label}${C===d?" \u2714":""}`,value:b.value,description:b.desc}))}))}catch{return console.log(f("Cancelled.")),{kind:"continue"}}let{lines:k,changed:w,effective:I}=bt(t.cwd,g??"default");for(let b of k)console.log(b.startsWith("\u26A0")?L(b):b.startsWith("\u2713")?E(b):f(b));return w&&await t.setModel(I),{kind:"continue"}}let{lines:n,changed:r,effective:s}=bt(t.cwd,o);for(let c of n)console.log(c.startsWith("\u26A0")?L(c):c.startsWith("\u2713")?E(c):f(c));return r&&await t.setModel(s),{kind:"continue"}}oo();async function os(e,t){return await t.withPausedInput(()=>tt(t.cwd)),{kind:"clear"}}H();import{select as ma}from"@inquirer/prompts";import{resolveActiveProfile as ga,setProfileProject as ha,listProjects as ka}from"document360-engine";async function an(e,t){let o=ga(e,t),n={profile:o.name,connection:o.connection};return{projects:await ka(n),profile:o.name,environment:o.connection.name,current:o.project.projectId}}var ns=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function rs(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 cn(e,t,o){ha(e,t,{projectId:o,workspaceId:void 0,workspaceName:void 0})}async function ss(e,t){let o;try{o=await an(e,t)}catch(g){console.log($(`Could not list projects: ${g.message}`));return}let{projects:n,profile:r,current:s}=o;if(n.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let g of n)console.log(` ${g.id===s?R("\u25CF"):" "} ${ns(g)} ${f(g.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await ma({message:"Select the Document360 project for this repo:",choices:n.map(g=>({name:`${ns(g)}${g.id===s?" (current)":""}`,value:g.id}))});cn(e,r,c);let d=n.find(g=>g.id===c);console.log(E(`\u2713 Project set to "${d?.name??c}" for profile "${r}". Next: pick a workspace.`))}async function is(e,t){return await t.withPausedInput(()=>ss(t.cwd,t.profileName)),{kind:"clear"}}H();import{resolveActiveProfile as ya}from"document360-engine";async function ls(e,t){let o=!1;try{o=ya(t.cwd).production}catch{}return o?(console.log(L("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(f("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}H();var as=async(e,t)=>{try{await t.withPausedInput(()=>Bt({}))}catch(o){console.log($(`Login failed: ${o.message}`))}return{kind:"continue"}};H();import{resolveActiveProfile as wa,clearTokens as $a,clearProfileProject as xa}from"document360-engine";async function cs(e,t){let o;try{o=wa(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let n=$a(o);return xa(t.cwd,o),console.log(n?E(`\u2713 Signed out of "${o}" and cleared its project/workspace selection.`):f(`Profile "${o}" was not signed in. Cleared any project/workspace selection.`)),console.log(f("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as us}from"node:fs";import{isAbsolute as ba,join as va,resolve as Ca}from"node:path";import{readProjectConfig as Pa,screenshotPlaceholderIds as Sa}from"document360-engine";var ds=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function un(e){let t=!e.includes("--no-setup"),o=e.filter(r=>r!=="--no-setup");if(o[0]==="--list")return{mode:"list",scope:o[1]?ds(o[1]):void 0};let n=o[0];return!n||n==="--all"?{mode:"all",setup:t}:/[\\/]/.test(n)||n.endsWith(".md")?{mode:"scope",scope:ds(n),setup:t}:{mode:"single",id:n}}function dn(e,t){let o=Pa(e),n=o?.captureDir??"user-docs/_capture",r=o?.outputDir??"user-docs/_screenshots",s=(c,d)=>ba(c)?va(c,d):Ca(e,c,d);return Sa(e,{scope:t}).map(({id:c,file:d})=>{let g=us(s(r,`${c}.png`))?"captured":us(s(n,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:d,state:g}})}var Ta={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Ra={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function pn(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(d=>d.file===s))r.push(` ${Ta[c.state]} ${c.id.padEnd(34)} ${Ra[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function ps(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(`
|
|
59
59
|
`),"","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(`
|
|
60
|
-
`)}async function
|
|
60
|
+
`)}async function no(e,t){let o=un(e);if(o.mode==="list"){let c=t?.cwd??process.cwd();for(let d of pn(dn(c,o.scope),o.scope))console.log(d);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(`
|
|
61
61
|
`),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.${o.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
|
|
62
|
-
`),s=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as
|
|
63
|
-
`),display:"/capture-setup"}}var
|
|
64
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(o?.startsWith("mcp__document360__")){let c=
|
|
65
|
-
`);return{lines:s.slice(0,t).map(c=>se(c,
|
|
62
|
+
`),s=o.mode==="scope"?`/screenshot ${o.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as ja,readFileSync as Aa}from"node:fs";import{isAbsolute as Ea,join as Da,resolve as Ia}from"node:path";import{readProjectConfig as _a}from"document360-engine";async function Ct(){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(`
|
|
63
|
+
`),display:"/capture-setup"}}var fs="-".repeat(64);function fn(e){let t="user-docs/_capture";try{let w=_a(e);w?.captureDir&&(t=w.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let o=Ea(t)?Da(t,"CAPTURE-TESTID-REQUESTS.json"):Ia(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!ja(o))return null;let n;try{let w=JSON.parse(Aa(o,"utf8").replace(/^/,""));n=Array.isArray(w?.requests)?w.requests:[]}catch{return null}if(n.length===0)return null;let r=new Set(n.map(w=>w.file).filter(Boolean)).size,s=n.length,c=`${s} data-testid attribute${s===1?"":"s"}`,d=`${r} source file${r===1?"":"s"}`,g=`${t}/CAPTURE-TESTID-REQUESTS.md`,k=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${d}.`,"\u26A0 Do NOT run this prompt here. d360-writer documents code; it does not change it \u2014"," these edits belong in your code repo. Open a SEPARATE terminal in:",` ${e}`," start Claude Code (or your coding agent), and paste everything between the lines."," Tip: run it in plan mode first \u2014 these are a hypothesis to verify, not a verified patch.","",fs,`Read ${g} and ${k}. They list ${c} that d360-writer THINKS this repo needs for screenshot automation. Treat them as a hypothesis to VERIFY against the source \u2014 not a verified patch list.`,"","For EACH request in the JSON:",'1. Locate the element in THIS repo. Trace it from the route/page, not the feature name. If "anchorVerified" is false, find it by the "element"/"reason" description; otherwise confirm the "anchor" snippet still exists in "file".',"2. If the element already has a data-testid, skip it and note the existing one.","3. Confirm the attribute will reach the DOM: the rendering component must forward unknown props (a {...rest} spread or explicit pass-through). If it is a shared wrapper (e.g. Modal, ContextMenu) that destructures a fixed prop list, a data-testid is silently dropped \u2014 thread it through the component, or report it as needing a code change instead of forcing it.",'4. Only then add data-testid="<testid>" to the verified element. Add nothing else; do not rename, restructure, reformat, or change behaviour.',"","When done, report: which testids you added (file + element), which were already present, which requests were wrong (wrong file/anchor/page) with the correction, and which need threading through a shared component. Never force a request that does not match the source \u2014 flag it instead.",fs]}H();import{existsSync as Na,rmSync as Ma}from"node:fs";import{basename as ms,resolve as gs}from"node:path";import{input as La}from"@inquirer/prompts";import{readProjectConfig as Oa}from"document360-engine";var Ua=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"];function mn(e){let t=null;try{t=Oa(e)}catch{t=null}let o=s=>s?.replace(/\\/g,"/").replace(/\/+$/,""),n=o(t?.docsDir)??"user-docs",r=new Set([n]);for(let s of[o(t?.captureDir),o(t?.outputDir)])s&&s!==n&&!s.startsWith(`${n}/`)&&r.add(s);return[...r,...Ua].filter(s=>Na(gs(e,s)))}function gn(e,t){let o=[],n=[];for(let r of t)try{Ma(gs(e,r),{recursive:!0,force:!0}),o.push(r)}catch(s){n.push({path:r,error:s.message})}return{removed:o,failed:n}}function hn(e,t){return t.length===0?["Nothing to reset \u2014 no d360-writer files found in this repo."]:["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(o=>` \u2022 ${o}`),"","Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${ms(e)}`]}async function hs(e,t){let o=mn(t.cwd);for(let d of hn(t.cwd,o))console.log(o.length===0?f(d):d);if(o.length===0)return{kind:"continue"};let n=ms(t.cwd);if((await t.withPausedInput(()=>La({message:`Type "${n}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==n)return console.log(L("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let{removed:s,failed:c}=gn(t.cwd,o);console.log(E(`\u2713 Reset complete \u2014 removed ${s.length} item${s.length===1?"":"s"}. The repo is back to its original state.`));for(let d of c)console.log($(` \u2717 ${d.path}: ${d.error}`));return console.log(f("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}var ks={help:Eo,"?":Eo,clear:cr,exit:Do,quit:Do,init:gr,mcp:Vt,publish:xr,audit:Qt,scope:vr,sync:Ar,convert:Or,write:Hr,resume:zr,rename:Gr,profile:Xr,model:Kr,doctor:vt,workspace:os,project:is,"allow-prod":ls,login:as,logout:cs,screenshot:no,"capture-setup":Ct,reset:hs};function ys(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}H();var Wa={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"},$s=160,yn=200,xs=40;function se(e,t){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:o.slice(0,t-1)+"\u2026"}function ws(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}: ${se(typeof r=="string"?r:JSON.stringify(r),xs)}`);return t.length>4&&o.push("\u2026"),se(o.join(", "),$s)}var De=e=>typeof e=="string"&&e?e:null,kn=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function Fa(e){let t=De(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 Ha(e,t){let o=(n,r)=>({title:`Document360: ${n}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let n=De(t.title);if(!n)return null;let r=Fa(t.local_path);return o("Create article",`"${se(n,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let n=De(t.title),r=kn(t.article_id);return o("Update article",n?`"${se(n,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return o("Fork article (new draft)",kn(t.article_id)?`id ${kn(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",De(t.name)?`"${se(De(t.name),60)}"`:null);case"d360_upload_drive_file":{let n=De(t.file_path);return o("Upload image",n?se(n.replace(/\\/g,"/").split("/").pop()??n,60):null)}case"d360_sync_status":return o("Check sync status",null);default:return null}}function ro(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let k=Ha(c,t);if(k)return k}let d=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${d}`,sep:" ",arg:ws(t)}}let o=Wa[e],n=o?t[o]:void 0;return typeof n=="string"&&n?{title:e,sep:"",arg:se(n,$s)}:{title:e,sep:"",arg:ws(t)}}function Ba(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 qa(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let o=t.map(Ba).filter(r=>r!==null),n=`${t.length} item${t.length===1?"":"s"}`;return o.length===0?[n]:[n,...o.map(r=>se(r,yn))]}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}: ${se(String(r),xs)}`);return o.length>0?[se(o.join(" \xB7 "),yn)]:null}return null}function za(e){let t=De(e)?.replace(/\\/g,"/");if(!t)return null;let o=t.split("/").filter(Boolean);return o.length>1?o.slice(1).join("/"):t}function Ga(e,t,o){switch(e){case"d360_create_article":{let n=za(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=De(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 ${se(n[0],120)}`:""}`]}default:return null}}function so(e,t=4,o,n){let r=e.replace(/\r\n/g,`
|
|
64
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(o?.startsWith("mcp__document360__")){let c=Ga(o.slice(18),n,r);if(c)return{lines:c,hidden:0}}let s=qa(r)??r.split(`
|
|
65
|
+
`);return{lines:s.slice(0,t).map(c=>se(c,yn)),hidden:Math.max(0,s.length-t)}}function io(e,t,o,n="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${n}/${o}`}function lo(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 ao(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 rc=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function sc(e,t,o,n){if(rc.test(e))try{let r=Ps(n),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=lo(t,o),d=ao(o);e.endsWith("publish_article")&&d&&console.log(R(` \u2B95 Live: ${d}`)),c&&s&&console.log(R(` \u2B95 Preview: ${io(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Ss(e=process.cwd(),t="auto",o){let n=Xa(t);n.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${R("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${R('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${R("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${R("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),ic(e,o),n.kind==="subscription"&&(n.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=wn({cwd:e,profileName:o,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},d=Ya({input:process.stdin,output:process.stdout}),g=[],k=null,w=!1;d.on("line",C=>{if(k){let x=k;k=null,x(C)}else g.push(C)}),d.on("close",()=>{if(w=!0,k){let C=k;k=null,C(null)}});function I(){return g.length>0?Promise.resolve(g.shift()):w?Promise.resolve(null):(process.stdout.write(R("> ")),new Promise(C=>{k=C}))}let b={cwd:e,profileName:o,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=wn({cwd:e,profileName:o,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async C=>s.setModel(C),withPausedInput:async C=>{d.pause();try{return await C()}finally{d.resume()}}};try{for(;;){let C=await I();if(C===null)break;let x=C.trim();if(x){if(x.startsWith("/")){let _=ys(x);if(!_)continue;let z=ks[_.name];if(!z){console.log($(`Unknown command: /${_.name}`)),console.log(f("Type /help for the list."));continue}let G=await z(_.args,b);if(G.kind==="exit")break;if(G.kind==="clear"){b.restartAgent();continue}if(G.kind==="allow-prod"){r=!0,b.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(G.kind==="resume"){s.close(),s=wn({cwd:e,resume:G.uuid,profileName:o,allowProdWrites:r});let ae=Va(G.uuid);c={uuid:G.uuid,firstPrompt:ae?.firstPrompt??null,titleFired:!0},Cs(G.uuid),console.log(E(`\u2713 Resumed "${G.name}"`)),console.log("");continue}G.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=G.display??G.prompt),await vs(s,G.prompt,n,c,e));continue}c.firstPrompt||(c.firstPrompt=x),await vs(s,x,n,c,e)}}}finally{s.close(),d.close()}}function ic(e,t){console.log(""),console.log(mt("document360-writer")),console.log(f(` cwd: ${e}`));let o=ec(e);console.log(f(` model: ${o.model??"auto (engine right-sizes per task)"}${o.model?` (${o.source})`:""}`)),console.log(lc(e,t)),tc(e)||console.log(L(" First run: /init \u2192 /login \u2192 /workspace, then ask for a docs analysis.")),console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function lc(e,t){try{let o=Ps(e,t),n=o.production?L(" \u26A0 PRODUCTION"):"",r=nc(o.name);if(!r)return f(` Document360: profile "${o.name}"${n} \u2014 not logged in (d360-writer login)`);let s={...bs(r.idToken)??{},...bs(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return oc(r)&&!r.refreshToken?L(` Document360: profile "${o.name}"${n} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${o.name}"${n}`)}catch(o){return f(` Document360: ${o.message.split(".")[0]}`)}}function ac(){console.error(""),console.error(`Sign in with your Claude subscription: run ${R("claude")} once, then retry.`),console.error(` (No Claude Code? ${R("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${R("https://console.anthropic.com/settings/keys")}`)}function cc(e,t,o){e.uuid=t;let n=new Date().toISOString();Qa({uuid:t,name:Ka(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:o,firstPrompt:e.firstPrompt??"",createdAt:n,updatedAt:n})}function uc(e,t){e.titleFired=!0;let o=e.uuid,n=e.firstPrompt;!o||!n||Za(n,t).then(r=>{r&&Ja(o,r)}).catch(()=>{})}async function vs(e,t,o,n,r){let s=new Map;for await(let c of e.send(t))dc(c,n,r,o,s)}function dc(e,t,o,n,r){switch(e.type){case"session":t.uuid||cc(t,e.sessionId,o);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=ro(e.name,e.input);s&&(process.stdout.write(`
|
|
66
66
|
|
|
67
|
-
`),console.log(`${E("\u25CF")} ${Pe(s.title)}${s.arg!==null?Q(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Fe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=
|
|
68
|
-
`),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(
|
|
69
|
-
`)){let c=s.trim().replace(
|
|
70
|
-
`)}function
|
|
71
|
-
`)||e.length>200}function
|
|
72
|
-
`).length;return`[Pasted text #${e} +${o} line${o===1?"":"s"}]`}function
|
|
73
|
-
`)){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
|
|
74
|
-
`),s=0;for(let c=r.length-1;c>=0;c--){let
|
|
75
|
-
`),truncated:c>0||
|
|
76
|
-
`)){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
|
|
67
|
+
`),console.log(`${E("\u25CF")} ${Pe(s.title)}${s.arg!==null?Q(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Fe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=d=>d===1?"":"s";console.log(Q(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let d of s.lines)console.log(d);s.hidden>0&&console.log(f(` \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=so(e.output,4,e.isError?void 0:s.name,s.input),d=e.isError?$:Q;c.lines.forEach((g,k)=>console.log(d((k===0?" \u23BF ":" ")+g))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||sc(s.name,s.input,e.output,o);break}case"result":process.stdout.write(`
|
|
68
|
+
`),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Cs(t.uuid),t.titleFired||uc(t,o));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),n.kind==="subscription"&&e.kind==="auth"&&ac();break}}import{render as iu}from"ink";import{resolveAuth as lu}from"document360-engine";import{useCallback as X,useEffect as _e,useMemo as mo,useRef as K,useState as F}from"react";import{Box as J,Text as v,useApp as xc,useInput as bc,useStdout as vc}from"ink";import{existsSync as Hs,readFileSync as Bs,readdirSync as Zs}from"node:fs";import{basename as go,isAbsolute as Cc,join as St}from"node:path";import{createSession as qs,loginPkce as Pc,toStoredTokens as Sc,saveTokens as Tc,getAccessToken as Rc,resolveActiveProfile as le,resolveProjectId as jc,getArticle as Ac,decodeJwtClaims as st,isExpired as Ie,loadTokens as He,clearTokens as Ec,clearProfileProject as Dc,setTitle as Ic,slugify as _c,touchSession as bn,upsertSession as Nc,generateTitle as zs,findByName as Mc,listSessions as Lc,renameSession as Oc,suggestNextAction as Uc,readProjectConfig as ie,writeProjectConfig as Wc,resolveModelSetting as Tn,loadProfileMap as Gs,applyPull as Fc,computeSyncStatus as vn,planPull as Hc,inventoryRepo as Bc,knownEnvironments as qc,resolveEnvironment as zc,planPartitions as Ys,partitionEvenly as Gc,screenshotPlaceholderIds as Yc,trackedArticlePaths as Xc,runPartitioned as Cn,estimateBulkCost as Xs,resolveModelForOperation as Pn,readDocsPlan as Vc}from"document360-engine";import{existsSync as pc,mkdirSync as fc,readFileSync as mc,writeFileSync as gc}from"node:fs";import{join as Ts}from"node:path";import{writerDir as hc}from"document360-engine";function Rs(e){return Ts(hc(e),".sessions")}function js(e,t){return Ts(Rs(e),`${t}.json`)}function As(e,t,o){try{fc(Rs(e),{recursive:!0});let n=o.filter(r=>r.kind!=="banner");gc(js(e,t),JSON.stringify({v:1,items:n}),"utf8")}catch{}}function $n(e,t){try{let o=js(e,t);if(!pc(o))return[];let n=JSON.parse(mc(o,"utf8"));return Array.isArray(n.items)?n.items:[]}catch{return[]}}var kc=e=>`\x1B]0;${e}\x07`,yc=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Es(e){process.stdout.isTTY&&process.stdout.write(e)}function Pt(e){Es(kc(e))}function co(e){Es(yc(e))}var uo=["\xB7 "," \xB7"],xn="\u{1F7E3}";oo();var wc=/^(?:\d+[.)]|[-*•])\s+/;function Ds(e,t,o=4){let n=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
69
|
+
`)){let c=s.trim().replace(wc,""),d=c.match(/^`([^`]+)`$/);d&&(c=d[1].trim());let g=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!g||!n.has(g[1].toLowerCase()))continue;let k=`/${g[1].toLowerCase()}${g[2]?` ${g[2]}`:""}`;if(r.includes(k)||r.push(k),r.length>=o)break}return r}H();var $c=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Is(e){return e.replace(/\r\n?/g,`
|
|
70
|
+
`)}function _s(e){return e.includes(`
|
|
71
|
+
`)||e.length>200}function Ns(e,t){let o=t.split(`
|
|
72
|
+
`).length;return`[Pasted text #${e} +${o} line${o===1?"":"s"}]`}function Ms(e,t){return e.replace($c,o=>t.get(o)??o)}function Ls(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function po(e,t){let o=Math.max(1,t),n=[],r=0;for(let s of e.split(`
|
|
73
|
+
`)){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 fo(e,t){let o=0;for(let n=0;n<e.length&&e[n].start<=t;n++)o=n;return o}function Os(e,t,o){let n=fo(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 Us(e,t,o){let n=e[fo(e,t)];return o==="start"?n.start:n.end}function Ws(e,t,o){let n=Math.max(1,o),r=e.split(`
|
|
74
|
+
`),s=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(s+=Math.max(1,Math.ceil(d.length/n)),s>=t){let g=s-t;return{text:[g>0?d.slice(g*n):d,...r.slice(c+1)].join(`
|
|
75
|
+
`),truncated:c>0||g>0}}}return{text:e,truncated:!1}}function Fs(e){let t=!1,o=0,n=0;for(let r of e.split(`
|
|
76
|
+
`)){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 Sn,jsx as S,jsxs as U}from"react/jsx-runtime";var Jc={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},Vs=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
77
77
|
2. /login signs in to that environment
|
|
78
78
|
3. /project then /workspace \u2014 pick the project and where articles go
|
|
79
|
-
Press 1 to start.`;function
|
|
80
|
-
${
|
|
81
|
-
${
|
|
82
|
-
`)});return;case"exit":case"quit":
|
|
79
|
+
Press 1 to start.`;function Kc(e,t,o,n){let r=o.kind==="api"?"API key":o.kind==="subscription"?"subscription":"not configured",s=Tn(e),c=ie(e),d=(c?.docsDir??"user-docs").replace(/\/+$/,""),g=c?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${d}/ + config`,k={version:t,claude:r,model:s.model??"Claude Code default model",modelSource:Jc[s.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:c!==null,mode:g};if(c===null)return k;try{let w=le(e,n);k.profile=w.name,k.apiUrl=w.connection.apiUrl,k.prod=w.production,k.project=w.project.projectId??"(chosen at login)";let I=He(w.name);if(I){let b={...st(I.idToken)??{},...st(I.accessToken)??{}},C=b.email??b.preferred_username??"signed in";Ie(I)?I.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(I.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function Qc(e,t){try{let o=le(e,t),n=He(o.name);if(!n)return{text:`profile "${o.name}" \u2014 not logged in (/login)`,prod:o.production};let r={...st(n.idToken)??{},...st(n.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return Ie(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 Js=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],ko=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Zc="Ask me to write or update an article\u2026";function ho({ch:e,dim:t}){let[o,n]=F(!0);return _e(()=>{let r=setInterval(()=>n(s=>!s),530);return()=>clearInterval(r)},[]),S(v,{inverse:o,color:t&&!o?"gray":void 0,children:e})}var eu=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Ks(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var tu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Qs(e){try{return Zs(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function ou(e,t){let o=t??[];return o.length===0?["src","api","services","packages","modules"].some(n=>Qs(St(e,n))):o.some(n=>!n.includes("/")&&!n.endsWith(".md")&&Qs(St(e,n)))}function nu({startTime:e,chars:t}){let[o,n]=F(0);_e(()=>{let g=setInterval(()=>n(k=>k+1),120);return()=>clearInterval(g)},[]);let r=ko[o%ko.length],s=Js[Math.floor(o/16)%Js.length],c=Math.floor((Date.now()-e)/1e3),d=Math.round(t/4);return U(J,{children:[S(v,{color:B,children:` ${r} ${s}\u2026 `}),S(v,{color:"gray",children:`(${xt(c)} \xB7 ~${d} tokens \xB7 esc to interrupt)`})]})}var ru=12e4;function su({p:e}){let[t,o]=F(0);_e(()=>{let g=setInterval(()=>o(k=>k+1),150);return()=>clearInterval(g)},[]);let n=ko[t%ko.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),d=Date.now()-e.lastAt>=ru;return U(J,{flexDirection:"column",children:[U(J,{children:[S(v,{color:B,children:` ${n} ${e.verb??"Converting"} `}),S(v,{color:"gray",children:`${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${xt(r)} \xB7 esc to stop`})]}),e.active.length>0&&S(v,{dimColor:!0,children:` \u25B8 ${e.active.join(", ")} \xB7 last activity ${s}s ago`}),d&&S(v,{color:"yellow",children:` \u26A0 no activity for ${xt(s)} \u2014 press esc to stop if it's wedged`})]})}function ei({cwd:e,auth:t,profileName:o,version:n}){let{exit:r}=xc(),[s,c]=F(o),[d,g]=F(null),[k,w]=F({text:"",pos:0}),I=k.text,b=X(a=>{w(l=>{let i=typeof a=="function"?a(l.text):a;return{text:i,pos:i.length}})},[]),C=X(a=>{w(l=>({text:l.text.slice(0,l.pos)+a+l.text.slice(l.pos),pos:l.pos+a.length}))},[]),x=X(()=>{w(a=>{if(a.pos===0)return a;let l=a.text.slice(0,a.pos),i=Ls(l)??l.slice(0,-1);return{text:i+a.text.slice(a.pos),pos:i.length}})},[]),[_,z]=F(!1),[G,ae]=F(!1),[me,we]=F(0),[ge,he]=F(null),[it,V]=F([]),Tt=K(0),[ri,Rt]=F(!1),[si,lt]=F(0),Be=K(0),[at,qe]=F(0),[ze,jt]=F(null),An=K(new Map),ii=K(0),Ge=K([]),ce=K(null);ce.current===null&&(ce.current=qs({cwd:e,profileName:s,allowProdWrites:!1}));let $e=K({uuid:null,firstPrompt:null,titleFired:!1}),At=K(new Map),ct=K(!1),yo=K([]),Te=K([]),wo=K(null),[En,Ye]=F(null),[Ne,Me]=F(null),[xe,Xe]=F(null),[Re,Ve]=F(null),[oe,Je]=F(null),[ue,Ke]=F(null),[be,Qe]=F(null),[de,Le]=F(null),[ne,Ze]=F(null),[Dn,$o]=F([]),Oe=K([]),Et=K(!1),ve=K(null),[In,Z]=F(null),Dt=K(!1),It=K(null),[pe,Ue]=F(null),[_n,ut]=F(0),[Nn,dt]=F(0),[li,Mn]=F(0),xo=mo(()=>{try{return Tn(e).model??"auto"}catch{return null}},[e,li]),{stdout:ke}=vc(),[,ai]=F(0),Ln=K(`${ke.columns??80}x${ke.rows??24}`),je=X(()=>Math.max(20,(ke.columns??80)-1),[ke]),u=X(a=>{Ge.current.push(a),console.log(Ho(a,je()))},[je]);_e(()=>{let a=`d360-writer \xB7 ${En??go(e)}`;if(!_){co(0),Pt(`${xn} ${a}`);return}co(3);let l=0;Pt(`${uo[0]} ${a}`);let i=setInterval(()=>{l=(l+1)%uo.length,Pt(`${uo[l]} ${a}`)},400);return()=>clearInterval(i)},[_,e,En]),_e(()=>()=>co(0),[]),_e(()=>{if(u({kind:"banner",info:Kc(e,n,t,s)}),!ie(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
80
|
+
${Vs}`}),V(["/init"]);return}try{let a=le(e,s),l=He(a.name);l&&Ie(l)&&l.refreshToken?Rc({profile:a.name,connection:a.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),we(i=>i+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),V(["/login"])}):(!l||Ie(l))&&(u({kind:"note",tone:"warn",text:`Profile "${a.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),V(["/login"]))}catch{}try{let a=ie(e),l=le(e,s),i=He(l.name);a&&i&&!Ie(i)&&ou(e,a.authoritativeSourceFiles)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),V(["/scope"]))}catch{}},[]),_e(()=>{let a=null,l=null,i=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null;let h=`${ke.columns??80}x${ke.rows??24}`;h!==Ln.current&&(Ln.current=h,ai(p=>p+1),l&&clearTimeout(l),l=setTimeout(()=>{l=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+Lr(Ge.current,je())+"\x1B[?2026l")},80))},400)};return ke.on("resize",i),()=>{a&&clearTimeout(a),l&&clearTimeout(l),ke.off("resize",i)}},[ke,je]);let We=Math.max(20,(ke.columns??80)-1),On=mo(()=>Qc(e,s),[e,s,me]),bo=mo(()=>{let a=ie(e);if(!a)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};try{let h=le(e,s),p=He(h.name);if(!(!!p&&!(Ie(p)&&!p.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${h.name}")\u2026`,isSetup:!0};if(!h.project.workspaceId)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}let l=St(e,(a.docsDir??"user-docs").replace(/\/+$/,""));return(()=>{try{return Hs(l)&&Zs(l).length>0}catch{return!1}})()?{text:Zc,isSetup:!1}:{text:"Let's get started \u2014 try: write the docs for this repo",isSetup:!1}},[e,s,me]),pt=lr(I),Un=pt.length>0&&!_,vo=d!==null?Ws(d,8,We):null,_t=de?de.paths.filter(a=>!de.query||a.toLowerCase().includes(de.query.toLowerCase())).slice(0,8):[],Nt=pe?pe.sessions.filter(a=>{let l=pe.query.toLowerCase();return!l||a.name.toLowerCase().includes(l)||a.firstPrompt.toLowerCase().includes(l)}).slice(0,8):[],re=X((a,l)=>{ce.current?.close(),ce.current=qs({cwd:e,resume:a,profileName:l??s,allowProdWrites:ct.current}),a||($e.current={uuid:null,firstPrompt:null,titleFired:!1},Ye(null)),ut(0),dt(0)},[e,s]),Wn=X((a,l,i)=>{if(eu.test(a))try{let h=le(e,s),p=typeof l.project_id=="string"&&l.project_id||h.project.projectId,m=lo(l,i),y=[],T=ao(i);a.endsWith("publish_article")&&T&&y.push(`Live: ${T}`),m&&p&&y.push(`Preview: ${io(h.connection.portalUrl,p,m,h.project.languageCode??"en")}`),y.length>0&&u({kind:"link",lines:y})}catch{}},[e,s,u]),Ce=X(async(a,l)=>{Rt(!0),he(null),V([]);let i=++Tt.current;u({kind:"user",text:l?.echoDisplay&&l.display?l.display:a});let h=$e.current;h.firstPrompt||(h.firstPrompt=l?.display??a),Be.current=Date.now(),lt(0),z(!0),At.current.clear();let p="",m="",y=null,T=()=>{y||(y=setTimeout(()=>{y=null,g(m.length>0?m:null)},60))},D=()=>{y&&clearTimeout(y),y=null,g(null)},M=()=>{if(m.trim()){let A=m.trimEnd();u({kind:"assistant",text:A})}m="",D()};try{for await(let A of ce.current.send(a))if(A.type==="session"){if(!h.uuid){h.uuid=A.sessionId;let N=new Date().toISOString(),P=_c(h.firstPrompt??"session");Nc({uuid:A.sessionId,name:P,renamed:!1,titled:!1,cwd:e,firstPrompt:h.firstPrompt??"",createdAt:N,updatedAt:N}),Ye(P)}}else if(A.type==="text"){m+=A.delta,p+=A.delta;let N=Fs(m);if(N>0){let P=m.slice(0,N).trimEnd();P&&u({kind:"assistant",text:P}),m=m.slice(N)}T(),lt(P=>P+A.delta.length)}else if(A.type==="tool"){let N=ro(A.name,A.input);N&&(M(),u({kind:"tool",title:N.title,sep:N.sep,arg:N.arg}),At.current.set(A.id,{name:A.name,input:A.input}))}else if(A.type==="article_diff"){let N=Fe(A.oldContent,A.newContent,je());N&&(M(),u({kind:"diff",added:N.added,removed:N.removed,lines:N.lines,hidden:N.hidden}))}else if(A.type==="tool_result"){A.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(A.output)&&(Dt.current=!0);let N=At.current.get(A.id);if(N){At.current.delete(A.id),M();let P=so(A.output,4,A.isError?void 0:N.name,N.input);u({kind:"tool-result",lines:P.lines,hidden:P.hidden,isError:A.isError}),A.isError||Wn(N.name,N.input,A.output)}}else if(A.type==="result"){M(),ut(P=>P+A.outputTokens),dt(P=>P+A.costUsd),u({kind:"done",seconds:Math.round((Date.now()-Be.current)/1e3),tokens:A.outputTokens,costUsd:A.costUsd,ok:A.ok});let N=A.ok?Ds(p,kt.map(P=>P.name)):[];if(N.length>0?V(N):A.ok&&p.trim()&&Uc(a,p,e).then(P=>{P&&Tt.current===i&&he(P)}).catch(()=>{}),h.uuid&&(bn(h.uuid),!h.titleFired)){h.titleFired=!0;let P=h.uuid,j=h.firstPrompt;j&&zs(j,e).then(W=>{W&&(Ic(P,W),Ye(W))}).catch(()=>{})}}else A.type==="error"&&(M(),A.kind==="auth"&&(Dt.current=!0),u({kind:"note",text:`agent error: ${A.message}`,tone:"error"}))}finally{z(!1),D(),$e.current.uuid&&As(e,$e.current.uuid,Ge.current),Dt.current&&(Dt.current=!1,It.current=l?.display??a,V(["/login"])),Et.current&&(Et.current=!1,Oe.current.length>0&&(u({kind:"note",tone:"info",text:`(${Oe.current.length} queued message(s) discarded)`}),Oe.current=[],$o([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,Wn,je]),Co=X(a=>{let l=He(a);if(!l||Ie(l)&&!l.refreshToken)return null;let i={...st(l.idToken)??{},...st(l.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),Po=X((a,l)=>{if(l){let i=ie(e);i&&(i.defaultProfile=a,Wc(i,e))}c(a),re(void 0,a),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${a}"${l?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Co(a)||(u({kind:"note",tone:"warn",text:`Profile "${a}" is not signed in \u2014 do you want to log in now? (press 1)`}),V(["/login"])),we(i=>i+1)},[e,u,re,Co]),Mt=X((a,l,i)=>{Wt(e,a,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),re(),Gs(e,a)||(u({kind:"note",tone:"info",text:"Setup complete. Press tab to start with a docs analysis."}),he("analyze this repo and propose a docs structure"))},[e,u,re]),So=X(async a=>{let l;try{l=await gt(e,a)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),V(["/workspace"]);return}if(l.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=l.workspaces.filter(p=>(p.workspace_type??"").toLowerCase()!=="apidocumentation"),h=i.length>0?i:l.workspaces;if(h.length===1){let p=h[0],m=l.workspaces.length-h.length;u({kind:"note",tone:"ok",text:`Selected the "${p.name??p.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),Mt(l.profile,l.projectId,p);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${h.length} available).`}),V(["/workspace"])},[e,u,Mt]),Fn=X((a,l)=>{cn(e,a,l.id),u({kind:"note",tone:"ok",text:`Project set to "${l.name??l.id}" (agent restarted).`}),re(),So(a)},[e,u,re,So]),Lt=X(()=>{let a=Te.current[0];if(!a)return;u({kind:"note",tone:"info",text:`\u25CF ${a.title} (${a.path})`});for(let i of a.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${i}`});a.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let l=Fe(a.oldContent,a.newContent,je());u(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."}),u({kind:"note",tone:"info",text:`Write ${a.path}? (y/n \u2014 anything else cancels)`})},[u,je]),Hn=X(a=>{if(Te.current.length===0)return!1;let l=a.trim().toLowerCase();if(l==="y"||l==="yes"){let i=Te.current.shift();try{Fc({cwd:e,profileName:s},i),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${i.path} (sync base advanced).`}),Te.current.length===0&&V(h=>h.length>0?h:["/sync"])}catch(h){u({kind:"note",tone:"error",text:`Pull failed: ${h.message}`})}}else if(l==="n"||l==="no"){let i=Te.current.shift();u({kind:"note",tone:"info",text:`Skipped ${i.path}.`})}else{let i=Te.current.length;return Te.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${i} article(s) left untouched).`}),!0}return Lt(),!0},[e,s,Lt,u]),Bn=X(a=>{let l=wo.current;if(!l)return!1;if(wo.current=null,a.trim()!==l.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:h}=gn(e,l.targets);u({kind:"note",tone:h.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let p of h)u({kind:"note",tone:"error",text:` \u2717 ${p.path}: ${p.error}`});return u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
81
|
+
${Vs}`}),V(["/init"]),Rt(!1),!0},[e,u]),qn=X(async a=>{let l=a.slice(1).trim().split(/\s+/),i=(l[0]??"").toLowerCase(),h=l.slice(1);switch(Rt(!0),i){case"help":u({kind:"note",tone:"info",text:Yt().join(`
|
|
82
|
+
`)});return;case"exit":case"quit":ce.current?.close(),r();return;case"clear":re(),Ge.current=[],Rt(!1),he(null),Tt.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let p;try{p=le(e,s)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${p.name}" \u2192 ${p.connection.name} (${p.connection.apiUrl})${p.production?" \u26A0 PRODUCTION":""}`}),ae(!0);try{let m=await Pc(p.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},D=>u({kind:"note",tone:"info",text:D})),y=Sc(p.name,m);Tc(y),Ao(y,p.name,D=>u({kind:"note",tone:"info",text:D})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${p.name}" as ${Ht(y)}`});let T=(()=>{try{return le(e,s)}catch{return p}})();T.project.workspaceId||(T.project.projectId?await So(T.name):(u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),V(["/project"]))),It.current&&(he(It.current),It.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{ae(!1),we(m=>m+1)}return}case"allow-prod":{let p=!1;try{p=le(e,s).production}catch{}if(!p){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}ct.current=!0,re(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let p=nn(h.join(" ")),m=$e.current.uuid;if(!m){u({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!p){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let y=$e.current.firstPrompt??"";zs(y,e).then(T=>{T?(he(`/rename ${T}`),u({kind:"note",tone:"info",text:`Suggestion: "${T}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}Oc(m,p),Ye(p),Pt(`${xn} d360-writer \xB7 ${p}`),u({kind:"note",tone:"ok",text:`Session renamed to "${p}".`});return}case"profile":{let p=h[0],m=ie(e);if(!p){let y=Object.entries(m?.profiles??{});if(y.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let T=y.map(([A,N])=>({name:A,env:N.connection?.environment??"custom",prod:N.production===!0,who:Co(A)})),D=s??m?.defaultProfile,M=Math.max(0,T.findIndex(A=>A.name===D));Xe({cursor:M,current:M,rows:T});return}if(p==="add"){let y=rn(e,h[1],h[2]);if(y){u({kind:"note",tone:"error",text:y});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${h[1]}" created (environment: ${h[2]??h[1]}).`}),Po(h[1],!1);return}if(!m?.profiles?.[p]){u({kind:"note",tone:"error",text:`Unknown profile "${p}". Create it: /profile add ${p} <environment>`});return}Po(p,!0);return}case"doctor":await vt(h,{cwd:e});return;case"mcp":await Vt(h);return;case"init":{if(ie(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let p=qc().map(m=>({name:m,apiUrl:zc(m).apiUrl}));Ve({cursor:0,rows:p});return}case"resume":{let p=h.join(" ").trim(),m=Lc(e).filter(D=>D.uuid!==$e.current.uuid);if(!p){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ue({query:"",cursor:0,sessions:m});return}let y=Mc(e,p);if(!y){u({kind:"note",tone:"error",text:`No session matches "${p}".`});return}re(y.uuid),$e.current={uuid:y.uuid,firstPrompt:y.firstPrompt,titleFired:!0},Ye(y.name),bn(y.uuid),Ge.current=[];let T=$n(e,y.uuid);for(let D of T)u(D);u({kind:"note",tone:"ok",text:T.length?`Resumed "${y.name}" \u2014 restored ${T.length} message(s); continue where you left off.`:`Resumed "${y.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let p=h.join(" ").trim(),m;try{m=await gt(e,s)}catch(T){u({kind:"note",tone:"error",text:`Could not list workspaces: ${T.message}`});return}if(!p){let T=m.workspaces.map(M=>({id:M.id,name:M.name??M.id,type:M.workspace_type}));if(T.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let D=Math.max(0,T.findIndex(M=>M.id===m.current));Je({cursor:D,current:D,rows:T,profile:m.profile,projectId:m.projectId,environment:m.environment});return}let y=jo(m.workspaces,p);if(!y){u({kind:"note",tone:"error",text:`No workspace matches "${p}".`});return}Mt(m.profile,m.projectId,y);return}case"project":{let p=h.join(" ").trim(),m;try{m=await an(e,s)}catch(T){u({kind:"note",tone:"error",text:`Could not list projects: ${T.message} (signed in? try /login)`});return}if(!p){let T=m.projects.map(M=>({id:M.id,name:M.name??M.id,sub:M.sub_domain}));if(T.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let D=T.findIndex(M=>M.id===m.current);Ke({cursor:Math.max(0,D),current:D,rows:T,profile:m.profile,environment:m.environment});return}let y=rs(m.projects,p);if(!y){u({kind:"note",tone:"error",text:`No project matches "${p}". Available: ${m.projects.map(T=>T.name??T.id).join(", ")}`});return}Fn(m.profile,y);return}case"logout":{let p;try{p=le(e,s).name}catch(y){u({kind:"note",tone:"error",text:y.message});return}let m=Ec(p);Dc(e,p),re(),we(y=>y+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${p}" and cleared its project/workspace selection.`:`Profile "${p}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),V(["/login"]);return}case"publish":{if(h[0]&&h[0]!=="--all"){await Ce(Kt(h[0]),{display:`/publish ${h[0]}`,echoDisplay:!0});return}let p=h[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await vn({cwd:e,profileName:s}),y=Jt(m.entries);if(y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let D=m.counts["unknown-base"]??0;D>0&&u({kind:"note",tone:"info",text:`(${D} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(p){await Ce(wt(y.map(D=>D.path)),{display:"/publish --all",echoDisplay:!0});return}let T=y.length>1?[{path:"--all",label:`publish all ${y.length} candidates in one run`},...y]:y;Qe({cursor:0,rows:T})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let p=h.join(" ").trim();if(!p){let y=[];try{y=Object.keys(Gs(e,le(e,s).name)?.articles??{})}catch{}if(y.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Le({query:"",cursor:0,paths:y});return}let m=Cc(p)?p:St(e,p);if(Hs(m)){try{u({kind:"preview",name:go(m),text:Ks(Bs(m,"utf8"))})}catch(y){u({kind:"note",tone:"error",text:`Could not read ${m}: ${y.message}`})}return}if(tu.test(p)){try{let y=le(e,s),T={profile:y.name,connection:y.connection},D=y.project.projectId??jc(T),M=await Ac(T,D,p);u({kind:"preview",name:M.title??p,text:M.content??"*(article has no content)*"})}catch(y){u({kind:"note",tone:"error",text:`Could not fetch article: ${y.message}`})}return}u({kind:"note",tone:"error",text:`"${p}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let p=h[0]?.trim();if(!p){let D=to(Tn(e));Me({cursor:D,current:D});return}let{lines:m,changed:y,effective:T}=bt(e,p);for(let D of m)u({kind:"note",tone:D.startsWith("\u26A0")?"warn":D.startsWith("\u2713")?"ok":"info",text:D});y&&(Mn(D=>D+1),ce.current?.setModel(T));return}case"convert":{if(!ie(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:p,run:m}=qo(h),y=Xc(e,s);if(y.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let T=zo(y,p);if(T.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${p}". (${y.length} are tracked overall.)`});return}let D=Ys(T),M=3,A=`/convert${p?` --scope ${p}`:""} --run`,N=Pn(e,"light");if(!m){let j=Xs({files:Go(e,T),op:"convert",model:N.model}),W=p?`Scope: ${p} (${T.length} of ${y.length} tracked)
|
|
83
83
|
`:"",ee=`
|
|
84
|
-
Model: ${N.model}${N.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;
|
|
85
|
-
`)+ee}),V([A]);return}Be.current=Date.now(),lt(0),z(!0);let P=new AbortController;ve.current=P,Z({total:
|
|
86
|
-
`)})}}catch(j){
|
|
84
|
+
Model: ${N.model}${N.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:W+Xo(D,j,M).join(`
|
|
85
|
+
`)+ee}),V([A]);return}Be.current=Date.now(),lt(0),z(!0);let P=new AbortController;ve.current=P,Z({total:D.length,done:0,active:[],tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${T.length} articles across ${D.length} partitions (\u2264${M} agents at once) on ${N.model}\u2026 (esc to stop)`});try{for await(let j of Cn({cwd:e,partitions:D,promptFor:Yo,concurrency:M,profileName:s,allowProdWrites:ct.current,model:N.model,signal:P.signal}))if(j.type==="partition_status")j.status==="running"?(Z(W=>W&&{...W,active:[...W.active,j.label],lastAt:Date.now()}),u({kind:"note",tone:"info",text:` \u25B8 ${j.label} \u2014 converting\u2026`})):(Z(W=>W&&{...W,active:W.active.filter(ee=>ee!==j.label),done:W.done+1,lastAt:Date.now()}),u({kind:"note",tone:j.status==="done"?"ok":"error",text:` ${j.status==="done"?"\u2713":"\u2717"} ${j.label}`}));else if(j.type==="partition_event")Z(W=>{if(!W)return W;let ee={...W,lastAt:Date.now()};return j.event.type==="tool"?ee.tools=W.tools+1:j.event.type==="text"&&(ee.chars=W.chars+j.event.delta.length),ee});else if(j.type==="run_done"){dt(O=>O+j.totalCostUsd),ut(O=>O+j.results.reduce((Y,te)=>Y+te.outputTokens,0));let W=j.aborted?"Stopped. ":"",ee=t.kind==="api"?"api":"subscription";u({kind:"note",tone:j.aborted?"warn":j.ok?"ok":"warn",text:W+Vo(j.results,D,ee).join(`
|
|
86
|
+
`)})}}catch(j){u({kind:"note",tone:"error",text:`Convert run failed: ${j.message}`})}finally{ve.current=null,Z(null),z(!1)}return}case"write":{if(!ie(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=Vc(e);if(p.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:y,run:T}=Ko(h),{docsDir:D,targets:M,reason:A}=on(e,p,{scope:m,path:y});if(M.length===0){u({kind:"note",tone:"warn",text:A??"Nothing to write."});return}let N=Ys(M),P=5,j=Pn(e,"standard");if(!T&&!!!y){let O=Xs({files:Qo(e,p,M),op:"write",model:j.model}),Y=m?`Scope: ${m} (${M.length} pending)
|
|
87
87
|
`:"",te=`
|
|
88
|
-
Model: ${j.model}${j.forced?" (forced)":" \u2014 authoring; /model to override"}`;
|
|
89
|
-
`)+te}),V([`/write${
|
|
90
|
-
`)})}}catch(O){
|
|
91
|
-
`)});return}if(p==="pull"){let
|
|
92
|
-
`)})}return}case"screenshot":{let p=
|
|
93
|
-
`)});return}if(p.mode==="single"){let P=await
|
|
94
|
-
`)})}return}case"reset":{let p=
|
|
95
|
-
`)});return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Nt,d,re,Ce]),Mt=X(a=>{let l=(a??D).trim();if(b(""),Rt(null),qe(0),l.startsWith("/")){let k=g=>g.trim().split(/\s+/).slice(1).join(" "),p=k(l);V(g=>g.filter(y=>y.trim()!==l&&!(p&&k(y)===p)))}if(!l||Hn(l)||Fn(l))return;ko.current.push(l);let i=Ns(l,Rn.current);l.startsWith("/")?Bn(i):Ce(i,{display:l})},[D,Hn,Fn,Bn,Ce]),qn=X(a=>{if(a.length>1){if(a.includes("\x1B"))return;let l=Ds(a);if(Is(l)){let i=_s(++si.current,l);Rn.current.set(i,l),C(i)}else C(l);return}C(a)},[C]),et=Math.max(10,We-6),zn=fo(()=>uo(h.text,et),[h.text,et]),Po=X(a=>w(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+a))})),[]),Lt=X(a=>w(l=>({...l,pos:Ls(uo(l.text,et),l.pos,a)})),[et]),ft=X(a=>w(l=>({...l,pos:Os(uo(l.text,et),l.pos,a)})),[et]),ai=["\x1B[H","\x1B[1~","\x1BOH"],ci=["\x1B[F","\x1B[4~","\x1BOF"],Gn=X((a,l)=>l.leftArrow?(Po(-1),!0):l.rightArrow?(Po(1),!0):a&&ai.includes(a)?(ft("start"),!0):a&&ci.includes(a)?(ft("end"),!0):l.ctrl&&a==="a"?(ft("start"),!0):l.ctrl&&a==="e"?(ft("end"),!0):!1,[Po,ft]);return xc((a,l)=>{if(l.ctrl&&a==="c"){ae.current?.close(),r();return}if(!G){if(I){if(l.escape){if(ve.current){ve.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ve.current.abort());return}At.current||(At.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ae.current?.interrupt());return}if(l.return){let i=D.trim();if(!i)return;Oe.current.push(i),wo([...Oe.current]),b("");return}if(Gn(a,l))return;if(l.upArrow){Lt(-1);return}if(l.downArrow){Lt(1);return}if(l.backspace||l.delete){x();return}a&&!l.ctrl&&!l.meta&&qn(a);return}if(Ne){if(l.upArrow){Me(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Me(i=>i&&{...i,cursor:Math.min(ye.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=ye.length){Me(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=ye[Ne.cursor];Me(null);let{lines:k,changed:p,effective:g}=xt(e,i.value??"default");for(let y of k)d({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});p&&(_n(y=>y+1),ae.current?.setModel(g));return}if(a==="s"){let i=ye[Ne.cursor];Me(null),ae.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){Me(null);return}return}if(xe){if(l.upArrow){Xe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Xe(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){Xe(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return||a==="s"){let i=xe.rows[xe.cursor];Xe(null),Co(i.name,l.return===!0);return}if(l.escape){Xe(null);return}return}if(Re){if(l.upArrow){Ve(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ve(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=Re.rows.length){Ve(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=Re.rows[Re.cursor].name;if(Ve(null),!pr(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 p=!1;try{let g=He(i);p=!!g&&!(Ie(g)&&!g.refreshToken)}catch{}p?(d({kind:"note",tone:"info",text:`Already signed in to ${i} \u2014 next: pick a workspace.`}),V(["/workspace"])):(d({kind:"note",tone:"info",text:`Next: sign in to Document360 (${i}).`}),V(["/login"])),we(g=>g+1);return}if(l.escape){Ve(null);return}return}if(oe){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(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=oe.rows.length){Je(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=oe.rows[oe.cursor],{profile:k,projectId:p}=oe;Je(null),Un(k,p,i);return}if(l.escape){Je(null);return}return}if(ce){if(l.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=ce.rows.length){Ke(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=ce.rows[ce.cursor],{profile:k}=ce;Ke(null),Wn(k,i);return}if(l.escape){Ke(null);return}return}if(ne){if(l.upArrow){Ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ze(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a===" "){Ze(i=>i&&{...i,rows:i.rows.map((k,p)=>p===i.cursor?{...k,checked:!k.checked}:k)});return}if(l.return){let i=ne.rows.filter(k=>k.checked).map(k=>k.path);if(Ze(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Do(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){Ze(null);return}return}if(be){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&&/^[1-9]$/.test(a)&&Number(a)<=be.rows.length){Qe(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=be.rows[be.cursor],k=be.rows.filter(p=>p.path!=="--all").map(p=>p.path);Qe(null),Ce(i.path==="--all"?yt(k):Jt(i.path),{display:i.path==="--all"?"/publish --all":`/publish ${i.path}`,echoDisplay:!0});return}if(l.escape){Qe(null);return}return}if(ue){if(l.escape){Le(null);return}if(l.upArrow){Le(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Le(i=>i&&{...i,cursor:Math.min(Math.max(0,It.length-1),i.cursor+1)});return}if(l.return){let i=It[ue.cursor];if(i){Le(null);try{d({kind:"preview",name:mo(i),text:Js(Hs(Pt(e,i),"utf8"))})}catch(k){d({kind:"note",tone:"error",text:`Could not read ${i}: ${k.message}`})}}return}if(l.backspace||l.delete){Le(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(a&&!l.ctrl&&!l.meta&&a.length===1){Le(i=>i&&{...i,query:i.query+a,cursor:0});return}return}if(de){if(l.escape){Ue(null);return}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(Math.max(0,_t.length-1),i.cursor+1)});return}if(l.return){let i=_t[de.cursor];if(i){Ue(null),re(i.uuid),$e.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},Ye(i.name),$n(i.uuid),Ge.current=[];let k=yn(e,i.uuid);for(let p of k)d(p);d({kind:"note",tone:"ok",text:k.length?`Resumed "${i.name}" \u2014 restored ${k.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){Ue(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(a&&!l.ctrl&&!l.meta&&a.length===1){Ue(i=>i&&{...i,query:i.query+a,cursor:0});return}return}if(l.tab&&!D&&ge){b(ge),he(null),St.current++;return}if(!D&&it.length>0&&a&&/^[1-9]$/.test(a)){let i=it[Number(a)-1];if(i){b(i);return}}if(!Gn(a,l)){if(Ln){if(l.upArrow){qe(i=>Math.max(0,i-1));return}if(l.downArrow){qe(i=>Math.min(pt.length-1,i+1));return}if(l.tab){b("/"+(pt[at]?.name??"")+" "),qe(0);return}if(l.return){let i=pt[at];if(i){let k=D.trim().slice(1).split(/\s+/).slice(1).join(" ");if(lr(i.usage)&&!k){b("/"+i.name+" "),qe(0);return}Mt("/"+i.name+(k?" "+k:""));return}}}else{if(l.upArrow){if(D!==""&&ze===null){Lt(-1);return}let i=ko.current;if(!i.length)return;let k=ze===null?i.length-1:Math.max(0,ze-1);Rt(k),b(i[k]??"");return}if(l.downArrow){if(D!==""&&ze===null){Lt(1);return}let i=ko.current;if(ze===null)return;let k=ze+1;k>=i.length?(Rt(null),b("")):(Rt(k),b(i[k]??""));return}}if(l.return){Mt();return}if(l.backspace||l.delete){x();return}if(l.escape){b(""),qe(0),he(null),V([]);return}a&&!l.ctrl&&!l.meta&&qn(a)}}}),_e(()=>{if(I||G)return;let a=Oe.current.shift();a!==void 0&&(wo([...Oe.current]),Mt(a))},[I,G,Mt]),U(J,{flexDirection:"column",width:We,children:[bo!==null&&U(J,{marginTop:1,flexDirection:"column",children:[bo.truncated&&S(v,{dimColor:!0,children:"\u2026"}),S(v,{children:bo.text})]}),I&&(En?S(ru,{p:En}):S(ou,{startTime:Be.current,chars:ri})),S(J,{borderStyle:"round",borderColor:Mn.prod?"yellow":B,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:D?zn.map((a,l)=>{let i=h.text.slice(a.start,a.end),k=l===po(zn,h.pos),p=Math.min(h.pos,a.end)-a.start;return U(v,{children:[S(v,{color:B,children:l===0?"> ":" "}),k?U(Cn,{children:[i.slice(0,p),S(go,{ch:i[p]??" "}),i.slice(p+1)]}):i||" "]},`${l}-${a.start}`)}):U(v,{children:[S(v,{color:B,children:"> "}),ge&&!I?U(Cn,{children:[S(go,{ch:ge[0],dim:!0}),S(v,{color:"gray",children:ge.slice(1)}),S(v,{dimColor:!0,children:" (tab)"})]}):xo.isSetup||!ni?U(Cn,{children:[S(go,{ch:xo.text[0],dim:!0}),S(v,{color:"gray",children:xo.text.slice(1)})]}):S(go,{ch:" "})]})}),An.length>0&&S(J,{flexDirection:"column",paddingX:1,children:An.map((a,l)=>S(v,{color:"gray",children:`\u29D7 queued: ${a}`},`${l}-${a.slice(0,24)}`))}),Ne?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Select model"}),S(v,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),ye.map((a,l)=>U(v,{color:l===Ne.cursor?B:void 0,children:[l===Ne.cursor?"\u276F ":" ",`${l+1}. ${a.label}${l===Ne.current?" \u2714":""}`.padEnd(16),S(v,{color:"gray",children:a.desc})]},a.label)),S(v,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):xe?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Switch connection profile"}),xe.rows.map((a,l)=>U(v,{color:l===xe.cursor?B:void 0,children:[l===xe.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===xe.current?" \u2714":""}`.padEnd(20),S(v,{color:"gray",children:`${a.env} \xB7 ${a.who??"not signed in"}`}),a.prod?S(v,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},a.name)),S(v,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Re?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Pick your Document360 environment"}),Re.rows.map((a,l)=>U(v,{color:l===Re.cursor?B:void 0,children:[l===Re.cursor?"\u276F ":" ",`${l+1}. ${a.name}`.padEnd(16),S(v,{color:"gray",children:a.apiUrl})]},a.name)),S(v,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):oe?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Switch workspace"}),S(v,{dimColor:!0,children:`environment ${oe.environment} \xB7 project ${oe.projectId.slice(0,8)}\u2026`}),oe.rows.map((a,l)=>U(v,{color:l===oe.cursor?B:void 0,children:[l===oe.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===oe.current?" \u2714":""}`.padEnd(30),S(v,{color:"gray",children:a.type??""})]},a.id)),S(v,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ce?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Choose project"}),S(v,{dimColor:!0,children:`environment ${ce.environment}`}),ce.rows.map((a,l)=>U(v,{color:l===ce.cursor?B:void 0,children:[l===ce.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===ce.current?" \u2714":""}`.padEnd(30),S(v,{color:"gray",children:a.sub??""})]},a.id)),S(v,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ne?(()=>{let l=Math.min(Math.max(0,ne.cursor-Math.floor(7)),Math.max(0,ne.rows.length-14)),i=ne.rows.slice(l,l+14),k=ne.rows.filter(p=>p.checked).length;return U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:`Which folders back the user docs? (${k} selected of ${ne.rows.length})`}),l>0?S(v,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((p,g)=>{let y=l+g;return U(v,{color:y===ne.cursor?B:void 0,children:[y===ne.cursor?"\u276F ":" ",p.checked?"\u25C9 ":"\u25CB ",p.path.padEnd(Math.min(48,We-34)),S(v,{color:"gray",children:Qt(p)})]},p.path)}),l+14<ne.rows.length?S(v,{dimColor:!0,children:` \u2193 ${ne.rows.length-l-14} more`}):null,S(v,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():be?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Publish which article?"}),be.rows.map((a,l)=>U(v,{color:l===be.cursor?B:void 0,children:[l===be.cursor?"\u276F ":" ",`${l+1}. ${a.path}`.padEnd(Math.min(56,We-30)),S(v,{color:"gray",children:a.label})]},a.path)),S(v,{dimColor:!0,children:"enter publish (draft) \xB7 esc cancel"})]}):ue?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:`Preview article${ue.query?` \u2014 filter: ${ue.query}`:" (type to filter)"}`}),It.length===0?S(v,{color:"gray",children:"no articles match"}):It.map((a,l)=>U(v,{color:l===ue.cursor?B:void 0,children:[l===ue.cursor?"\u276F ":" ",a]},a)),S(v,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):de?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:`Resume session${de.query?` \u2014 filter: ${de.query}`:" (type to filter)"}`}),_t.length===0?S(v,{color:"gray",children:"no sessions match"}):_t.map((a,l)=>U(v,{color:l===de.cursor?B:void 0,children:[l===de.cursor?"\u276F ":" ",a.name.slice(0,28).padEnd(30),S(v,{color:l===de.cursor?B:"gray",children:a.firstPrompt.slice(0,Math.max(10,We-40))})]},a.uuid)),S(v,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Ln?S(J,{flexDirection:"column",children:pt.map((a,l)=>U(v,{color:l===at?B:void 0,children:[l===at?"\u276F ":" ",a.usage.padEnd(22)," ",S(v,{color:l===at?B:"gray",children:a.name==="model"&&$o?`${a.desc} (currently ${$o})`:a.desc})]},a.name))}):!D&&it.length>0?U(J,{flexDirection:"column",paddingX:1,children:[it.map((a,l)=>U(v,{children:[S(v,{color:B,children:l+1})," ",a.slice(0,Math.max(20,We-5))]},a)),S(v,{dimColor:!0,children:`press 1-${it.length} to fill the command \xB7 esc dismiss`})]}):S(J,{paddingX:1,children:U(v,{color:"gray",children:[Mn.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${$o??"model n/a"}${t.kind==="api"?In>0?` \xB7 ${pe(In)}`:"":Dn>0?` \xB7 ${rt(Dn)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as lu}from"react/jsx-runtime";async function ei(e=process.cwd(),t="auto",o,n="0.0.0"){let r=iu(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${R("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${R("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=su(lu(Zs,{cwd:e,auth:r,profileName:o,version:n}));await s(),process.stdout.write(`
|
|
96
|
-
`),process.exit(0)}var
|
|
88
|
+
Model: ${j.model}${j.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:Y+en(N,O,P).join(`
|
|
89
|
+
`)+te}),V([`/write${m?` --scope ${m}`:" --all"} --run`]);return}Be.current=Date.now(),lt(0),z(!0);let ee=new AbortController;ve.current=ee,Z({verb:"Writing",total:N.length,done:0,active:[],tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${M.length} article${M.length===1?"":"s"} across ${N.length} partition${N.length===1?"":"s"} (\u2264${P} agents at once) on ${j.model}${j.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let O of Cn({cwd:e,partitions:N,promptFor:Y=>Zo(Y,D),concurrency:P,profileName:s,allowProdWrites:ct.current,model:j.model,signal:ee.signal}))if(O.type==="partition_status")O.status==="running"?(Z(Y=>Y&&{...Y,active:[...Y.active,O.label],lastAt:Date.now()}),u({kind:"note",tone:"info",text:` \u25B8 ${O.label} \u2014 writing\u2026`})):(Z(Y=>Y&&{...Y,active:Y.active.filter(te=>te!==O.label),done:Y.done+1,lastAt:Date.now()}),u({kind:"note",tone:O.status==="done"?"ok":"error",text:` ${O.status==="done"?"\u2713":"\u2717"} ${O.label}`}));else if(O.type==="partition_event")Z(Y=>{if(!Y)return Y;let te={...Y,lastAt:Date.now()};return O.event.type==="tool"?te.tools=Y.tools+1:O.event.type==="text"&&(te.chars=Y.chars+O.event.delta.length),te});else if(O.type==="run_done"){dt(Ro=>Ro+O.totalCostUsd),ut(Ro=>Ro+O.results.reduce((di,pi)=>di+pi.outputTokens,0));let Y=O.aborted?"Stopped. ":"",te=t.kind==="api"?"api":"subscription";u({kind:"note",tone:O.aborted?"warn":O.ok?"ok":"warn",text:Y+tn(O.results,N,te).join(`
|
|
90
|
+
`)})}}catch(O){u({kind:"note",tone:"error",text:`Write run failed: ${O.message}`})}finally{ve.current=null,Z(null),z(!1)}return}case"sync":{let p=(h[0]??"status").toLowerCase();try{if(p==="status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let m=await vn({cwd:e,profileName:s});u({kind:"note",tone:"info",text:eo(m).join(`
|
|
91
|
+
`)});return}if(p==="pull"){let m=h[1];if(!m){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let y;if(m==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),y=(await vn({cwd:e,profileName:s})).entries.filter(M=>M.status==="remote-ahead"&&M.path).map(M=>M.path),y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else y=[m.replace(/\\/g,"/")];let T=[];for(let D of y)T.push(await Hc({cwd:e,profileName:s,relPath:D}));Te.current=T,Lt();return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${p} \u2014 use /sync or /sync pull <path>|--all.`})}catch(m){u({kind:"note",tone:"error",text:`Sync failed: ${m.message}`})}return}case"scope":{if(!ie(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let p=Bc(e);if(p.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}Ze({cursor:0,rows:p.map(m=>({...m,checked:m.recommended}))});return}case"audit":case"capture-setup":{let m=await(i==="audit"?Qt:Ct)(h,void 0);if(m.kind==="forward-to-agent"&&m.prompt&&await Ce(m.prompt,{display:m.display,echoDisplay:!0}),i==="capture-setup"){let y=fn(e);y&&u({kind:"note",tone:"info",text:y.join(`
|
|
92
|
+
`)})}return}case"screenshot":{let p=un(h);if(p.mode==="list"){if(!ie(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:pn(dn(e,p.scope),p.scope).join(`
|
|
93
|
+
`)});return}if(p.mode==="single"){let P=await no(h);P.kind==="forward-to-agent"&&P.prompt&&await Ce(P.prompt,{display:P.display,echoDisplay:!0});return}if(!ie(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=p.mode==="scope"?p.scope:void 0,y=Yc(e,{scope:m}).map(P=>P.id);if(y.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let T=6,D=Gc(y,3),M=Pn(e,"standard");Be.current=Date.now(),lt(0),z(!0);let A=new AbortController;ve.current=A,Z({verb:"Authoring",total:D.length,done:0,active:[],tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${y.length} screenshot spec${y.length===1?"":"s"} across ${D.length} partition${D.length===1?"":"s"} (\u2264${T} agents at once) on ${M.model}${M.forced?" (forced)":""}\u2026 (esc to stop)`});let N=!1;try{for await(let P of Cn({cwd:e,partitions:D,promptFor:ps,concurrency:T,profileName:s,allowProdWrites:ct.current,model:M.model,signal:A.signal}))if(P.type==="partition_status")P.status==="running"?(Z(j=>j&&{...j,active:[...j.active,P.label],lastAt:Date.now()}),u({kind:"note",tone:"info",text:` \u25B8 ${P.label} \u2014 authoring\u2026`})):(Z(j=>j&&{...j,active:j.active.filter(W=>W!==P.label),done:j.done+1,lastAt:Date.now()}),u({kind:"note",tone:P.status==="done"?"ok":"error",text:` ${P.status==="done"?"\u2713":"\u2717"} ${P.label}`}));else if(P.type==="partition_event")Z(j=>{if(!j)return j;let W={...j,lastAt:Date.now()};return P.event.type==="tool"?W.tools=j.tools+1:P.event.type==="text"&&(W.chars=j.chars+P.event.delta.length),W});else if(P.type==="run_done"){dt(O=>O+P.totalCostUsd),ut(O=>O+P.results.reduce((Y,te)=>Y+te.outputTokens,0));let j=P.results.filter(O=>O.ok).length,W=P.aborted?"Stopped. ":"";N=!P.aborted&&p.setup;let ee=P.aborted?"":N?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:P.aborted?"warn":P.ok?"ok":"warn",text:`${W}Authored specs \u2014 ${j}/${P.results.length} batches ok.${ee}`})}}catch(P){u({kind:"note",tone:"error",text:`Spec authoring failed: ${P.message}`})}finally{ve.current=null,Z(null),z(!1)}if(N){let P=await Ct();P.kind==="forward-to-agent"&&P.prompt&&await Ce(P.prompt,{display:P.display,echoDisplay:!0});let j=fn(e);j&&u({kind:"note",tone:"info",text:j.join(`
|
|
94
|
+
`)})}return}case"reset":{let p=mn(e);if(p.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}wo.current={repoName:go(e),targets:p},u({kind:"note",tone:"warn",text:hn(e,p).join(`
|
|
95
|
+
`)});return}default:u({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,Lt,u,re,Ce]),Ot=X(a=>{let l=(a??I).trim();if(b(""),jt(null),qe(0),l.startsWith("/")){let h=m=>m.trim().split(/\s+/).slice(1).join(" "),p=h(l);V(m=>m.filter(y=>y.trim()!==l&&!(p&&h(y)===p)))}if(!l||Bn(l)||Hn(l))return;yo.current.push(l);let i=Ms(l,An.current);l.startsWith("/")?qn(i):Ce(i,{display:l})},[I,Bn,Hn,qn,Ce]),zn=X(a=>{if(a.length>1){if(a.includes("\x1B"))return;let l=Is(a);if(_s(l)){let i=Ns(++ii.current,l);An.current.set(i,l),C(i)}else C(l);return}C(a)},[C]),et=Math.max(10,We-6),Gn=mo(()=>po(k.text,et),[k.text,et]),To=X(a=>w(l=>({...l,pos:Math.max(0,Math.min(l.text.length,l.pos+a))})),[]),Ut=X(a=>w(l=>({...l,pos:Os(po(l.text,et),l.pos,a)})),[et]),ft=X(a=>w(l=>({...l,pos:Us(po(l.text,et),l.pos,a)})),[et]),ci=["\x1B[H","\x1B[1~","\x1BOH"],ui=["\x1B[F","\x1B[4~","\x1BOF"],Yn=X((a,l)=>l.leftArrow?(To(-1),!0):l.rightArrow?(To(1),!0):a&&ci.includes(a)?(ft("start"),!0):a&&ui.includes(a)?(ft("end"),!0):l.ctrl&&a==="a"?(ft("start"),!0):l.ctrl&&a==="e"?(ft("end"),!0):!1,[To,ft]);return bc((a,l)=>{if(l.ctrl&&a==="c"){ce.current?.close(),r();return}if(!G){if(_){if(l.escape){if(ve.current){ve.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ve.current.abort());return}Et.current||(Et.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ce.current?.interrupt());return}if(l.return){let i=I.trim();if(!i)return;Oe.current.push(i),$o([...Oe.current]),b("");return}if(Yn(a,l))return;if(l.upArrow){Ut(-1);return}if(l.downArrow){Ut(1);return}if(l.backspace||l.delete){x();return}a&&!l.ctrl&&!l.meta&&zn(a);return}if(Ne){if(l.upArrow){Me(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Me(i=>i&&{...i,cursor:Math.min(ye.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=ye.length){Me(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=ye[Ne.cursor];Me(null);let{lines:h,changed:p,effective:m}=bt(e,i.value??"default");for(let y of h)u({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});p&&(Mn(y=>y+1),ce.current?.setModel(m));return}if(a==="s"){let i=ye[Ne.cursor];Me(null),ce.current?.setModel(i.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(l.escape){Me(null);return}return}if(xe){if(l.upArrow){Xe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Xe(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){Xe(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return||a==="s"){let i=xe.rows[xe.cursor];Xe(null),Po(i.name,l.return===!0);return}if(l.escape){Xe(null);return}return}if(Re){if(l.upArrow){Ve(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ve(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=Re.rows.length){Ve(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=Re.rows[Re.cursor].name;if(Ve(null),!fr(e,i).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${i}").`});let p=!1;try{let m=He(i);p=!!m&&!(Ie(m)&&!m.refreshToken)}catch{}p?(u({kind:"note",tone:"info",text:`Already signed in to ${i} \u2014 next: pick a workspace.`}),V(["/workspace"])):(u({kind:"note",tone:"info",text:`Next: sign in to Document360 (${i}).`}),V(["/login"])),we(m=>m+1);return}if(l.escape){Ve(null);return}return}if(oe){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(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=oe.rows.length){Je(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=oe.rows[oe.cursor],{profile:h,projectId:p}=oe;Je(null),Mt(h,p,i);return}if(l.escape){Je(null);return}return}if(ue){if(l.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a&&/^[1-9]$/.test(a)&&Number(a)<=ue.rows.length){Ke(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=ue.rows[ue.cursor],{profile:h}=ue;Ke(null),Fn(h,i);return}if(l.escape){Ke(null);return}return}if(ne){if(l.upArrow){Ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Ze(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(a===" "){Ze(i=>i&&{...i,rows:i.rows.map((h,p)=>p===i.cursor?{...h,checked:!h.checked}:h)});return}if(l.return){let i=ne.rows.filter(h=>h.checked).map(h=>h.path);if(Ze(null),i.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}_o(e,i),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let h of i)u({kind:"note",tone:"info",text:` ${h}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(l.escape){Ze(null);return}return}if(be){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&&/^[1-9]$/.test(a)&&Number(a)<=be.rows.length){Qe(i=>i&&{...i,cursor:Number(a)-1});return}if(l.return){let i=be.rows[be.cursor],h=be.rows.filter(p=>p.path!=="--all").map(p=>p.path);Qe(null),Ce(i.path==="--all"?wt(h):Kt(i.path),{display:i.path==="--all"?"/publish --all":`/publish ${i.path}`,echoDisplay:!0});return}if(l.escape){Qe(null);return}return}if(de){if(l.escape){Le(null);return}if(l.upArrow){Le(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(l.downArrow){Le(i=>i&&{...i,cursor:Math.min(Math.max(0,_t.length-1),i.cursor+1)});return}if(l.return){let i=_t[de.cursor];if(i){Le(null);try{u({kind:"preview",name:go(i),text:Ks(Bs(St(e,i),"utf8"))})}catch(h){u({kind:"note",tone:"error",text:`Could not read ${i}: ${h.message}`})}}return}if(l.backspace||l.delete){Le(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(a&&!l.ctrl&&!l.meta&&a.length===1){Le(i=>i&&{...i,query:i.query+a,cursor:0});return}return}if(pe){if(l.escape){Ue(null);return}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(Math.max(0,Nt.length-1),i.cursor+1)});return}if(l.return){let i=Nt[pe.cursor];if(i){Ue(null),re(i.uuid),$e.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},Ye(i.name),bn(i.uuid),Ge.current=[];let h=$n(e,i.uuid);for(let p of h)u(p);u({kind:"note",tone:"ok",text:h.length?`Resumed "${i.name}" \u2014 restored ${h.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(l.backspace||l.delete){Ue(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(a&&!l.ctrl&&!l.meta&&a.length===1){Ue(i=>i&&{...i,query:i.query+a,cursor:0});return}return}if(l.tab&&!I&&ge){b(ge),he(null),Tt.current++;return}if(!I&&it.length>0&&a&&/^[1-9]$/.test(a)){let i=it[Number(a)-1];if(i){b(i);return}}if(!Yn(a,l)){if(Un){if(l.upArrow){qe(i=>Math.max(0,i-1));return}if(l.downArrow){qe(i=>Math.min(pt.length-1,i+1));return}if(l.tab){b("/"+(pt[at]?.name??"")+" "),qe(0);return}if(l.return){let i=pt[at];if(i){let h=I.trim().slice(1).split(/\s+/).slice(1).join(" ");if(ar(i.usage)&&!h){b("/"+i.name+" "),qe(0);return}Ot("/"+i.name+(h?" "+h:""));return}}}else{if(l.upArrow){if(I!==""&&ze===null){Ut(-1);return}let i=yo.current;if(!i.length)return;let h=ze===null?i.length-1:Math.max(0,ze-1);jt(h),b(i[h]??"");return}if(l.downArrow){if(I!==""&&ze===null){Ut(1);return}let i=yo.current;if(ze===null)return;let h=ze+1;h>=i.length?(jt(null),b("")):(jt(h),b(i[h]??""));return}}if(l.return){Ot();return}if(l.backspace||l.delete){x();return}if(l.escape){b(""),qe(0),he(null),V([]);return}a&&!l.ctrl&&!l.meta&&zn(a)}}}),_e(()=>{if(_||G)return;let a=Oe.current.shift();a!==void 0&&($o([...Oe.current]),Ot(a))},[_,G,Ot]),U(J,{flexDirection:"column",width:We,children:[vo!==null&&U(J,{marginTop:1,flexDirection:"column",children:[vo.truncated&&S(v,{dimColor:!0,children:"\u2026"}),S(v,{children:vo.text})]}),_&&(In?S(su,{p:In}):S(nu,{startTime:Be.current,chars:si})),S(J,{borderStyle:"round",borderColor:On.prod?"yellow":B,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:I?Gn.map((a,l)=>{let i=k.text.slice(a.start,a.end),h=l===fo(Gn,k.pos),p=Math.min(k.pos,a.end)-a.start;return U(v,{children:[S(v,{color:B,children:l===0?"> ":" "}),h?U(Sn,{children:[i.slice(0,p),S(ho,{ch:i[p]??" "}),i.slice(p+1)]}):i||" "]},`${l}-${a.start}`)}):U(v,{children:[S(v,{color:B,children:"> "}),ge&&!_?U(Sn,{children:[S(ho,{ch:ge[0],dim:!0}),S(v,{color:"gray",children:ge.slice(1)}),S(v,{dimColor:!0,children:" (tab)"})]}):bo.isSetup||!ri?U(Sn,{children:[S(ho,{ch:bo.text[0],dim:!0}),S(v,{color:"gray",children:bo.text.slice(1)})]}):S(ho,{ch:" "})]})}),Dn.length>0&&S(J,{flexDirection:"column",paddingX:1,children:Dn.map((a,l)=>S(v,{color:"gray",children:`\u29D7 queued: ${a}`},`${l}-${a.slice(0,24)}`))}),Ne?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Select model"}),S(v,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),ye.map((a,l)=>U(v,{color:l===Ne.cursor?B:void 0,children:[l===Ne.cursor?"\u276F ":" ",`${l+1}. ${a.label}${l===Ne.current?" \u2714":""}`.padEnd(16),S(v,{color:"gray",children:a.desc})]},a.label)),S(v,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):xe?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Switch connection profile"}),xe.rows.map((a,l)=>U(v,{color:l===xe.cursor?B:void 0,children:[l===xe.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===xe.current?" \u2714":""}`.padEnd(20),S(v,{color:"gray",children:`${a.env} \xB7 ${a.who??"not signed in"}`}),a.prod?S(v,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},a.name)),S(v,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Re?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Pick your Document360 environment"}),Re.rows.map((a,l)=>U(v,{color:l===Re.cursor?B:void 0,children:[l===Re.cursor?"\u276F ":" ",`${l+1}. ${a.name}`.padEnd(16),S(v,{color:"gray",children:a.apiUrl})]},a.name)),S(v,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):oe?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Switch workspace"}),S(v,{dimColor:!0,children:`environment ${oe.environment} \xB7 project ${oe.projectId.slice(0,8)}\u2026`}),oe.rows.map((a,l)=>U(v,{color:l===oe.cursor?B:void 0,children:[l===oe.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===oe.current?" \u2714":""}`.padEnd(30),S(v,{color:"gray",children:a.type??""})]},a.id)),S(v,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):ue?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Choose project"}),S(v,{dimColor:!0,children:`environment ${ue.environment}`}),ue.rows.map((a,l)=>U(v,{color:l===ue.cursor?B:void 0,children:[l===ue.cursor?"\u276F ":" ",`${l+1}. ${a.name}${l===ue.current?" \u2714":""}`.padEnd(30),S(v,{color:"gray",children:a.sub??""})]},a.id)),S(v,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ne?(()=>{let l=Math.min(Math.max(0,ne.cursor-Math.floor(7)),Math.max(0,ne.rows.length-14)),i=ne.rows.slice(l,l+14),h=ne.rows.filter(p=>p.checked).length;return U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:`Which folders back the user docs? (${h} selected of ${ne.rows.length})`}),l>0?S(v,{dimColor:!0,children:` \u2191 ${l} more`}):null,i.map((p,m)=>{let y=l+m;return U(v,{color:y===ne.cursor?B:void 0,children:[y===ne.cursor?"\u276F ":" ",p.checked?"\u25C9 ":"\u25CB ",p.path.padEnd(Math.min(48,We-34)),S(v,{color:"gray",children:Zt(p)})]},p.path)}),l+14<ne.rows.length?S(v,{dimColor:!0,children:` \u2193 ${ne.rows.length-l-14} more`}):null,S(v,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():be?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:"Publish which article?"}),be.rows.map((a,l)=>U(v,{color:l===be.cursor?B:void 0,children:[l===be.cursor?"\u276F ":" ",`${l+1}. ${a.path}`.padEnd(Math.min(56,We-30)),S(v,{color:"gray",children:a.label})]},a.path)),S(v,{dimColor:!0,children:"enter publish (draft) \xB7 esc cancel"})]}):de?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:`Preview article${de.query?` \u2014 filter: ${de.query}`:" (type to filter)"}`}),_t.length===0?S(v,{color:"gray",children:"no articles match"}):_t.map((a,l)=>U(v,{color:l===de.cursor?B:void 0,children:[l===de.cursor?"\u276F ":" ",a]},a)),S(v,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):pe?U(J,{flexDirection:"column",paddingX:1,children:[S(v,{color:B,bold:!0,children:`Resume session${pe.query?` \u2014 filter: ${pe.query}`:" (type to filter)"}`}),Nt.length===0?S(v,{color:"gray",children:"no sessions match"}):Nt.map((a,l)=>U(v,{color:l===pe.cursor?B:void 0,children:[l===pe.cursor?"\u276F ":" ",a.name.slice(0,28).padEnd(30),S(v,{color:l===pe.cursor?B:"gray",children:a.firstPrompt.slice(0,Math.max(10,We-40))})]},a.uuid)),S(v,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):Un?S(J,{flexDirection:"column",children:pt.map((a,l)=>U(v,{color:l===at?B:void 0,children:[l===at?"\u276F ":" ",a.usage.padEnd(22)," ",S(v,{color:l===at?B:"gray",children:a.name==="model"&&xo?`${a.desc} (currently ${xo})`:a.desc})]},a.name))}):!I&&it.length>0?U(J,{flexDirection:"column",paddingX:1,children:[it.map((a,l)=>U(v,{children:[S(v,{color:B,children:l+1})," ",a.slice(0,Math.max(20,We-5))]},a)),S(v,{dimColor:!0,children:`press 1-${it.length} to fill the command \xB7 esc dismiss`})]}):S(J,{paddingX:1,children:U(v,{color:"gray",children:[On.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${xo??"model n/a"}${t.kind==="api"?Nn>0?` \xB7 ${fe(Nn)}`:"":_n>0?` \xB7 ${rt(_n)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}H();import{jsx as au}from"react/jsx-runtime";async function ti(e=process.cwd(),t="auto",o,n="0.0.0"){let r=lu(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${R("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${R("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=iu(au(ei,{cwd:e,auth:r,profileName:o,version:n}));await s(),process.stdout.write(`
|
|
96
|
+
`),process.exit(0)}var pu=uu(import.meta.url),oi=pu("../package.json"),Se=new cu;function Rn(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Se.command("login").description("Sign in to Document360 (browser OAuth; project chosen during login)").option("--profile <name>","Connection profile (defaults to the repo's defaultProfile)").option("--env <name>",!1).option("--manual","No local listener \u2014 paste the redirect URL instead (SSH/locked-down setups)").action(async e=>{Rn(e),await Bt({profile:e.profile,manual:e.manual})});Se.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Rn(e),await nr({profile:e.profile})});Se.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{Rn(e),await or({profile:e.profile})});var jn=Se.command("profile").description("Manage connection profiles for the current repo");jn.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>qt(process.cwd()));jn.command("use <name>").description("Set the default profile for this repo").action(e=>zt(process.cwd(),e));jn.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Gt(process.cwd(),e));var ni=Se.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");ni.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>tt(process.cwd(),e.profile));ni.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)});Se.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>sr());Se.command("doctor").description("Health-check: node, Claude auth, Document360 login, profile/workspace, category map, API reachability").action(async()=>{let{renderDoctorChecks:e,runDoctorChecks:t}=await Promise.resolve().then(()=>(oo(),ts)),o=await t(process.cwd());for(let n of e(o))console.log(n);process.exitCode=o.some(n=>n.level==="fail")?1:0});Se.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(oi.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(du.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 ir(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 Ss(e.cwd,e.auth,e.profile):await ti(e.cwd,e.auth,e.profile,oi.version)});Se.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|
package/package.json
CHANGED