document360-writer 0.5.16 → 0.5.17
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 +33 -33
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -178,8 +178,8 @@ Anything only a human knows that would help document this product. For example:
|
|
|
178
178
|
`)}function qo(e){try{let t=Cc(ei(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function oi(e,t){let o={...qo(e)??{},emittedVersion:ne,emittedAt:t};Gt(ei(e),`${JSON.stringify(o,null,2)}
|
|
179
179
|
`)}function Yt(e){try{return Pc(Zs(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=qo(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ne?"stale":"current",completedVersion:n}}function In(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ne};try{if(!An(En(e)))return n;let o=qo(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ne>r&&(jn(Ho(e)),Gt(En(e),ti()),oi(e,t),n.guideRefreshed=!0),ne>s&&(Sc(e).some(p=>p.kind==="request"&&p.subject.startsWith(Qs))||(Rc(e,{id:`onb${ne}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Qs}${ne})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${ne}${s?` (you last completed v${s})`:""}.`,"Re-run the hand-off so the docs agent and this repo stay in step \u2014 run this prompt here:","",ot()].join(`
|
|
180
180
|
`)}),n.notifiedBuilder=!0))}catch{}return n}function Nn(e){if(!An(En(e)))return[];let t=Ee(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${ne}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,Tt,ot(),Tt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Bo(){return['document360-writer (its "docs agent") has been removed from this repository. Please undo its dev\u2192docs',"hand-off setup and restore this repo to how it was before \u2014 in order:","","1. In this repo's agent-memory file (CLAUDE.md, or AGENTS.md \u2014 whichever it edited), REMOVE the",' "Documentation hand-off" section that was added (the rule about dropping hint files in'," `.d360-writer/hints/`, keeping `.d360-writer/architecture/` current, and checking"," `.d360-writer/messages/`). Leave everything else in that file untouched.","2. The `.d360-writer/` folder is already deleted on disk. If it was committed, remove it from version"," control too \u2014 `git rm -r --cached .d360-writer` (if it still resolves) \u2014 and commit the deletions.","3. Do NOT recreate any of those files or follow the hand-off protocol anymore.","","That's it \u2014 this repo is back to its pre-docs-agent state."].join(`
|
|
181
|
-
`)}function _n(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Tt,Bo(),Tt]}function St(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ne}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Tt,ot(),Tt,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var Tt,ne,Qs,rt=Oo(()=>{"use strict";Tt="-".repeat(64),ne=5;Qs="Re-run dev\u2194docs onboarding (protocol v"});var aa={};Ul(aa,{doctorCommand:()=>en,renderDoctorChecks:()=>ia,runDoctorChecks:()=>sa});import{existsSync as na}from"node:fs";import{d360GetAll as sd,getAccessToken as id,isExpired as Ar,loadProfileMap as ad,loadTokens as ld,packageSkillsDir as oa,projectConfigPath as cd,readProjectConfig as ud,DEFAULT_DOCS_DIR as dd,resolveActiveProfile as pd,classifyClaudeAuth as fd,CLAUDE_CODE_SETUP_HINT as ra,resolveModelSetting as md,probeModel as hd,devHintsGuidePath as gd}from"document360-engine";async function sa(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let o=fd();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${ra}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ra});let r=md(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let y=await hd(e,r.model??void 0);y.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(y.latencyMs/1e3).toFixed(1)}s`}):y.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${y.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let s=ud(e);if(!s)return t.push({level:"fail",label:`No ${cd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??dd).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 p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.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 f;try{f=pd(e),t.push({level:"ok",label:`Profile: ${f.name} (${f.connection.name})${f.production?" \u26A0 PRODUCTION":""}`})}catch(y){return t.push({level:"fail",label:`Profile config: ${y.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let x=ld(f.name);x?Ar(x)&&!x.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ar(x)?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(x.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${f.name})`}),t.push(f.project.workspaceId?{level:"ok",label:`Workspace: ${f.project.workspaceName??f.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let k=ad(e,f.name);k?k.projectId&&f.project.projectId&&k.projectId!==f.project.projectId?t.push({level:"fail",label:`Category map projectId (${k.projectId}) \u2260 profile projectId (${f.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(k.articles).length} articles, ${Object.keys(k.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${f.name}" (created on first /publish)`}),t.push(na(oa())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${oa()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ee(e);if((na(gd(e))||A.status!=="unset")&&(A.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ne})`}):A.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${A.completedVersion}, current is v${ne}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}):t.push({level:"warn",label:"Dev hand-off: guide emitted but the builder hasn't completed it",fix:"Have the repo's coding agent run the /devhints prompt (sets up the two-way channel)"})),x&&(!Ar(x)||x.refreshToken)){let y={profile:f.name,connection:f.connection};try{await id(y);let T=await sd(y,"/v3/projects");t.push({level:"ok",label:`API reachable (${f.connection.apiUrl}) \u2014 ${T.length} project(s) visible`})}catch(T){t.push({level:"fail",label:`API call failed: ${T.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function ia(e){let t=[""];for(let r of e){let s=r.level==="ok"?I("\u2713"):r.level==="warn"?U("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${O(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?I(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function en(e,t){console.log(m("Running checks\u2026"));for(let n of ia(await sa(t.cwd)))console.log(n);return{kind:"continue"}}var Gn=Oo(()=>{"use strict";rt();W()});import{Command as Mf}from"commander";import{createRequire as Lf}from"node:module";import{AUTH_MODES as Wf}from"document360-engine";import{input as ec}from"@inquirer/prompts";import{loginPkce as tc,refreshTokens as nc,toStoredTokens as Ms,clearTokens as oc,decodeJwtClaims as Us,isExpired as rc,loadTokens as sc,saveTokens as Ls,resolveActiveProfile as Cn,setProfileProject as ic,readProjectConfig as ac}from"document360-engine";W();import{select as Fl}from"@inquirer/prompts";import{resolveActiveProfile as Hl,setProfileProject as ql,resolveProjectId as Bl,listWorkspaces as Gl}from"document360-engine";async function qt(e,t){let n=Hl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Bl(o);return{workspaces:await Gl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Es=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Uo(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function vn(e,t,n,o,r){ql(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Is(e,t,n){let o;try{o=await qt(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Uo(o.workspaces,t);return r?(vn(e,o.profile,o.projectId,r.id,r.name),console.log(I(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Pt(e,t){let n;try{n=await qt(e,t)}catch(x){console.log(v(`Could not list workspaces: ${x.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let x of o)console.log(` ${x.id===c?O("\u25CF"):" "} ${Es(x)} ${m(x.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Fl({message:"Select the Document360 workspace for this repo:",choices:o.map(x=>({name:`${Es(x)}${x.id===c?" (current)":""}`,value:x.id}))}),f=o.find(x=>x.id===p);vn(e,s,r,p,f?.name),console.log(I(`\u2713 Workspace set to "${f?.name??p}" for profile "${s}".`))}W();import{select as Yl}from"@inquirer/prompts";import{resolveActiveProfile as Vl,setProfileProject as zl,listProjects as Kl}from"document360-engine";async function nt(e,t){let n=Vl(e,t),o={profile:n.name,connection:n.connection};return{projects:await Kl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ns=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function _s(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function Mo(e,t,n,o){zl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Os(e,t){let n;try{n=await nt(e,t)}catch(f){console.log(v(`Could not list projects: ${f.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let f of o)console.log(` ${f.id===s?O("\u25CF"):" "} ${Ns(f)} ${m(f.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let c=await Yl({message:"Select the Document360 project for this repo:",choices:o.map(f=>({name:`${Ns(f)}${f.id===s?" (current)":""}`,value:f.id}))}),p=o.find(f=>f.id===c);Mo(e,r,c,p?.name),console.log(I(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import Xl from"picocolors";function Jl(e=process.env){return e.FORCE_HYPERLINK==="0"||!Xl.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 Ql(e,t=e,n){return Jl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Zl=/https?:\/\/[^\s\x1b]+/g;function Bt(e,t){return e.replace(Zl,n=>Ql(n,n,t))}function Ws(e){return{...Us(e.idToken)??{},...Us(e.accessToken)??{}}}function Pn(e){let t=Ws(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Tn(e){let t=Cn(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await tc(n,{manual:e.manual,promptForRedirect:s=>ec({message:s})},s=>console.log(Bt(s))),r=Ms(t.name,o);if(Ls(r),await Lo(r,t.name,s=>console.log(m(s))),console.log(""),console.log(I(`\u2713 Logged in to "${t.name}" as ${Pn(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{ac(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Pt(process.cwd(),t.name))}catch{}}async function Lo(e,t,n){let r=Ws(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Cn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await nt(process.cwd(),t);c=p.find(f=>f.id===r)?.name}catch{}ic(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Fs(e){let t=Cn(process.cwd(),e.profile),n=t.connection,o=sc(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Pn(o)}`),rc(o))if(o.refreshToken)try{let r=Ms(t.name,await nc(n,o.refreshToken));Ls(r),console.log(I(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(U("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function Hs(e){let t=Cn(process.cwd(),e.profile);oc(t.name)?console.log(I(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as qs,writeProjectConfig as lc,resolveActiveProfile as cc,loadTokens as uc,isExpired as dc}from"document360-engine";function Rn(e){let t=qs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?O("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=uc(n),f=p?dc(p)&&!p.refreshToken?U("expired"):m("logged in"):m("not logged in");console.log(`${r}${O(n)} \u2192 ${c}${s} [${f}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Sn(e,t){let n=qs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,lc(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(I(`\u2713 Default profile is now "${t}"${o}`))}function Dn(e,t){try{let n=cc(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?U(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}W();import{existsSync as pc,readdirSync as fc,statSync as Bs}from"node:fs";import{join as Gs}from"node:path";import{apiLogDir as mc}from"document360-engine";function Ys(){let e=mc();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!pc(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=fc(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Bs(Gs(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Bs(Gs(e,r)).size/1024).toFixed(1);console.log(` ${v(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as hc,resolveAuth as gc,findByName as wc,slugify as yc,touchSession as kc,upsertSession as bc,resolveActiveProfile as xc}from"document360-engine";async function Vs(e,t,n,o,r,s){let c=gc(n);c.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let p=null;try{p=xc(e,r)}catch(y){console.error(v(`Document360 profile error: ${y.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let f;if(o){let y=wc(e,o);y||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),f=y.uuid,console.error(m(`Resuming "${y.name}"`))}let x=hc({cwd:e,resume:f,profileName:r,allowProdWrites:s===!0}),k=f??null,A=1;for await(let y of x.send(t))switch(y.type){case"session":if(!k){k=y.sessionId;let T=new Date().toISOString();bc({uuid:k,name:yc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write(y.delta);break;case"tool":console.error(oe(` \u2699 ${y.name}`));break;case"result":A=y.ok?0:1,console.error(m(`(${y.inputTokens}\u2192${y.outputTokens} tokens`+(y.costUsd>0?`, $${y.costUsd<.01?y.costUsd.toFixed(4):y.costUsd.toFixed(2)}`:"")+")")),y.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${y.message}`)),process.exit(1)}k&&kc(k),process.stdout.write(`
|
|
182
|
-
`),process.exit(A)}import{createInterface as
|
|
181
|
+
`)}function _n(){return['\u{1F9F9} One leftover: your builder still has the "Documentation hand-off" rule in its CLAUDE.md / AGENTS.md'," (reset only clears d360-writer's own .d360-writer/ folder \u2014 never your repo's files)."," To restore it, paste this prompt into your repo's coding agent (Claude Code / Codex / Cursor):",Tt,Bo(),Tt]}function St(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${ne}.`," Have them run the prompt below again \u2014 it now sets up two-way messages + on-demand docs.",""]:[],"\u2713 Wrote .d360-writer/DEV-HINTS-GUIDE.md + the .d360-writer/architecture/ (brief), .d360-writer/hints/, and .d360-writer/messages/ inboxes.","","\u{1F4CB} Copy this one prompt and run it in your repo's coding agent (Claude Code / Codex / Cursor):",Tt,ot(),Tt,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var Tt,ne,Qs,rt=Oo(()=>{"use strict";Tt="-".repeat(64),ne=5;Qs="Re-run dev\u2194docs onboarding (protocol v"});var aa={};Ul(aa,{doctorCommand:()=>en,renderDoctorChecks:()=>ia,runDoctorChecks:()=>sa});import{existsSync as na}from"node:fs";import{d360GetAll as sd,getAccessToken as id,isExpired as Ar,loadProfileMap as ad,loadTokens as ld,packageSkillsDir as oa,projectConfigPath as cd,readProjectConfig as ud,DEFAULT_DOCS_DIR as dd,fetchManifestSummary as pd,resolveActiveProfile as fd,classifyClaudeAuth as md,CLAUDE_CODE_SETUP_HINT as ra,resolveModelSetting as hd,probeModel as gd,devHintsGuidePath as wd}from"document360-engine";async function sa(e){let t=[],n=Number(process.versions.node.split(".")[0]);t.push(n>=20?{level:"ok",label:`Node ${process.versions.node}`}:{level:"fail",label:`Node ${process.versions.node} \u2014 20+ required`,fix:"Install Node 20 or later (nodejs.org)"});let o=md();o.state==="ready"?t.push({level:"ok",label:`Claude auth: ${o.kind==="api"?"API key":"subscription (Claude Code login found)"}`}):o.state==="maybe"?t.push({level:"warn",label:"Claude: no Claude Code login found (may be in the macOS Keychain)",fix:`If a docs turn ends with no output, sign in to Claude Code. ${ra}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ra});let r=hd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let y=await gd(e,r.model??void 0);y.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(y.latencyMs/1e3).toFixed(1)}s`}):y.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${y.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let s=ud(e);if(!s)return t.push({level:"fail",label:`No ${cd(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??dd).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 p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.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 f;try{f=fd(e),t.push({level:"ok",label:`Profile: ${f.name} (${f.connection.name})${f.production?" \u26A0 PRODUCTION":""}`})}catch(y){return t.push({level:"fail",label:`Profile config: ${y.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let x=ld(f.name);x?Ar(x)&&!x.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Ar(x)?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(x.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${f.name})`}),t.push(f.project.workspaceId?{level:"ok",label:`Workspace: ${f.project.workspaceName??f.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let k=ad(e,f.name);k?k.projectId&&f.project.projectId&&k.projectId!==f.project.projectId?t.push({level:"fail",label:`Category map projectId (${k.projectId}) \u2260 profile projectId (${f.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(k.articles).length} articles, ${Object.keys(k.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${f.name}" (created on first /publish)`}),t.push(na(oa())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${oa()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ee(e);if((na(wd(e))||A.status!=="unset")&&(A.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ne})`}):A.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${A.completedVersion}, current is v${ne}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}):t.push({level:"warn",label:"Dev hand-off: guide emitted but the builder hasn't completed it",fix:"Have the repo's coding agent run the /devhints prompt (sets up the two-way channel)"})),x&&(!Ar(x)||x.refreshToken)){let y={profile:f.name,connection:f.connection};try{await id(y);let C=await sd(y,"/v3/projects");t.push({level:"ok",label:`API reachable (${f.connection.apiUrl}) \u2014 ${C.length} project(s) visible`})}catch(C){t.push({level:"fail",label:`API call failed: ${C.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}let T=k?.projectId??f.project.projectId;if(T&&f.project.workspaceId)try{let C=await pd(y,T,f.project.workspaceId);t.push(C?{level:"ok",label:`Workspace sync manifest: available on ${f.connection.name} (${C.languages?.length??0} language${(C.languages?.length??0)===1?"":"s"})`}:{level:"warn",label:`Workspace sync manifest: not live on ${f.connection.name} yet`,fix:"No action needed \u2014 sync uses the per-article path until the manifest ships on this environment"})}catch(C){t.push({level:"warn",label:`Workspace sync manifest: probe failed (${C.message.slice(0,80)})`})}}return t}function ia(e){let t=[""];for(let r of e){let s=r.level==="ok"?I("\u2713"):r.level==="warn"?U("\u26A0"):v("\u2717");t.push(` ${s} ${r.label}${r.detail?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${O(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?I(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):v(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function en(e,t){console.log(m("Running checks\u2026"));for(let n of ia(await sa(t.cwd)))console.log(n);return{kind:"continue"}}var Gn=Oo(()=>{"use strict";rt();W()});import{Command as Lf}from"commander";import{createRequire as Wf}from"node:module";import{AUTH_MODES as Ff}from"document360-engine";import{input as ec}from"@inquirer/prompts";import{loginPkce as tc,refreshTokens as nc,toStoredTokens as Ms,clearTokens as oc,decodeJwtClaims as Us,isExpired as rc,loadTokens as sc,saveTokens as Ls,resolveActiveProfile as Cn,setProfileProject as ic,readProjectConfig as ac}from"document360-engine";W();import{select as Fl}from"@inquirer/prompts";import{resolveActiveProfile as Hl,setProfileProject as ql,resolveProjectId as Bl,listWorkspaces as Gl}from"document360-engine";async function qt(e,t){let n=Hl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Bl(o);return{workspaces:await Gl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Es=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function Uo(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function vn(e,t,n,o,r){ql(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function Is(e,t,n){let o;try{o=await qt(e,n)}catch(s){return console.log(v(`Could not list workspaces: ${s.message}`)),1}let r=Uo(o.workspaces,t);return r?(vn(e,o.profile,o.projectId,r.id,r.name),console.log(I(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log(v(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function Pt(e,t){let n;try{n=await qt(e,t)}catch(x){console.log(v(`Could not list workspaces: ${x.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let x of o)console.log(` ${x.id===c?O("\u25CF"):" "} ${Es(x)} ${m(x.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Fl({message:"Select the Document360 workspace for this repo:",choices:o.map(x=>({name:`${Es(x)}${x.id===c?" (current)":""}`,value:x.id}))}),f=o.find(x=>x.id===p);vn(e,s,r,p,f?.name),console.log(I(`\u2713 Workspace set to "${f?.name??p}" for profile "${s}".`))}W();import{select as Yl}from"@inquirer/prompts";import{resolveActiveProfile as Vl,setProfileProject as zl,listProjects as Kl}from"document360-engine";async function nt(e,t){let n=Vl(e,t),o={profile:n.name,connection:n.connection};return{projects:await Kl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var Ns=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function _s(e,t){let n=t.toLowerCase();return e.find(o=>(o.name??"").toLowerCase()===n)??e.find(o=>(o.name??"").toLowerCase().startsWith(n))??e.find(o=>o.id.startsWith(t))}function Mo(e,t,n,o){zl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Os(e,t){let n;try{n=await nt(e,t)}catch(f){console.log(v(`Could not list projects: ${f.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let f of o)console.log(` ${f.id===s?O("\u25CF"):" "} ${Ns(f)} ${m(f.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let c=await Yl({message:"Select the Document360 project for this repo:",choices:o.map(f=>({name:`${Ns(f)}${f.id===s?" (current)":""}`,value:f.id}))}),p=o.find(f=>f.id===c);Mo(e,r,c,p?.name),console.log(I(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import Xl from"picocolors";function Jl(e=process.env){return e.FORCE_HYPERLINK==="0"||!Xl.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 Ql(e,t=e,n){return Jl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Zl=/https?:\/\/[^\s\x1b]+/g;function Bt(e,t){return e.replace(Zl,n=>Ql(n,n,t))}function Ws(e){return{...Us(e.idToken)??{},...Us(e.accessToken)??{}}}function Pn(e){let t=Ws(e),n=t.email??t.preferred_username??t.sub??"unknown",o=t.doc360_project_id?` \xB7 project ${t.doc360_project_id}`:"";return`${n}${o}`}async function Tn(e){let t=Cn(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await tc(n,{manual:e.manual,promptForRedirect:s=>ec({message:s})},s=>console.log(Bt(s))),r=Ms(t.name,o);if(Ls(r),await Lo(r,t.name,s=>console.log(m(s))),console.log(""),console.log(I(`\u2713 Logged in to "${t.name}" as ${Pn(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{ac(process.cwd())?.profiles?.[t.name]&&(console.log(""),await Pt(process.cwd(),t.name))}catch{}}async function Lo(e,t,n){let r=Ws(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(Cn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await nt(process.cwd(),t);c=p.find(f=>f.id===r)?.name}catch{}ic(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Fs(e){let t=Cn(process.cwd(),e.profile),n=t.connection,o=sc(t.name);if(!o){console.log(v(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${Pn(o)}`),rc(o))if(o.refreshToken)try{let r=Ms(t.name,await nc(n,o.refreshToken));Ls(r),console.log(I(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(U("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function Hs(e){let t=Cn(process.cwd(),e.profile);oc(t.name)?console.log(I(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as qs,writeProjectConfig as lc,resolveActiveProfile as cc,loadTokens as uc,isExpired as dc}from"document360-engine";function Rn(e){let t=qs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log(v("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?O("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=uc(n),f=p?dc(p)&&!p.refreshToken?U("expired"):m("logged in"):m("not logged in");console.log(`${r}${O(n)} \u2192 ${c}${s} [${f}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Sn(e,t){let n=qs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log(v(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,lc(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(I(`\u2713 Default profile is now "${t}"${o}`))}function Dn(e,t){try{let n=cc(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?U(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log(v(n.message)),process.exitCode=1}}W();import{existsSync as pc,readdirSync as fc,statSync as Bs}from"node:fs";import{join as Gs}from"node:path";import{apiLogDir as mc}from"document360-engine";function Ys(){let e=mc();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!pc(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=fc(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Bs(Gs(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Bs(Gs(e,r)).size/1024).toFixed(1);console.log(` ${v(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as hc,resolveAuth as gc,findByName as wc,slugify as yc,touchSession as kc,upsertSession as bc,resolveActiveProfile as xc}from"document360-engine";async function Vs(e,t,n,o,r,s){let c=gc(n);c.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let p=null;try{p=xc(e,r)}catch(y){console.error(v(`Document360 profile error: ${y.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error(v("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(m(" --yes given \u2014 proceeding against production.")));let f;if(o){let y=wc(e,o);y||(console.error(v(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),f=y.uuid,console.error(m(`Resuming "${y.name}"`))}let x=hc({cwd:e,resume:f,profileName:r,allowProdWrites:s===!0}),k=f??null,A=1;for await(let y of x.send(t))switch(y.type){case"session":if(!k){k=y.sessionId;let T=new Date().toISOString();bc({uuid:k,name:yc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:T,updatedAt:T})}break;case"text":process.stdout.write(y.delta);break;case"tool":console.error(oe(` \u2699 ${y.name}`));break;case"result":A=y.ok?0:1,console.error(m(`(${y.inputTokens}\u2192${y.outputTokens} tokens`+(y.costUsd>0?`, $${y.costUsd<.01?y.costUsd.toFixed(4):y.costUsd.toFixed(2)}`:"")+")")),y.ok||console.error(v("agent finished with an error result"));break;case"error":console.error(""),console.error(v(`agent error: ${y.message}`)),process.exit(1)}k&&kc(k),process.stdout.write(`
|
|
182
|
+
`),process.exit(A)}import{createInterface as ip}from"node:readline/promises";import{createSession as Vr,resolveAuth as ap,getSession as lp,setTitle as cp,slugify as up,touchSession as Ea,upsertSession as dp,generateTitle as pp,resolveActiveProfile as Ia,resolveModelSetting as fp,readProjectConfig as mp,decodeJwtClaims as ja,isExpired as hp,loadTokens as gp}from"document360-engine";var xe=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"text",s:"Agentic Mode is designed for applications built using AI coding agents. D360-Writer works alongside your coding agent to continuously create and maintain your user documentation. Think of it as hiring a Technical Writer dedicated to your project."},{t:"gap"},{t:"text",s:"As your coding agent ships new features, it leaves documentation notes for D360-Writer. All you need to do is run the documentation loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, read the notes left by your coding agent, update the documentation, and publish the changes."},{t:"dim",s:" (or run /catch-up to review drafts first, then /publish when you're ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what has changed and identify missing documentation, without writing or publishing anything."},{t:"cmd",name:"/sync",s:"Pull changes made directly in the Document360 portal and reconcile any documentation drift."},{t:"cmd",name:"/inbox",s:"Review and act on messages left by your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/sync",s:"Pull portal edits; reconcile drift."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function $c(e){switch(e.t){case"head":return e.s;case"text":return` ${e.s}`;case"dim":return` ${e.s}`;case"sub":return e.s;case"good":return` ${e.s}`;case"step":return` ${e.n}. ${e.s}`;case"cmd":return` ${e.name.padEnd(20)} ${e.s}`;case"gap":return""}}function zs(){let e=["document360-writer \u2014 help",""];for(let t of xe){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push($c(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Wo(){console.log("");for(let e of zs())console.log(e);return console.log(""),console.log("Reporting a problem? Run `d360-writer logs` for the API log files."),console.log(""),{kind:"continue"}}W();import{getSession as vc}from"document360-engine";async function Ks(e,t){let n=t.currentUuid(),o=n?vc(n):void 0;return console.log(o?m(`
|
|
183
183
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
184
184
|
`):m(`
|
|
185
185
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
@@ -236,44 +236,44 @@ Articles:
|
|
|
236
236
|
`+e.paths.map(n=>`- ${n}`).join(`
|
|
237
237
|
`)}function yr(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${pe(r)}\u2013${pe(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function kr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,S)=>C+o(S),0),p=r.reduce((C,S)=>C+o(S),0),f=e.reduce((C,S)=>C+S.costUsd,0),x=e.reduce((C,S)=>C+S.outputTokens,0),k=n==="api"?`${pe(f)} total`:He(x),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,y=C=>`${C} article${C===1?"":"s"}`,T=[];if(s.length===0)T.push(`Wrote ${y(c)} (${A}) successfully \xB7 ${k}.`),T.push("Next \u2014 push them to Document360:"),T.push("/publish --all"),T.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{T.push(`Wrote ${p}/${y(c)} (${A}) \xB7 ${k}.`),T.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)T.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return T}function br(e,t,n){let o=(Li(e)?.docsDir??Ou).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Fu(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Hu(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};let c=hr(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Wi(e,t){if(!Li(t.cwd))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=_u(t.cwd);if(n.length===0)return console.log(v("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:c}=mr(e),{docsDir:p,targets:f,reason:x}=br(t.cwd,n,{scope:o,path:r});if(f.length===0)return console.log(x?U(x):U("Nothing to write.")),{kind:"continue"};let k=Nu(f),A=fr(c),{model:y,forced:T}=Uu(t.cwd,"standard");if(s&&!!!r){let S=Iu({files:gr(t.cwd,n,f),op:"write",model:y});o&&console.log(m(`Scope: ${o} (${f.length} pending).`));for(let N of yr(k,S,A))console.log(N);return console.log(m(`Model: ${y}${T?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${f.length} article${f.length===1?"":"s"} across ${k.length} partition${k.length===1?"":"s"} (\u2264${A} agents at once) on ${y}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let S of Mu({cwd:t.cwd,partitions:k,promptFor:N=>wr(N,p),concurrency:A,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:y}))if(S.type==="partition_status")S.status==="running"?console.log(m(` \u25B8 ${S.label} \u2014 writing\u2026`)):S.status==="done"?console.log(I(` \u2713 ${S.label}`)):console.log(v(` \u2717 ${S.label}`));else if(S.type==="run_done"){console.log("");let N=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let H of kr(S.results,k,N))console.log(S.ok?I(H):U(H))}}catch(S){console.log(v(`Write run failed: ${S.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as qu,readdirSync as Fi,statSync as Hi}from"node:fs";import{join as qi}from"node:path";import{inputDir as Bu,readProjectConfig as Gu}from"document360-engine";var Bi=/\.(md|markdown|pdf|txt)$/i;function xr(e){let t=Bu(e);if(!qu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Fi(t)){let s=qi(t,r),c=!1;try{c=Hi(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=Yu(s);p>0&&n.push({name:r,docCount:p})}else Bi.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function Yu(e){let t=0;for(let n of Fi(e))try{Hi(qi(e,n)).isFile()&&Bi.test(n)&&t++}catch{}return t}function $r(e,t){let n=t.trim().toLowerCase();return n?e.find(o=>o.name.toLowerCase()===n)?.name??e.find(o=>o.name.toLowerCase().startsWith(n))?.name??e.find(o=>o.name.toLowerCase().includes(n))?.name??null:null}function qn(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
238
238
|
`)}var vr="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Gi(e,t){let n=t?.cwd??process.cwd();if(!Gu(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=xr(n);if(o.length===0&&r===0)return console.log(m(vr)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let f of o)console.log(` ${f.name} ${m(`(${f.docCount} doc${f.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:qn(p),display:p?`/draft ${p}`:"/draft"}}let c=$r(o,s);return{kind:"forward-to-agent",prompt:qn(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Vu,readProjectConfig as zu}from"document360-engine";function Cr(e){try{return Vu(e).filter(t=>t.kind==="request").length}catch{return 0}}function Pr(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function Tr(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
|
|
239
|
-
`)}var Rr="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function Yi(e,t){let n=t?.cwd??process.cwd();if(!zu(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Pr(e);if(!r&&Cr(n)===0)return console.log(m(Rr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Tr(r,o),display:s}}W();import{search as Ku}from"@inquirer/prompts";import{findByName as Xu,getSession as Ju,listSessions as Qu,relativeTime as zi}from"document360-engine";async function Ki(e,t){let n=Qu(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Xu(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),Vi(n),{kind:"continue"})}if(!process.stdin.isTTY)return Vi(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Ku({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${zi(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Ju(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Vi(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${m(zi(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Zu}from"document360-engine";function Sr(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 Xi(e,t){let n=Sr(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Zu(o,n)?console.log(I(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(console.log(v("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Ji,readProjectConfig as ed,writeProjectConfig as td}from"document360-engine";W();function Dr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=ed(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return Ji().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},td(o,e),null):`Unknown environment "${r}". Known: ${Ji().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Qi(e,t){let n=e[0];if(!n)return Rn(t.cwd),{kind:"continue"};if(n==="add"){let o=Dr(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(I(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return Sn(t.cwd,n),Dn(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as nd}from"@inquirer/prompts";import{readProjectConfig as od,readUserConfig as Zi,resolveModelSetting as jr,writeUserConfig as ea}from"document360-engine";var Re=[{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 Bn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Re.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function rd(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 Zt(e,t){let n=()=>{let s=jr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Zi();return s.defaultModel?(delete s.defaultModel,ea(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${jr(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}ea({...Zi(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=od(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function ta(e,t){let n=e[0]?.trim();if(!n){let c=jr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${O(c.model??"Claude Code default")}`),console.log(m(` source: ${rd(c)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Bn(c),f;try{f=await t.withPausedInput(()=>nd({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Re[p].value,choices:Re.map((y,T)=>({name:`${y.label}${T===p?" \u2714":""}`,value:y.value,description:y.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:x,changed:k,effective:A}=Zt(t.cwd,f??"default");for(let y of x)console.log(y.startsWith("\u26A0")?U(y):y.startsWith("\u2713")?I(y):m(y));return k&&await t.setModel(A),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Zt(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?U(c):c.startsWith("\u2713")?I(c):m(c));return r&&await t.setModel(s),{kind:"continue"}}Gn();async function la(e,t){return await t.withPausedInput(()=>Pt(t.cwd)),{kind:"clear"}}async function ca(e,t){return await t.withPausedInput(()=>Os(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as
|
|
239
|
+
`)}var Rr="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function Yi(e,t){let n=t?.cwd??process.cwd();if(!zu(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=Pr(e);if(!r&&Cr(n)===0)return console.log(m(Rr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:Tr(r,o),display:s}}W();import{search as Ku}from"@inquirer/prompts";import{findByName as Xu,getSession as Ju,listSessions as Qu,relativeTime as zi}from"document360-engine";async function Ki(e,t){let n=Qu(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Xu(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log(v(`No session matches "${o}".`)),Vi(n),{kind:"continue"})}if(!process.stdin.isTTY)return Vi(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Ku({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${zi(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=Ju(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Vi(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${m(zi(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Zu}from"document360-engine";function Sr(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 Xi(e,t){let n=Sr(e.join(" "));if(!n)return console.log(v("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Zu(o,n)?console.log(I(`\u2713 Session renamed to "${n}"`)):console.log(v("Could not find the current session record.")),{kind:"continue"}):(console.log(v("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as Ji,readProjectConfig as ed,writeProjectConfig as td}from"document360-engine";W();function Dr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=ed(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return Ji().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},td(o,e),null):`Unknown environment "${r}". Known: ${Ji().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Qi(e,t){let n=e[0];if(!n)return Rn(t.cwd),{kind:"continue"};if(n==="add"){let o=Dr(t.cwd,e[1],e[2]);return o?(console.log(v(o)),{kind:"continue"}):(console.log(I(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return Sn(t.cwd,n),Dn(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as nd}from"@inquirer/prompts";import{readProjectConfig as od,readUserConfig as Zi,resolveModelSetting as jr,writeUserConfig as ea}from"document360-engine";var Re=[{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 Bn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Re.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function rd(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 Zt(e,t){let n=()=>{let s=jr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Zi();return s.defaultModel?(delete s.defaultModel,ea(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${jr(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}ea({...Zi(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=od(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function ta(e,t){let n=e[0]?.trim();if(!n){let c=jr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${O(c.model??"Claude Code default")}`),console.log(m(` source: ${rd(c)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Bn(c),f;try{f=await t.withPausedInput(()=>nd({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Re[p].value,choices:Re.map((y,T)=>({name:`${y.label}${T===p?" \u2714":""}`,value:y.value,description:y.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:x,changed:k,effective:A}=Zt(t.cwd,f??"default");for(let y of x)console.log(y.startsWith("\u26A0")?U(y):y.startsWith("\u2713")?I(y):m(y));return k&&await t.setModel(A),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Zt(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?U(c):c.startsWith("\u2713")?I(c):m(c));return r&&await t.setModel(s),{kind:"continue"}}Gn();async function la(e,t){return await t.withPausedInput(()=>Pt(t.cwd)),{kind:"clear"}}async function ca(e,t){return await t.withPausedInput(()=>Os(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as yd}from"document360-engine";async function ua(e,t){let n=!1;try{n=yd(t.cwd).production}catch{}return n?(console.log(U("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var da=async(e,t)=>{try{await t.withPausedInput(()=>Tn({}))}catch(n){console.log(v(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as kd,clearTokens as bd,clearProfileProject as xd}from"document360-engine";async function pa(e,t){let n;try{n=kd(t.cwd,t.profileName).name}catch(r){return console.log(v(r.message)),{kind:"continue"}}let o=bd(n);return xd(t.cwd,n),console.log(o?I(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as fa}from"node:fs";import{isAbsolute as $d,join as vd,resolve as Cd}from"node:path";import{readProjectConfig as Pd,screenshotPlaceholderIds as Td,DEFAULT_CAPTURE_DIR as Rd,DEFAULT_OUTPUT_DIR as Sd}from"document360-engine";var ma=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Er(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?ma(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:ma(o),setup:t}:{mode:"single",id:o}}function Ir(e,t){let n=Pd(e),o=n?.captureDir??Rd,r=n?.outputDir??Sd,s=(c,p)=>$d(c)?vd(c,p):Cd(e,c,p);return Td(e,{scope:t}).map(({id:c,file:p})=>{let f=fa(s(r,`${c}.png`))?"captured":fa(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:f}})}var Dd={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},jd={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Nr(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let c of e.filter(p=>p.file===s))r.push(` ${Dd[c.state]} ${c.id.padEnd(34)} ${jd[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function ha(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(`
|
|
240
240
|
`),"","For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
|
|
241
241
|
`)}async function Yn(e,t){let n=Er(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of Nr(Ir(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), 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>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
|
|
242
242
|
`),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"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.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
|
|
243
|
-
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as
|
|
244
|
-
`),display:"/capture-setup"}}var ga="-".repeat(64);function _r(e){let t=
|
|
245
|
-
`)}async function wa(e,t){let n=t?.cwd??process.cwd();return
|
|
246
|
-
`)}async function ya(e,t){let n=t?.cwd??process.cwd();if(!
|
|
247
|
-
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function
|
|
248
|
-
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=
|
|
249
|
-
`);return{lines:s.slice(0,t).map(c=>he(c,Yr)),hidden:Math.max(0,s.length-t)}}function Qn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Zn(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function eo(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var
|
|
250
|
-
|
|
251
|
-
`),console.log(`${I("\u25CF")} ${Te(s.title)}${s.arg!==null?oe(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=st(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(oe(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(m(` \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=Jn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?v:oe;c.lines.forEach((f,x)=>console.log(p((x===0?" \u23BF ":" ")+f))),c.hidden>0&&console.log(m(` \u2026 +${c.hidden} lines`)),e.isError||
|
|
252
|
-
`),console.log(m(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Ea(t.uuid),t.titleFired
|
|
253
|
-
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){
|
|
254
|
-
`)}import{existsSync as
|
|
255
|
-
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var
|
|
256
|
-
`)){let c=s.trim().replace(
|
|
257
|
-
`)}function Qa(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:
|
|
243
|
+
`),s=n.mode==="scope"?`/screenshot ${n.scope}`:`/screenshot${e[0]?` ${e[0]}`:""}`;return{kind:"forward-to-agent",prompt:r,display:s}}import{existsSync as Ad,readFileSync as Ed}from"node:fs";import{isAbsolute as Id,join as Nd,resolve as _d}from"node:path";import{readProjectConfig as Od,DEFAULT_CAPTURE_DIR as Ud}from"document360-engine";async function tn(){return{kind:"forward-to-agent",prompt:["Run the capture-setup-checklist skill.","","Scan every <!-- SCREENSHOT --> block across the docs tree (the configured docsDir), 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(`
|
|
244
|
+
`),display:"/capture-setup"}}var ga="-".repeat(64);function _r(e){let t=Ud;try{let k=Od(e);k?.captureDir&&(t=k.captureDir.replace(/\\/g,"/").replace(/\/+$/,""))}catch{}let n=Id(t)?Nd(t,"CAPTURE-TESTID-REQUESTS.json"):_d(e,t,"CAPTURE-TESTID-REQUESTS.json");if(!Ad(n))return null;let o;try{let k=JSON.parse(Ed(n,"utf8").replace(/^/,""));o=Array.isArray(k?.requests)?k.requests:[]}catch{return null}if(o.length===0)return null;let r=new Set(o.map(k=>k.file).filter(Boolean)).size,s=o.length,c=`${s} data-testid attribute${s===1?"":"s"}`,p=`${r} source file${r===1?"":"s"}`,f=`${t}/CAPTURE-TESTID-REQUESTS.md`,x=`${t}/CAPTURE-TESTID-REQUESTS.json`;return[`\u{1F4CB} Developer hand-off \u2014 ${c} requested across ${p}.`,"\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.","",ga,`Read ${f} and ${x}. 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.",ga]}rt();W();import{listOpenForDocs as Md,readProjectConfig as Ld}from"document360-engine";function Or(e){try{return Md(e).length}catch{return 0}}function Ur(){return["Process the two-way message inbox from the source repo's coding agent (the builder).","","1. Call d360_inbox to list the OPEN messages addressed to you.","2. For each message, act by its kind:",' \u2022 request ("document the X we shipped") \u2192 treat it as a session hand-off: run the document-handoff'," skill \u2014 read what changed, ground it in the cited sources + the architecture brief, then decide and"," apply the RIGHT doc action (new section, new article, update existing, or retire). No fixed shape."," \u2022 answer (a reply to a question you asked; `re` = your question id) \u2192 fold the fact into the affected"," article(s), and into `.d360-writer/architecture/` if it is durable product knowledge.","3. After acting on a message, mark it resolved: edit its file in `.d360-writer/messages/` and set the"," frontmatter `status: done` (add `done_at` with the current UTC time). Never delete the file.","4. Drafts only \u2014 do not publish unless explicitly asked. End with a one-line summary of what you did per"," message (and, for any request you could not fully ground, what you still need)."].join(`
|
|
245
|
+
`)}async function wa(e,t){let n=t?.cwd??process.cwd();return Ld(n)?Or(n)===0?(console.log(m("Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)")),{kind:"continue"}):{kind:"forward-to-agent",prompt:Ur(),display:"/inbox"}:(console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"})}W();import{listOpenHints as Wd,listOpenForDocs as Fd,readProjectConfig as Hd}from"document360-engine";function At(e){let t=0,n=0,o=0;try{t=Wd(e).length}catch{}try{let r=Fd(e);n=r.filter(s=>s.kind==="request").length,o=r.filter(s=>s.kind==="answer").length}catch{}return{hints:t,requests:n,answers:o}}function Et(e){let t=[];return e.hints&&t.push(`${e.hints} hint${e.hints===1?"":"s"}`),e.requests&&t.push(`${e.requests} request${e.requests===1?"":"s"}`),e.answers&&t.push(`${e.answers} answer${e.answers===1?"":"s"}`),t.length?t.join(", "):null}function Mr(e){return{publish:e.includes("--publish")}}function Lr({publish:e}){let t=["Catch the documentation up: process ALL the pending work the builder has queued, end to end.","","1. Trust the inventory first \u2014 call d360_sync_status. If anything is in conflict or remote-ahead, STOP and tell me what to resolve (never write over a copy you can't trust).","2. Gather the pending work: d360_pending_hints (the builder's per-change hints) AND d360_inbox (open requests + answers).","3. Decide the right doc actions across all of it: gap-analysis for the hints (verify each against its sources + commit), document-handoff for each request (no fixed shape \u2014 new section / new article / update / retire), and fold any answers into the affected article(s) + the architecture brief.","4. If that means writing more than one article, call d360_estimate_cost and show me the count + cost band first (the bulk gate), then proceed.","5. Write/update the articles as drafts, grounded in the cited sources.","6. Close the loop: stamp consumed hints, and mark handled messages status: done with resulting_articles.","7. Push the drafts to Document360.","8. Cross-link second pass: any article you wrote that links to ANOTHER article in this same batch had that inline link degrade to plain text (its target had no live URL yet when the source was written). Now that every target exists, re-update the affected articles so those inline links resolve to live URLs \u2014 only the ones that had such forward references need it. (The structured Related Articles sidebars are already two-way linked; this is just inline body links.)"];return t.push(e?"9. Then publish the new/updated articles live (publish-to-d360 skill), respecting the production write-guard.":"Leave everything as DRAFTS for review \u2014 do not publish live (run /publish when you want them live)."),t.push("","End with a one-line-per-item summary of what you wrote/updated, and anything you couldn't ground (plus the d360_ask_builder question you left for it)."),t.join(`
|
|
246
|
+
`)}async function ya(e,t){let n=t?.cwd??process.cwd();if(!Hd(n))return console.log(v("No d360-writer config here. Run /init first.")),{kind:"continue"};let o=Ie(n,t?.profileName);if(!o.ok)return console.log(v(o.reason)),{kind:"continue"};let{publish:r}=Mr(e),s=Et(At(n));return console.log(m(s?`Catching up on ${s} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026")),{kind:"forward-to-agent",prompt:Lr({publish:r}),display:`/catch-up${r?" --publish":""}`}}W();import{spawn as qd}from"node:child_process";var it="document360-writer",Vn=`npm i -g ${it}@latest`;async function zn(){let e=process.platform==="win32";return new Promise(t=>{try{let n=qd(`npm i -g ${it}@latest`,{stdio:"ignore",shell:!0,detached:!e,windowsHide:!0});n.on("error",o=>t({ok:!1,output:String(o)})),n.on("close",o=>t({ok:o===0,output:""})),e||n.unref()}catch(n){t({ok:!1,output:String(n)})}})}async function ka(){return console.log(m(`Updating ${it}\u2026`)),(await zn()).ok?console.log(I("\u2713 Updated. Exit (/exit) and relaunch d360-writer to apply.")):console.log(v(`Update failed \u2014 run manually: ${Vn}`)),{kind:"continue"}}W();rt();import{existsSync as Wr,rmSync as Bd}from"node:fs";import{basename as ba,resolve as Fr}from"node:path";import{execFileSync as Gd}from"node:child_process";import{input as Yd}from"@inquirer/prompts";import{readProjectConfig as Vd,devHintsGuidePath as zd}from"document360-engine";var Kd=[".d360-writer.json",".d360-writer","d360-category-map.json",".d360-capture.json",".d360-capture-cache"],Xd=new Set([".d360-writer.json","d360-category-map.json",".d360-capture.json",".d360-capture-cache"]),Kn=e=>(e??"").replace(/\\/g,"/").replace(/\/+$/,""),xa=e=>e===".d360-writer"||e.startsWith(".d360-writer/");function $a(e){let t=Kn(e);return t===""||t.startsWith("..")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:xa(t)?!0:Xd.has(t)}function Hr(e){let t=null;try{t=Vd(e)}catch{t=null}let n=new Set(Kd);for(let o of[Kn(t?.docsDir),Kn(t?.captureDir),Kn(t?.outputDir)])o&&xa(o)&&n.add(o);return[...n].filter(o=>$a(o)&&Wr(Fr(e,o)))}function qr(e,t){let n=[],o=[];for(let r of t){if(!$a(r)){o.push({path:r,error:"refused \u2014 outside .d360-writer/ (protected)"});continue}try{Bd(Fr(e,r),{recursive:!0,force:!0}),n.push(r)}catch(s){o.push({path:r,error:s.message})}}return{removed:n,failed:o}}function va(e,t){try{return Gd("git",["status","--porcelain","--",t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
247
|
+
`).filter(o=>o.trim()&&/\.md\s*$/.test(o)).length}catch{return 0}}function Jd(e){return va(e,".d360-writer/hints")}function Qd(e){return va(e,".d360-writer/messages")}function Br(e,t){if(t.length===0)return["Nothing to reset \u2014 no d360-writer files found in this repo."];let n=Jd(e),o=Qd(e),r=Wr(Fr(e,"user-docs"));return["\u26A0 This permanently DELETES everything d360-writer created here:",...t.map(s=>` \u2022 ${s}`),"",...n>0?[`\u26A0 ${n} doc hint(s) under .d360-writer/hints/ are not committed \u2014 commit them first or they're gone.`]:[],...o>0?[`\u26A0 ${o} message(s) under .d360-writer/messages/ are not committed \u2014 commit them first or they're gone.`]:[],...r?["Protected: root user-docs/ is NOT touched (only .d360-writer/ is removed)."]:[],"Undo = git: committed files are restorable; untracked ones (most screenshots) are gone.",`To confirm, type the repo name: ${ba(e)}`]}async function Ca(e,t){let n=Hr(t.cwd);for(let f of Br(t.cwd,n))console.log(n.length===0?m(f):f);if(n.length===0)return{kind:"continue"};let o=ba(t.cwd);if((await t.withPausedInput(()=>Yd({message:`Type "${o}" to delete (anything else cancels):`}).catch(()=>""))).trim()!==o)return console.log(U("Reset cancelled \u2014 nothing deleted.")),{kind:"continue"};let s=Wr(zd(t.cwd)),{removed:c,failed:p}=qr(t.cwd,n);console.log(I(`\u2713 Reset complete \u2014 removed ${c.length} item${c.length===1?"":"s"}. The repo is back to its original state.`));for(let f of p)console.log(v(` \u2717 ${f.path}: ${f.error}`));if(s){for(let f of _n())console.log(f);console.log(m("(Select and copy the prompt above to paste into your coding agent.)"))}return console.log(m("Set up d360-writer again with /init (then /login, /workspace).")),{kind:"continue"}}var Pa={help:Wo,"?":Wo,clear:Ks,exit:Fo,quit:Fo,init:pi,mcp:Un,publish:Ti,audit:Qt,scope:Si,sync:_i,convert:Oi,write:Wi,draft:Gi,document:Yi,resume:Ki,rename:Xi,profile:Qi,model:ta,doctor:en,workspace:la,project:ca,"allow-prod":ua,login:da,logout:pa,screenshot:Yn,"capture-setup":tn,devhints:ni,inbox:wa,"catch-up":ya,update:ka,reset:Ca};function Ta(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.slice(1).split(/\s+/),o=(n[0]??"").toLowerCase();return o?{name:o,args:n.slice(1)}:null}rt();W();var Zd={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"},Sa=160,Yr=200,Da=40;function he(e,t){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:n.slice(0,t-1)+"\u2026"}function Ra(e){let t=Object.entries(e).filter(([,o])=>o!=null&&o!=="");if(t.length===0)return null;let n=t.slice(0,4).map(([o,r])=>`${o}: ${he(typeof r=="string"?r:JSON.stringify(r),Da)}`);return t.length>4&&n.push("\u2026"),he(n.join(", "),Sa)}var qe=e=>typeof e=="string"&&e?e:null,Gr=e=>typeof e=="string"&&e.length>=8?e.slice(0,8):null;function ep(e){let t=qe(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-2],r=o.replace(/^\d+[-_.]/,"").split(/[-_]/).filter(Boolean);return r.length===0?o:r.map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function tp(e,t){let n=(o,r)=>({title:`Document360: ${o}`,sep:" ",arg:r});switch(e){case"d360_create_article":{let o=qe(t.title);if(!o)return null;let r=ep(t.local_path);return n("Create article",`"${he(o,60)}"${r?` in ${r}`:""}`)}case"d360_update_article":{let o=qe(t.title),r=Gr(t.article_id);return n("Update article",o?`"${he(o,60)}"`:r?`id ${r}\u2026`:null)}case"d360_fork_article":return n("Fork article (new draft)",Gr(t.article_id)?`id ${Gr(t.article_id)}\u2026`:null);case"d360_publish_article":{let o=t.version_number;return n("Publish article LIVE",typeof o=="number"?`v${o}`:null)}case"d360_unpublish_article":return n("Unpublish article",null);case"d360_create_category":return n("Create category",qe(t.name)?`"${he(qe(t.name),60)}"`:null);case"d360_upload_drive_file":{let o=qe(t.file_path);return n("Upload image",o?he(o.replace(/\\/g,"/").split("/").pop()??o,60):null)}case"d360_sync_status":return n("Check sync status",null);default:return null}}function Xn(e,t){if(e==="ToolSearch")return null;if(e.startsWith("mcp__")){let[,r="",...s]=e.split("__"),c=s.join("__");if(r==="document360"){let x=tp(c,t);if(x)return x}let p=c.replace(/^d360_/,"").replace(/_/g," ");return{title:`${r==="document360"?"Document360":r.charAt(0).toUpperCase()+r.slice(1)}: ${p}`,sep:" ",arg:Ra(t)}}let n=Zd[e],o=n?t[n]:void 0;return typeof o=="string"&&o?{title:e,sep:"",arg:he(o,Sa)}:{title:e,sep:"",arg:Ra(t)}}function np(e){if(e===null||typeof e!="object")return typeof e=="string"?e:null;let t=e;for(let n of["name","title","slug","id"])if(typeof t[n]=="string"&&t[n])return t[n];return null}function op(e){if(!/^[[{]/.test(e))return null;let t;try{t=JSON.parse(e)}catch{return null}if(Array.isArray(t)){let n=t.map(np).filter(r=>r!==null),o=`${t.length} item${t.length===1?"":"s"}`;return n.length===0?[o]:[o,...n.map(r=>he(r,Yr))]}if(t!==null&&typeof t=="object"){let n=Object.entries(t).filter(([,o])=>o!==null&&(typeof o=="string"||typeof o=="number"||typeof o=="boolean")).slice(0,6).map(([o,r])=>`${o}: ${he(String(r),Da)}`);return n.length>0?[he(n.join(" \xB7 "),Yr)]:null}return null}function rp(e){let t=qe(e)?.replace(/\\/g,"/");if(!t)return null;let n=t.split("/").filter(Boolean);return n.length>1?n.slice(1).join("/"):t}function sp(e,t,n){switch(e){case"d360_create_article":{let o=rp(t?.local_path);return[`\u2713 draft created${o?` \xB7 ${o}`:""}`]}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 o=qe(t?.name);return[`\u2713 category created${o?` \xB7 "${o}"`:""}`]}case"d360_upload_drive_file":{let o=n.match(/https?:\/\/\S+/);return[`\u2713 uploaded${o?` \xB7 ${he(o[0],120)}`:""}`]}default:return null}}function Jn(e,t=4,n,o){let r=e.replace(/\r\n/g,`
|
|
248
|
+
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=sp(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=op(r)??r.split(`
|
|
249
|
+
`);return{lines:s.slice(0,t).map(c=>he(c,Yr)),hidden:Math.max(0,s.length-t)}}function Qn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Zn(e,t){if(typeof e.article_id=="string"&&e.article_id)return e.article_id;try{let n=JSON.parse(t),r=(Array.isArray(n)?n[0]:n)?.id;return typeof r=="string"&&r?r:null}catch{return null}}function eo(e){try{let t=JSON.parse(e),o=(Array.isArray(t)?t[0]:t)?.url;return typeof o=="string"&&/^https?:\/\//.test(o)?o:null}catch{return null}}var wp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function yp(e,t,n,o){if(wp.test(e))try{let r=Ia(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Zn(t,n),p=eo(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`)),c&&s&&console.log(O(` \u2B95 Preview: ${Qn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Na(e=process.cwd(),t="auto",n){let o=ap(t);o.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),kp(e,n),o.kind==="subscription"&&(o.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=Vr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=ip({input:process.stdin,output:process.stdout}),f=[],x=null,k=!1;p.on("line",T=>{if(x){let C=x;x=null,C(T)}else f.push(T)}),p.on("close",()=>{if(k=!0,x){let T=x;x=null,T(null)}});function A(){return f.length>0?Promise.resolve(f.shift()):k?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(T=>{x=T}))}let y={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Vr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async T=>s.setModel(T),withPausedInput:async T=>{p.pause();try{return await T()}finally{p.resume()}}};try{for(;;){let T=await A();if(T===null)break;let C=T.trim();if(C){if(C.startsWith("/")){let S=Ta(C);if(!S)continue;let N=Pa[S.name];if(!N){console.log(v(`Unknown command: /${S.name}`)),console.log(m("Type /help for the list."));continue}let H=await N(S.args,y);if(H.kind==="exit")break;if(H.kind==="clear"){y.restartAgent();continue}if(H.kind==="allow-prod"){r=!0,y.restartAgent(),console.log(I("\u2713 Production writes authorized for this session.")),console.log("");continue}if(H.kind==="resume"){s.close(),s=Vr({cwd:e,resume:H.uuid,profileName:n,allowProdWrites:r});let se=lp(H.uuid);c={uuid:H.uuid,firstPrompt:se?.firstPrompt??null,titleFired:!0},Ea(H.uuid),console.log(I(`\u2713 Resumed "${H.name}"`)),console.log("");continue}H.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=H.display??H.prompt),await Aa(s,H.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await Aa(s,C,o,c,e)}}}finally{s.close(),p.close()}}function kp(e,t){console.log(""),console.log(Ht("document360-writer")),console.log(m(` cwd: ${e}`));let n=fp(e);if(console.log(m(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(bp(e,t)),!mp(e))console.log(U(" First run: /init (scaffolds config + prints the builder hand-off prompt) \u2192 /login, then ask me to write the docs."));else{try{In(e);for(let o of Nn(e))console.log(U(` ${o}`))}catch{}try{let o=Et(At(e));o&&console.log(U(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function bp(e,t){try{let n=Ia(e,t),o=n.production?U(" \u26A0 PRODUCTION"):"",r=gp(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ja(r.idToken)??{},...ja(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return hp(r)&&!r.refreshToken?U(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function xp(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function $p(e,t,n){e.uuid=t;let o=new Date().toISOString();dp({uuid:t,name:up(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function vp(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||pp(o,t).then(r=>{r&&cp(n,r)}).catch(()=>{})}async function Aa(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Cp(c,o,r,n,s)}function Cp(e,t,n,o,r){switch(e.type){case"session":t.uuid||$p(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Xn(e.name,e.input);s&&(process.stdout.write(`
|
|
250
|
+
|
|
251
|
+
`),console.log(`${I("\u25CF")} ${Te(s.title)}${s.arg!==null?oe(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=st(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(oe(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(m(` \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=Jn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?v:oe;c.lines.forEach((f,x)=>console.log(p((x===0?" \u23BF ":" ")+f))),c.hidden>0&&console.log(m(` \u2026 +${c.hidden} lines`)),e.isError||yp(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
|
|
252
|
+
`),console.log(m(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Ea(t.uuid),t.titleFired||vp(t,n));break;case"error":console.error(""),console.error(v(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&xp();break}}import{render as _f}from"ink";import{resolveAuth as Of}from"document360-engine";import{useCallback as Y,useEffect as $e,useMemo as Zr,useRef as X,useState as F}from"react";import{Box as te,Text as R,useApp as Fp,useInput as Hp,useStdout as qp}from"ink";import{existsSync as Be,readFileSync as es,readdirSync as fo}from"node:fs";import{spawnSync as Bp}from"node:child_process";import{basename as rn,isAbsolute as Gp,join as lt}from"node:path";import{createSession as ll,classifyClaudeAuth as ss,CLAUDE_CODE_SETUP_HINT as Yp,loginPkce as Vp,toStoredTokens as zp,saveTokens as Kp,getAccessToken as Xp,resolveActiveProfile as ue,resolveProjectId as Jp,getArticle as Qp,decodeJwtClaims as It,isExpired as _e,loadTokens as Ge,clearTokens as Zp,clearProfileProject as ef,setTitle as tf,slugify as nf,touchSession as ts,upsertSession as of,generateTitle as cl,findByName as rf,listSessions as sf,renameSession as af,suggestNextAction as lf,readProjectConfig as J,writeProjectConfig as ul,resolveModelSetting as is,loadProfileMap as po,applyPull as cf,computeSyncStatus as ns,planPull as uf,establishBaselines as df,inventoryRepo as pf,knownEnvironments as ff,resolveEnvironment as mf,planPartitions as os,partitionEvenly as hf,screenshotPlaceholderIds as gf,trackedArticlePaths as wf,runPartitioned as lo,estimateBulkCost as dl,resolveModelForOperation as co,readDocsPlan as pl,checkForUpdate as yf,detectInstallKind as kf,isSelfUpdatable as bf,devHintsGuidePath as as,toolFeedbackPath as xf,reconcileToolFeedback as $f,DEFAULT_DOCS_DIR as sn,setProfileProject as vf,writeCrashLog as Cf}from"document360-engine";rt();import{spawn as _a}from"node:child_process";function Pp(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Tp(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?_a([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):_a(e,t,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>o(!1)),r.on("close",c=>o(c===0)),r.stdin?.on("error",()=>o(!1));let s=process.platform==="win32"?Buffer.from("\uFEFF"+n,"utf16le"):Buffer.from(n,"utf8");r.stdin?.end(s)}catch{o(!1)}})}async function Oa(e){for(let[t,n]of Pp())if(await Tp(t,n,e))return!0;return!1}var Rp=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function zr(e,t){if(t.closed)return e;let n=e.split(`
|
|
253
|
+
`),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Rp.test(s)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
254
|
+
`)}import{existsSync as Sp,mkdirSync as Dp,readFileSync as jp,writeFileSync as Ap}from"node:fs";import{join as Ua}from"node:path";import{writerDir as Ep}from"document360-engine";function Ma(e){return Ua(Ep(e),".sessions")}function La(e,t){return Ua(Ma(e),`${t}.json`)}function Wa(e,t,n){try{Dp(Ma(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Ap(La(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Kr(e,t){try{let n=La(e,t);if(!Sp(n))return[];let o=JSON.parse(jp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Ip=e=>`\x1B]0;${e}\x07`,Np=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function Fa(e){process.stdout.isTTY&&process.stdout.write(e)}function nn(e){Fa(Ip(e))}function to(e){Fa(Np(e))}var no=["\xB7 "," \xB7"],Xr="\u{1F7E3}";Gn();var oo=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer.json, and set up the builder hand-off (prints the one-paste prompt)",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:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",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:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --concurrency default 3)",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 [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all] [baseline]",desc:"Drift report local vs Document360; pull portal edits; baseline = set a sync base for not-yet-compared articles",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:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",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"}],Ha={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/sync":"check Document360 for changes made there","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function qa(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ha[n])return Ha[n];let o=oo.find(r=>r.name===t);return o?o.desc:""}function Ba(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return oo.filter(n=>n.name.startsWith(t))}function Ga(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as Ya,Text as re}from"ink";import{jsx as ie,jsxs as ro}from"react/jsx-runtime";function _p({row:e}){switch(e.t){case"head":return ie(re,{color:L,bold:!0,children:e.s});case"text":return ie(re,{children:e.s});case"dim":return ie(re,{dimColor:!0,children:e.s});case"sub":return ie(re,{bold:!0,dimColor:!0,children:e.s});case"good":return ie(re,{color:"green",children:e.s});case"step":return ro(re,{children:[ie(re,{color:L,children:`${e.n}. `}),e.s]});case"cmd":return ro(re,{children:[" ",ie(re,{color:L,children:e.name.padEnd(20)}),ie(re,{dimColor:!0,children:e.s})]});case"gap":return ie(re,{children:" "})}}function Va({tab:e,width:t}){let n=xe[e]??xe[0],o=6+xe.reduce((s,c)=>s+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return ro(Ya,{flexDirection:"column",paddingX:1,children:[ro(re,{children:[ie(re,{color:L,bold:!0,children:"Help "}),xe.map((s,c)=>c===e?ie(re,{color:L,bold:!0,inverse:!0,children:` ${s.label} `},s.key):ie(re,{dimColor:!0,children:` ${s.label} `},s.key))]}),ie(re,{color:L,children:r}),ie(Ya,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>ie(_p,{row:s},c))}),ie(re,{dimColor:!0,children:`
|
|
255
|
+
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Op=/^(?:\d+[.)]|[-*•])\s+/;function za(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
256
|
+
`)){let c=s.trim().replace(Op,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let f=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!f||!o.has(f[1].toLowerCase()))continue;let x=`/${f[1].toLowerCase()}${f[2]?` ${f[2]}`:""}`;if(r.includes(x)||r.push(x),r.length>=n)break}return r}W();function on(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ne(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Jr(e){return e.replace(/^[\w.-]+\//,"")}var so=16,Ka={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Qr(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Xa(e,t){let n=Qr(t);return e.some(r=>r.trim()===t.trim()||!!n&&Qr(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Qr(r)===n)):[]}var Up='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function Mp(e,t){switch(e){case"/write":return"finish the planned articles that aren\u2019t written yet";case"/catch-up":return"write up everything your builder flagged";case"/audit":return t?"also scan the code for other changes":"check the code for anything new or missing in the docs";case"/sync":return"check Document360 for changes made there";default:return""}}function at(e){return e===1?"":"s"}function Lp(e){switch(e){case"/write":return"it finishes the articles already planned";case"/catch-up":return"it clears everything your builder queued";case"/audit":return"it shows what the latest code changes touch";case"/sync":return"it reconciles anything changed on Document360";default:return"it\u2019s the most useful next step"}}function Ja(e,t,n){let o=[];e.pendingWrites>0&&o.push(` \u2022 ${e.pendingWrites} planned article${at(e.pendingWrites)} still unwritten`),e.pendingText&&o.push(` \u2022 your builder left ${e.pendingText}`),e.behind>0&&o.push(` \u2022 ${e.behind} code change${at(e.behind)} since your last docs check`);let r=o.length>0?["Welcome back \u2014 where your docs stand:",...o,`I\u2019d start with ${t[0]} \u2014 ${Lp(t[0])}.`]:[`Welcome back. Your ${e.tracked} tracked article${at(e.tracked)} are all in sync.`];return r.push("",...t.map((s,c)=>` ${c+1} ${s.padEnd(9)} ${Mp(s,n)}`),"Or just tell me what to write or update."),r.join(`
|
|
257
|
+
`)}function Qa(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:Up,ghost:"write the docs for this repo",title:t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:null,options:t?["/catch-up","/audit"]:["/audit"]};if(e.pendingWrites>0){let r=t?["/write","/catch-up"]:["/write","/audit"],s=`\u{1F4DD} ${e.pendingWrites} planned article${at(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:Ja(e,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${at(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/sync"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${at(e.behind)} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${e.tracked} article${at(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:Ja(e,n,t),title:o,options:n}}var Wp=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Za(e){return e.replace(/\r\n?/g,`
|
|
258
258
|
`)}function el(e){return e.includes(`
|
|
259
259
|
`)||e.length>200}function tl(e,t){let n=t.split(`
|
|
260
|
-
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function nl(e,t){return e.replace(
|
|
260
|
+
`).length;return`[Pasted text #${e} +${n} line${n===1?"":"s"}]`}function nl(e,t){return e.replace(Wp,n=>t.get(n)??n)}function ol(e){let t=e.match(/\[Pasted text #\d+ \+\d+ lines?\]$/);return t?e.slice(0,-t[0].length):null}function io(e,t){let n=Math.max(1,t),o=[],r=0;for(let s of e.split(`
|
|
261
261
|
`)){if(s.length===0)o.push({start:r,end:r});else for(let c=0;c<s.length;c+=n)o.push({start:r+c,end:r+Math.min(c+n,s.length)});r+=s.length+1}return o.length>0?o:[{start:0,end:0}]}function ao(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function rl(e,t,n){let o=ao(e,t),r=o+n;if(r<0||r>=e.length)return t;let s=Math.min(t,e[o].end)-e[o].start;return Math.min(e[r].start+s,e[r].end)}function sl(e,t,n){let o=e[ao(e,t)];return n==="start"?o.start:o.end}function il(e,t,n){let o=Math.max(1,n),r=e.split(`
|
|
262
262
|
`),s=0;for(let c=r.length-1;c>=0;c--){let p=r[c];if(s+=Math.max(1,Math.ceil(p.length/o)),s>=t){let f=s-t;return{text:[f>0?p.slice(f*o):p,...r.slice(c+1)].join(`
|
|
263
263
|
`),truncated:c>0||f>0}}}return{text:e,truncated:!1}}function al(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
264
|
-
`)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as rs,jsx as j,jsxs as B}from"react/jsx-runtime";var
|
|
264
|
+
`)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as rs,jsx as j,jsxs as B}from"react/jsx-runtime";var Pf={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},fl=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
265
265
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
266
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function
|
|
267
|
-
${
|
|
266
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Tf(e,t,n,o){let r=ss(n),s=r.state==="ready"?r.kind==="api"?"API key":"subscription":r.state==="maybe"?"subscription":"not signed in \u2014 run /doctor (needs Claude Code, not Claude Desktop)",c=is(e),p=J(e),f=(p?.docsDir??sn).replace(/\/+$/,""),x=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${f}/ + config`,k={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Pf[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:x};if(p===null)return k;try{let A=ue(e,o);k.profile=A.name,k.apiUrl=A.connection.apiUrl,k.prod=A.production,k.project=A.project.projectName??A.project.projectId??"(chosen at login)";let y=Ge(A.name);if(y){let T={...It(y.idToken)??{},...It(y.accessToken)??{}},C=T.email??T.preferred_username??"signed in";_e(y)?y.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(y.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function Rf(e,t){try{let n=ue(e,t),o=Ge(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...It(o.idToken)??{},...It(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return _e(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var ml=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],mo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Sf="Ask me to write or update an article\u2026";function uo({ch:e,dim:t}){let[n,o]=F(!0);return $e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),j(R,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Df=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function hl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var jf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gl(e){try{return fo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function wl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>gl(lt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&gl(lt(e,o)))}function yl(e,t){try{let n=J(e);if(!n)return!1;let o=ue(e,t),r=po(e,o.name);if(r&&Object.keys(r.articles).length>0)return!0;let s=lt(e,(n.docsDir??sn).replace(/\/+$/,""));return!!(Be(s)&&fo(s).length>0||Be(as(e)))}catch{return!1}}function Af({startTime:e,chars:t}){let[n,o]=F(0);$e(()=>{let f=setInterval(()=>o(x=>x+1),120);return()=>clearInterval(f)},[]);let r=mo[n%mo.length],s=ml[Math.floor(n/16)%ml.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[j(R,{color:L,children:` ${r} ${s}\u2026 `}),j(R,{color:"gray",children:`(${Kt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Ef=12e4;function If({p:e}){let[t,n]=F(0);$e(()=>{let N=setInterval(()=>n(H=>H+1),150);return()=>clearInterval(N)},[]);let o=mo[t%mo.length],r=Math.floor((Date.now()-e.startedAt)/1e3),s=Math.floor((Date.now()-e.lastAt)/1e3),c=Math.round(e.chars/4),p=Date.now()-e.lastAt>=Ef,f=e.verb??"Converting",x=e.unit??"article",k=e.rows.reduce((N,H)=>N+H.items,0),A=f.toLowerCase(),y=e.rows,T=0;if(y.length>so){let N=y.findIndex(se=>se.status==="active"||se.status==="pending"),H=Math.max(0,Math.min(N-2,y.length-so));T=y.slice(0,H).filter(se=>se.status==="done").length,y=y.slice(H,H+so)}let C=Math.min(40,Math.max(...y.map(N=>Jr(N.label).length),0)),S=N=>N==="failed"?"red":N==="active"?L:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[j(R,{color:L,children:` ${o} ${f} ${k} ${x}${k===1?"":"s"} `}),j(R,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Kt(r)} \xB7 esc to stop`})]}),T>0&&j(R,{dimColor:!0,children:` \u2714 +${T} done`}),y.map(N=>B(R,{color:S(N.status),dimColor:N.status==="done"||N.status==="pending",children:[` ${Ka[N.status]} ${Jr(N.label).padEnd(C)}`,N.status!=="pending"?` (${N.items} ${x}${N.items===1?"":"s"})`:"",N.status==="active"?` \u2190 ${A}\u2026`:""]},N.label)),p&&j(R,{color:"yellow",children:` \u26A0 no activity for ${Kt(s)} \u2014 press esc to stop if it's wedged`})]})}var Nf=10800*1e3;function kl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Fp(),[s,c]=F(n),[p,f]=F(null),[x,k]=F({text:"",pos:0}),A=x.text,y=Y(l=>{k(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),T=Y(l=>{k(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),C=Y(()=>{k(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=ol(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[S,N]=F(!1),[H,se]=F(!1),[ve,ae]=F(0),[Ce,le]=F(null),[Ye,G]=F([]),ct=X(0),[Tl,an]=F(!1),[Rl,ln]=F(!1),[ho,ds]=F(null),[Sl,ut]=F(0),Ve=X(0),[Nt,dt]=F(0),[pt,cn]=F(null),ps=X(new Map),Dl=X(0),ft=X([]),ge=X(null);ge.current===null&&(ge.current=ll({cwd:e,profileName:s,allowProdWrites:!1}));let Se=X({uuid:null,firstPrompt:null,titleFired:!1}),un=X(new Map),mt=X(!1),go=X([]),Ue=X([]),wo=X(null),[fs,ht]=F(null),[ze,Ke]=F(null),[De,gt]=F(null),[Me,wt]=F(null),[de,yt]=F(null),[we,Xe]=F(null),[Je,kt]=F(null),[ms,Qe]=F(null),[ye,Ze]=F(null),[fe,bt]=F(null),[hs,yo]=F([]),et=X([]),_t=X(!1),ke=X(null),[gs,Q]=F(null),dn=X(!1),pn=X(null),Ot=X(null),[be,tt]=F(null),[ko,Ut]=F(null),[ws,xt]=F(0),[ys,$t]=F(0),[jl,ks]=F(0),bo=Zr(()=>{try{return is(e).model??"auto"}catch{return null}},[e,jl]),{stdout:Pe}=qp(),[,Al]=F(0),bs=X(`${Pe.columns??80}x${Pe.rows??24}`),Le=Y(()=>Math.max(20,(Pe.columns??80)-1),[Pe]),d=Y(l=>{ft.current.push(l),console.log(Qo(l,Le()))},[Le]),[xo,$o]=F(null),vt=Y(l=>{$o(l),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),vo=X(!1),Co=Y(async()=>{try{if(vo.current||!bf(kf())||J(e)?.mode==="engineer")return;let l=await yf({pkg:it,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;vo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${it} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),ln(!0),(await zn().finally(()=>ln(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),G(a=>a.includes("/exit")?a:[...a,"/exit"]),ds(l.latest)):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Vn}`})}catch{}},[e,o,d]),Po=Y(l=>{let i=Ie(e,s);return i.ok?!0:(d({kind:"note",tone:"warn",text:i.reason}),Ot.current=l,G(["/login"]),!1)},[e,s,d]),[To,Ro]=F(null),Mt=X(!0),fn=X(0),Lt=X(0);$e(()=>{let l=setInterval(()=>{if(Mt.current){fn.current=0,Lt.current=0;return}if(!S)try{if(!Be(as(e)))return;if(Ee(e).status==="current"){Mt.current=!0,fn.current=0,Lt.current=0,d({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),$o(null),le("write the docs for this repo");return}fn.current+=1;let i=fn.current;if((i===4||i%15===0)&&Lt.current<3){Lt.current+=1;let a=Lt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Yt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${a}`:`\u23F3 Waiting for your builder to run the prompt \u2014 paste it into your coding agent; I'll pick up automatically when it's done.${a}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,S,d]),$e(()=>{let l=`d360-writer \xB7 ${fs??rn(e)}`;if(!S){to(0),nn(`${Xr} ${l}`);return}to(3);let i=0;nn(`${no[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%no.length,nn(`${no[i]} ${l}`)},400);return()=>clearInterval(a)},[S,e,fs]),$e(()=>()=>to(0),[]);let So=Y(l=>{try{let i=J(e);if(!i)return{kind:"idle"};let a=ue(e,s),g=Ge(a.name),u=!!g&&(!_e(g)||!!g.refreshToken),h=yl(e,s)||!wl(e,i.authoritativeSourceFiles),w=ss(t).state==="missing",b=po(e,a.name),P=b?Object.keys(b.articles).length:0,E=lt(e,(i.docsDir??sn).replace(/\/+$/,"")),K=!1;try{K=Be(E)&&fo(E).length>0}catch{}let Z=0;if(b?.lastAnalyzedCommit)try{let D=Bp("git",["rev-list","--count",`${b.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:1200});D.status===0&&(Z=parseInt((D.stdout||"").trim(),10)||0)}catch{}let _=0;try{let D=pl(e);if(D.length>0){let M=(i.docsDir??sn).replace(/\/+$/,"");_=hr(e,M,D.map(ee=>ee.path)).length}}catch{}let $={ready:u&&h&&!w,hasDocs:K,tracked:P,pendingText:Et(At(e)),behind:Z,pendingWrites:_,autoAudit:!!i.autoAudit,profileName:a.name,allowAutoAudit:l};return Qa($)}catch{return{kind:"idle"}}},[e,s,t]);$e(()=>{let l=performance.now(),i=[],a=(w,b)=>{let P=performance.now();try{return b()}finally{let E=Math.round(performance.now()-P);E>=80&&i.push(`${w}: ${E}ms`)}};d({kind:"banner",info:a("banner",()=>Tf(e,o,t,s))});let g=ss(t).state==="missing";if(g&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
267
|
+
${Yp}
|
|
268
268
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!J(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
269
|
-
${fl}`}),G(g?["/doctor","/init"]:["/init"]);return}g&&G(["/doctor"]);try{let w=ue(e,s),b=Ge(w.name);b&&_e(b)&&b.refreshToken?
|
|
270
|
-
`)}),vt(ot()),Mt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()
|
|
269
|
+
${fl}`}),G(g?["/doctor","/init"]:["/init"]);return}g&&G(["/doctor"]);try{let w=ue(e,s),b=Ge(w.name);b&&_e(b)&&b.refreshToken?Xp({profile:w.name,connection:w.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ae(P=>P+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),G(["/login"])}):(!b||_e(b))&&(d({kind:"note",tone:"warn",text:`Profile "${w.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"]))}catch{}try{let w=J(e),b=ue(e,s),P=Ge(b.name);w&&P&&!_e(P)&&wl(e,w.authoritativeSourceFiles)&&!yl(e,s)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),G(["/scope"]))}catch{}try{if(a("reconcile-devhints",()=>In(e)),Ee(e).status!=="current")if(Yt(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${ne}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let w=Nn(e);w.length&&(d({kind:"note",tone:"warn",text:w.join(`
|
|
270
|
+
`)}),vt(ot()),Mt.current=!1)}}catch{}try{let w=a("reconcile-feedback",()=>$f(e));w.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${w.archived} resolved item${w.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${w.open>0?`; ${w.open} still open`:""}.`})}catch{}let u=a("ready-decision",()=>So(!0));u.kind==="autoAudit"?(d({kind:"note",tone:"info",text:u.note}),Qt().then(w=>{w.kind==="forward-to-agent"&&w.prompt&&ce(w.prompt,{display:w.display,quietUser:!0})})):u.kind==="noDocs"?(d({kind:"note",tone:"info",text:u.note}),le(u.ghost),G(u.options),u.title&&Qe(u.title)):u.kind==="actions"&&(d({kind:"note",tone:"info",text:u.note}),G(u.options),Qe(u.title));let h=Math.round(performance.now()-l);h>=800&&Cf({kind:"slow-launch",level:"transport",message:`Launch blocked the UI for ${h}ms \u2014 input is frozen until this finishes (s-228 class).`,detail:`${i.length?i.join(`
|
|
271
271
|
`):"no single phase \u226580ms"}
|
|
272
|
-
cwd: ${e}`}),Co()},[]),$e(()=>{let l=setInterval(()=>{Co()},
|
|
272
|
+
cwd: ${e}`}),Co()},[]),$e(()=>{let l=setInterval(()=>{Co()},Nf);return()=>clearInterval(l)},[Co]),$e(()=>{if(S||Ye.length>0)return;let l=So(!1);(l.kind==="actions"||l.kind==="noDocs")&&(G(l.options),Qe(l.title??null))},[S,Ye,ve,So]),$e(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${Pe.columns??80}x${Pe.rows??24}`;g!==bs.current&&(bs.current=g,Al(u=>u+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+$i(ft.current,Le())+"\x1B[?2026l")},80))},400)};return Pe.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),Pe.off("resize",a)}},[Pe,Le]);let je=Math.max(20,(Pe.columns??80)-1),xs=Zr(()=>Rf(e,s),[e,s,ve]),Do=(()=>{if(Rl)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};if(ho!==null)return{text:`Update ready \u2014 run /exit, then relaunch to apply${ho?` v${ho}`:""}\u2026`,isSetup:!0};let l=J(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=lt(e,(l.docsDir??sn).replace(/\/+$/,"")),a=(()=>{try{return Be(i)&&fo(i).length>0}catch{return!1}})();try{let g=ue(e,s),u=Ge(g.name);if(!(!!u&&!(_e(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!a)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return a?{text:Sf,isSetup:!1}:xo?{text:"Press c to copy the prompt above, run it in your coding agent \u2014 then ask me to write the docs",isSetup:!1}:{text:"Ask me to write the docs for this repo",isSetup:!1}})(),Wt=Ba(A),$s=Wt.length>0&&!S,jo=p!==null?il(p,8,je):null,mn=ye?ye.paths.filter(l=>!ye.query||l.toLowerCase().includes(ye.query.toLowerCase())).slice(0,8):[],hn=be?be.sessions.filter(l=>{let i=be.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],me=Y((l,i)=>{ge.current?.close(),ge.current=ll({cwd:e,resume:l,profileName:i??s,allowProdWrites:mt.current}),l||(Se.current={uuid:null,firstPrompt:null,titleFired:!1},ht(null)),xt(0),$t(0)},[e,s]),vs=Y((l,i,a)=>{if(Df.test(l))try{let g=ue(e,s),u=typeof i.project_id=="string"&&i.project_id||g.project.projectId,h=Zn(i,a),w=[],b=eo(a);l.endsWith("publish_article")&&b&&w.push(`Live: ${b}`),h&&u&&w.push(`Preview: ${Qn(g.connection.portalUrl,u,h,g.project.languageCode??"en")}`),w.length>0&&d({kind:"link",lines:w})}catch{}},[e,s,d]),ce=Y(async(l,i)=>{an(!0),le(null),G([]),Qe(null),$o(null),Ro(null);let a=++ct.current;i?.quietUser||d({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Se.current;g.firstPrompt||(g.firstPrompt=i?.display??l),Ve.current=Date.now(),ut(0),N(!0),un.current.clear();let u="",h=!1,w=!1,b="",P={num:0,closed:!1,cueSeen:!1},E=null,K=()=>{E||(E=setTimeout(()=>{E=null,f(b.length>0?b:null)},60))},Z=()=>{E&&clearTimeout(E),E=null,f(null)},_=()=>{if(b.trim()){let $=zr(b.trimEnd(),P);d({kind:"assistant",text:$})}b="",Z()};try{for await(let $ of ge.current.send(l))if($.type==="session"){if(!g.uuid){g.uuid=$.sessionId;let D=new Date().toISOString(),M=nf(g.firstPrompt??"session");of({uuid:$.sessionId,name:M,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:D,updatedAt:D}),ht(M)}}else if($.type==="text"){b+=$.delta,u+=$.delta;let D=al(b);if(D>0){let M=b.slice(0,D).trimEnd();M&&d({kind:"assistant",text:zr(M,P)}),b=b.slice(D)}K(),ut(M=>M+$.delta.length)}else if($.type==="tool"){h=!0;let D=Xn($.name,$.input);D&&(_(),d({kind:"tool",title:D.title,sep:D.sep,arg:D.arg}),un.current.set($.id,{name:$.name,input:$.input}))}else if($.type==="article_diff"){let D=st($.oldContent,$.newContent,Le());D&&(_(),d({kind:"diff",added:D.added,removed:D.removed,lines:D.lines,hidden:D.hidden}))}else if($.type==="tool_result"){$.isError&&/run \/login|not logged in|session expired|rejected the token/i.test($.output)&&(dn.current=!0);let D=un.current.get($.id);if(D){un.current.delete($.id),_();let M=Jn($.output,4,$.isError?void 0:D.name,D.input);d({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:$.isError}),$.isError||vs(D.name,D.input,$.output)}}else if($.type==="result"){if(_(),xt(M=>M+$.outputTokens),$t(M=>M+$.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Ve.current)/1e3),tokens:$.outputTokens,costUsd:$.costUsd,ok:$.ok}),!w&&!h&&!u.trim()&&!_t.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),$.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let M=xf(e);if(Be(M)){let ee=es(M,"utf8").trim();ee&&(Ro(ee),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let D=$.ok?za(u,oo.map(M=>M.name)):[];if(D.length>0?G(D):$.ok&&u.trim()&&lf(l,u,e).then(M=>{M&&ct.current===a&&le(M)}).catch(()=>{}),g.uuid&&(ts(g.uuid),!g.titleFired)){g.titleFired=!0;let M=g.uuid,ee=g.firstPrompt;ee&&cl(ee,e).then(q=>{q&&(tf(M,q),ht(q))}).catch(()=>{})}}else $.type==="error"&&(_(),w=!0,$.kind==="auth"&&(dn.current=!0),d({kind:"note",text:`agent error: ${$.message}`,tone:"error"}))}finally{N(!1),Z(),ae($=>$+1),Se.current.uuid&&Wa(e,Se.current.uuid,ft.current),dn.current&&(dn.current=!1,pn.current=i?.display??l,G(["/login"])),_t.current&&(_t.current=!1,et.current.length>0&&(d({kind:"note",tone:"info",text:`(${et.current.length} queued message(s) discarded)`}),et.current=[],yo([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,vs,Le]),gn=Y(async l=>{let i=os(l),a=co(e,"standard");Ve.current=Date.now(),ut(0),N(!0);let g=new AbortController;ke.current=g,Q({verb:"Publishing",total:i.length,done:0,active:[],rows:on(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Xt} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let u of lo({cwd:e,partitions:i,promptFor:h=>Ln(h.paths),concurrency:Xt,profileName:s,allowProdWrites:mt.current,model:a.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?Q(h=>h&&{...h,active:[...h.active,u.label],rows:Ne(h.rows,u.label,"active"),lastAt:Date.now()}):Q(h=>h&&{...h,active:h.active.filter(w=>w!==u.label),done:h.done+1,rows:Ne(h.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")Q(h=>{if(!h)return h;let w={...h,lastAt:Date.now()};return u.event.type==="tool"?w.tools=h.tools+1:u.event.type==="text"&&(w.chars=h.chars+u.event.delta.length),w});else if(u.type==="run_done"){$t(P=>P+u.totalCostUsd),xt(P=>P+u.results.reduce((E,K)=>E+K.outputTokens,0));let h=u.aborted?"Stopped. ":"",w=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:h+or(u.results,i,w).join(`
|
|
273
273
|
`)});let b=nr(e,s);b&&d({kind:"note",tone:"info",text:b})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ke.current=null,Q(null),N(!1),ae(u=>u+1)}},[e,s,d,t]),Ao=Y(async l=>{await ce(tr(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await Wn(e,s,l.replace(/\\/g,"/"));i.length>0&&(Qe(`Related articles not yet published (${i.length}):`),G([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,ce]),Eo=Y(l=>{let i=Ge(l);if(!i||_e(i)&&!i.refreshToken)return null;let a={...It(i.idToken)??{},...It(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),Io=Y((l,i)=>{if(i){let a=J(e);a&&(a.defaultProfile=l,ul(a,e))}c(l),me(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Eo(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"])),ae(a=>a+1)},[e,d,me,Eo]),wn=Y((l,i,a)=>{vn(e,l,i,a.id,a.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),me(),po(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:St(Rt(e)).join(`
|
|
274
|
-
`)}),vt(ot()),Mt.current=Ee(e).status==="current"||Yt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,me,vt]),yn=Y(async l=>{let i;try{i=await qt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),G(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let u=g[0],h=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${h>0?" (skipped the API-documentation workspace)":""}.`}),wn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),G(["/workspace"])},[e,d,wn]),kn=Y((l,i)=>{Mo(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),me(),yn(l)},[e,d,me,yn]),Cs=Y(async l=>{let i;try{i=ue(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await nt(e,i.name),g=a.find(u=>u.id===i.project.projectId);g?.name
|
|
274
|
+
`)}),vt(ot()),Mt.current=Ee(e).status==="current"||Yt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,me,vt]),yn=Y(async l=>{let i;try{i=await qt(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),G(["/workspace"]);return}if(i.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let u=g[0],h=i.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${h>0?" (skipped the API-documentation workspace)":""}.`}),wn(i.profile,i.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),G(["/workspace"])},[e,d,wn]),kn=Y((l,i)=>{Mo(e,l,i.id,i.name),d({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),me(),yn(l)},[e,d,me,yn]),Cs=Y(async l=>{let i;try{i=ue(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await nt(e,i.name),g=a.find(u=>u.id===i.project.projectId);g?.name&&vf(e,i.name,{projectName:g.name})}catch{}await yn(i.name);return}try{let{projects:a}=await nt(e,i.name);if(a.length===1){let g=a[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),kn(i.name,{id:g.id,name:g.name});return}if(a.length>1){let g=a.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Xe({cursor:0,current:-1,rows:g,profile:i.name,environment:i.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),G(["/project"])}},[e,d,yn,kn]),bn=Y(()=>{let l=Ue.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=st(l.oldContent,l.newContent,Le());d(i?{kind:"diff",added:i.added,removed:i.removed,lines:i.lines,hidden:i.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,Le]),Ps=Y(l=>{if(Ue.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Ue.current.shift();try{cf({cwd:e,profileName:s},a),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Ue.current.length===0&&G(g=>g.length>0?g:["/sync"])}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=Ue.current.shift();d({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Ue.current.length;return Ue.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return bn(),!0},[e,s,bn,d]),Ts=Y(l=>{let i=wo.current;if(!i)return!1;if(wo.current=null,le(null),ct.current++,l.trim()!==i.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=qr(e,i.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${a.length} item${a.length===1?"":"s"}. The repo is back to its original state.`});for(let u of g)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return i.hadDevhints&&(d({kind:"note",tone:"warn",text:_n().join(`
|
|
275
275
|
`)}),vt(Bo())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
276
|
-
${fl}`}),G(["/init"]),an(!1),!0},[e,d,vt]),Rs=Y(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(an(!0),a){case"help":Ut({tab:0});return;case"exit":case"quit":ge.current?.close(),r();return;case"clear":me(),ft.current=[],an(!1),le(null),ct.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=ue(e,s)}catch(h){d({kind:"note",tone:"error",text:h.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),se(!0);try{let h=await
|
|
276
|
+
${fl}`}),G(["/init"]),an(!1),!0},[e,d,vt]),Rs=Y(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(an(!0),a){case"help":Ut({tab:0});return;case"exit":case"quit":ge.current?.close(),r();return;case"clear":me(),ft.current=[],an(!1),le(null),ct.current++,d({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let u;try{u=ue(e,s)}catch(h){d({kind:"note",tone:"error",text:h.message});return}d({kind:"note",tone:"info",text:`Profile "${u.name}" \u2192 ${u.connection.name} (${u.connection.apiUrl})${u.production?" \u26A0 PRODUCTION":""}`}),se(!0);try{let h=await Vp(u.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},b=>d({kind:"note",tone:"info",text:b})),w=zp(u.name,h);if(Kp(w),await Lo(w,u.name,b=>d({kind:"note",tone:"info",text:b})),d({kind:"note",tone:"ok",text:`\u2713 Logged in to "${u.name}" as ${Pn(w)}`}),await Cs(s),Ot.current){let b=Ot.current;Ot.current=null;let P=Ie(e,s);P.ok?(d({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${b}.`}),G([b])):(d({kind:"note",tone:"warn",text:`${P.reason} (then ${b}.)`}),G(["/login"]),Ot.current=b)}else pn.current&&(le(pn.current),pn.current=null,d({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(h){d({kind:"note",tone:"error",text:`Login failed: ${h.message}`})}finally{se(!1),ae(h=>h+1)}return}case"allow-prod":{let u=!1;try{u=ue(e,s).production}catch{}if(!u){d({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}mt.current=!0,me(),d({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let u=Sr(g.join(" ")),h=Se.current.uuid;if(!h){d({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!u){d({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let w=Se.current.firstPrompt??"";cl(w,e).then(b=>{b?(le(`/rename ${b}`),d({kind:"note",tone:"info",text:`Suggestion: "${b}" \u2014 press tab to accept, or type /rename <your name>.`})):d({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>d({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}af(h,u),ht(u),nn(`${Xr} d360-writer \xB7 ${u}`),d({kind:"note",tone:"ok",text:`Session renamed to "${u}".`});return}case"profile":{let u=g[0],h=J(e);if(!u){let w=Object.entries(h?.profiles??{});if(w.length===0){d({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let b=w.map(([K,Z])=>({name:K,env:Z.connection?.environment??"custom",prod:Z.production===!0,who:Eo(K)})),P=s??h?.defaultProfile,E=Math.max(0,b.findIndex(K=>K.name===P));gt({cursor:E,current:E,rows:b});return}if(u==="add"){let w=Dr(e,g[1],g[2]);if(w){d({kind:"note",tone:"error",text:w});return}d({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),Io(g[1],!1);return}if(!h?.profiles?.[u]){d({kind:"note",tone:"error",text:`Unknown profile "${u}". Create it: /profile add ${u} <environment>`});return}Io(u,!0);return}case"doctor":await en(g,{cwd:e});return;case"mcp":await Un(g);return;case"init":{if(J(e)){d({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let u=ff().map(h=>({name:h,apiUrl:mf(h).apiUrl}));wt({cursor:0,rows:u});return}case"resume":{let u=g.join(" ").trim(),h=sf(e).filter(P=>P.uuid!==Se.current.uuid);if(!u){if(!h.length){d({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}tt({query:"",cursor:0,sessions:h});return}let w=rf(e,u);if(!w){d({kind:"note",tone:"error",text:`No session matches "${u}".`});return}me(w.uuid),Se.current={uuid:w.uuid,firstPrompt:w.firstPrompt,titleFired:!0},ht(w.name),ts(w.uuid),ft.current=[];let b=Kr(e,w.uuid);for(let P of b)d(P);d({kind:"note",tone:"ok",text:b.length?`Resumed "${w.name}" \u2014 restored ${b.length} message(s); continue where you left off.`:`Resumed "${w.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let u=g.join(" ").trim(),h;try{h=await qt(e,s)}catch(b){d({kind:"note",tone:"error",text:`Could not list workspaces: ${b.message}`});return}if(!u){let b=h.workspaces.map(E=>({id:E.id,name:E.name??E.id,type:E.workspace_type}));if(b.length===0){d({kind:"note",tone:"info",text:"No workspaces in this project."});return}let P=Math.max(0,b.findIndex(E=>E.id===h.current));yt({cursor:P,current:P,rows:b,profile:h.profile,projectId:h.projectId,projectName:h.projectName,environment:h.environment});return}let w=Uo(h.workspaces,u);if(!w){d({kind:"note",tone:"error",text:`No workspace matches "${u}".`});return}wn(h.profile,h.projectId,w);return}case"project":{let u=g.join(" ").trim(),h;try{h=await nt(e,s)}catch(b){d({kind:"note",tone:"error",text:`Could not list projects: ${b.message} (signed in? try /login)`});return}if(!u){let b=h.projects.map(E=>({id:E.id,name:E.name??E.id,sub:E.sub_domain}));if(b.length===0){d({kind:"note",tone:"info",text:"No projects found for this identity."});return}let P=b.findIndex(E=>E.id===h.current);Xe({cursor:Math.max(0,P),current:P,rows:b,profile:h.profile,environment:h.environment});return}let w=_s(h.projects,u);if(!w){d({kind:"note",tone:"error",text:`No project matches "${u}". Available: ${h.projects.map(b=>b.name??b.id).join(", ")}`});return}kn(h.profile,w);return}case"logout":{let u;try{u=ue(e,s).name}catch(w){d({kind:"note",tone:"error",text:w.message});return}let h=Zp(u);ef(e,u),me(),ae(w=>w+1),d({kind:"note",tone:h?"ok":"info",text:h?`\u2713 Signed out of "${u}" and cleared its project/workspace selection.`:`Profile "${u}" was not signed in. Cleared any project/workspace selection.`}),d({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),G(["/login"]);return}case"publish":{if(!Po(l.trim()))return;if(g[0]==="--related"&&g[1]){let h=await Wn(e,s,g[1].replace(/\\/g,"/"));if(h.length===0){d({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await gn(h);return}if(g[0]&&g[0]!=="--all"){await Ao(g[0]);return}let u=g[0]==="--all";d({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let h=await ns({cwd:e,profileName:s}),w=Jt(h.entries),b=Mn(h.entries);if(b>0&&d({kind:"note",tone:"warn",text:`\u26A0 ${b} article${b===1?"":"s"} already exist on Document360 but aren\u2019t linked \u2014 left OUT of publish (publishing would duplicate them). Run /catch-up (or ask me to link them) first.`}),w.length===0){d({kind:"note",tone:"ok",text:b>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let P=h.counts["unknown-base"]??0;P>0&&d({kind:"note",tone:"info",text:`(${P} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(u){await gn(w.map(P=>P.path));return}kt({cursor:0,rows:Pi(w)})}catch(h){d({kind:"note",tone:"error",text:`Could not compute sync status: ${h.message}`}),d({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let u=g.join(" ").trim();if(!u){let w=[];try{w=Object.keys(po(e,ue(e,s).name)?.articles??{})}catch{}if(w.length===0){d({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Ze({query:"",cursor:0,paths:w});return}let h=Gp(u)?u:lt(e,u);if(Be(h)){try{d({kind:"preview",name:rn(h),text:hl(es(h,"utf8"))})}catch(w){d({kind:"note",tone:"error",text:`Could not read ${h}: ${w.message}`})}return}if(jf.test(u)){try{let w=ue(e,s),b={profile:w.name,connection:w.connection},P=w.project.projectId??Jp(b),E=await Qp(b,P,u);d({kind:"preview",name:E.title??u,text:E.content??"*(article has no content)*"})}catch(w){d({kind:"note",tone:"error",text:`Could not fetch article: ${w.message}`})}return}d({kind:"note",tone:"error",text:`"${u}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let u=g[0]?.trim();if(!u){let P=Bn(is(e));Ke({cursor:P,current:P});return}let{lines:h,changed:w,effective:b}=Zt(e,u);for(let P of h)d({kind:"note",tone:P.startsWith("\u26A0")?"warn":P.startsWith("\u2713")?"ok":"info",text:P});w&&(ks(P=>P+1),ge.current?.setModel(b));return}case"convert":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:u,run:h}=ar(g),w=wf(e,s);if(w.length===0){d({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let b=lr(w,u);if(b.length===0){d({kind:"note",tone:"error",text:`No tracked articles under "${u}". (${w.length} are tracked overall.)`});return}let P=os(b),E=3,K=`/convert${u?` --scope ${u}`:""} --run`,Z=co(e,"light");if(!h){let $=dl({files:cr(e,b),op:"convert",model:Z.model}),D=u?`Scope: ${u} (${b.length} of ${w.length} tracked)
|
|
277
277
|
`:"",M=`
|
|
278
278
|
Model: ${Z.model}${Z.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;d({kind:"note",tone:"info",text:D+dr(P,$,E).join(`
|
|
279
279
|
`)+M}),G([K]);return}Ve.current=Date.now(),ut(0),N(!0);let _=new AbortController;ke.current=_,Q({verb:"Converting",total:P.length,done:0,active:[],rows:on(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Converting ${b.length} articles across ${P.length} partitions (\u2264${E} agents at once) on ${Z.model}\u2026 (esc to stop)`});try{for await(let $ of lo({cwd:e,partitions:P,promptFor:ur,concurrency:E,profileName:s,allowProdWrites:mt.current,model:Z.model,signal:_.signal}))if($.type==="partition_status")$.status==="running"?Q(D=>D&&{...D,active:[...D.active,$.label],rows:Ne(D.rows,$.label,"active"),lastAt:Date.now()}):Q(D=>D&&{...D,active:D.active.filter(M=>M!==$.label),done:D.done+1,rows:Ne(D.rows,$.label,$.status==="done"?"done":"failed"),lastAt:Date.now()});else if($.type==="partition_event")Q(D=>{if(!D)return D;let M={...D,lastAt:Date.now()};return $.event.type==="tool"?M.tools=D.tools+1:$.event.type==="text"&&(M.chars=D.chars+$.event.delta.length),M});else if($.type==="run_done"){$t(ee=>ee+$.totalCostUsd),xt(ee=>ee+$.results.reduce((q,z)=>q+z.outputTokens,0));let D=$.aborted?"Stopped. ":"",M=t.kind==="api"?"api":"subscription";d({kind:"note",tone:$.aborted?"warn":$.ok?"ok":"warn",text:D+pr($.results,P,M).join(`
|
|
@@ -284,16 +284,16 @@ Model: ${D.model}${D.forced?" (forced)":" \u2014 authoring; /model to override"}
|
|
|
284
284
|
`)}),!q.aborted&&q.ok&&G(["/publish --all","/screenshot --all"])}}catch(q){d({kind:"note",tone:"error",text:`Write run failed: ${q.message}`})}finally{ke.current=null,Q(null),N(!1),ae(q=>q+1)}return}case"draft":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:u,looseDocs:h}=xr(e);if(u.length===0&&h===0){d({kind:"note",tone:"info",text:vr});return}let w=g.join(" ").trim();if(!w&&u.length>1){d({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
|
|
285
285
|
${u.map(E=>` \u2022 ${E.name} (${E.docCount} doc${E.docCount===1?"":"s"})`).join(`
|
|
286
286
|
`)}`}),G(u.map(E=>`/draft ${E.name}`));return}let b="",P;if(w){let E=$r(u,w);E?b=E:P=w}else b=u[0]?.name??"";await ce(qn(b,P),{display:w?`/draft ${w}`:"/draft",quietUser:!0});return}case"sync":{if(!Po(l.trim()))return;let u=(g[0]??"status").toLowerCase();try{if(u==="status"){d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let h=await ns({cwd:e,profileName:s});d({kind:"note",tone:"info",text:Hn(h).join(`
|
|
287
|
-
`)});return}if(u==="pull"){let h=g[1];if(!h){d({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(h==="--all"){if(d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await ns({cwd:e,profileName:s})).entries.filter(E=>E.status==="remote-ahead"&&E.path).map(E=>E.path),w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else w=[h.replace(/\\/g,"/")];let b=[];for(let P of w)b.push(await
|
|
287
|
+
`)});return}if(u==="pull"){let h=g[1];if(!h){d({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let w;if(h==="--all"){if(d({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),w=(await ns({cwd:e,profileName:s})).entries.filter(E=>E.status==="remote-ahead"&&E.path).map(E=>E.path),w.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else w=[h.replace(/\\/g,"/")];let b=[];for(let P of w)b.push(await uf({cwd:e,profileName:s,relPath:P}));Ue.current=b,bn();return}if(u==="baseline"){let h=g[1],w=h&&h!=="--all"?h.replace(/\\/g,"/"):void 0;d({kind:"note",tone:"info",text:w?`Setting the sync baseline for ${w}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"});let b=await df({cwd:e,profileName:s,relPaths:w?[w]:void 0});if(b.baselined.length===0&&b.skipped.length===0){d({kind:"note",tone:"ok",text:"\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."});return}b.baselined.length>0&&d({kind:"note",tone:"ok",text:`\u2713 Baselined ${b.baselined.length} article${b.baselined.length===1?"":"s"} \u2014 they now read in-sync until either side changes.`}),b.skipped.length>0&&d({kind:"note",tone:"warn",text:`${b.skipped.length} skipped:
|
|
288
288
|
${b.skipped.map(P=>` - ${P.path} (${P.reason})`).join(`
|
|
289
|
-
`)}`}),ae(P=>P+1);return}d({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${u} \u2014 use /sync, /sync pull <path>|--all, or /sync baseline.`})}catch(h){d({kind:"note",tone:"error",text:`Sync failed: ${h.message}`})}return}case"scope":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=
|
|
289
|
+
`)}`}),ae(P=>P+1);return}d({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${u} \u2014 use /sync, /sync pull <path>|--all, or /sync baseline.`})}catch(h){d({kind:"note",tone:"error",text:`Sync failed: ${h.message}`})}return}case"scope":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let u=pf(e);if(u.length===0){d({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}bt({cursor:0,rows:u.map(h=>({...h,checked:h.recommended}))});return}case"audit":{if(g[0]==="--auto"){let h=J(e);if(!h){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let w=g[1]!=="off";ul({...h,autoAudit:w},e),d({kind:"note",tone:"ok",text:w?"\u2713 Auto-audit ON \u2014 when you launch with code changes since the last audit, I\u2019ll run /audit automatically. (/audit --auto off to disable.)":"\u2713 Auto-audit OFF \u2014 I\u2019ll just nudge you to run /audit when code changed."});return}let u=await Qt();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});return}case"capture-setup":{let u=await tn();u.kind==="forward-to-agent"&&u.prompt&&await ce(u.prompt,{display:u.display,quietUser:!0});let h=_r(e);h&&d({kind:"note",tone:"info",text:h.join(`
|
|
290
290
|
`)});return}case"devhints":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:St(Rt(e)).join(`
|
|
291
291
|
`)}),vt(ot()),Mt.current=Ee(e).status==="current"||Yt(e);return}case"inbox":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Or(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ce(Ur(),{display:"/inbox",quietUser:!0});return}case"document":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:h}=Pr(g);if(!h&&Cr(e)===0){d({kind:"note",tone:"info",text:Rr});return}let w=`/document${h?` ${h}`:""}${u?" --publish":""}`;await ce(Tr(h,u),{display:w,quietUser:!0});return}case"catch-up":{if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!Po(l.trim()))return;let{publish:u}=Mr(g),h=Et(At(e));d({kind:"note",tone:"info",text:h?`Catching up on ${h} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026"}),await ce(Lr({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{vo.current=!0,d({kind:"note",tone:"info",text:`Updating ${it}\u2026 (don\u2019t close this window)`}),ln(!0),(await zn().finally(()=>ln(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),G(h=>h.includes("/exit")?h:[...h,"/exit"]),ds("")):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Vn}`});return}case"screenshot":{let u=Er(g);if(u.mode==="list"){if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Nr(Ir(e,u.scope),u.scope).join(`
|
|
292
|
-
`)});return}if(u.mode==="single"){let _=await Yn(g);_.kind==="forward-to-agent"&&_.prompt&&await ce(_.prompt,{display:_.display,quietUser:!0});return}if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=u.mode==="scope"?u.scope:void 0,w=
|
|
292
|
+
`)});return}if(u.mode==="single"){let _=await Yn(g);_.kind==="forward-to-agent"&&_.prompt&&await ce(_.prompt,{display:_.display,quietUser:!0});return}if(!J(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=u.mode==="scope"?u.scope:void 0,w=gf(e,{scope:h}).map(_=>_.id);if(w.length===0){d({kind:"note",tone:"info",text:h?`No screenshot placeholders under ${h}.`:"No screenshot placeholders found in the docs."});return}let b=6,P=hf(w,3),E=co(e,"standard");Ve.current=Date.now(),ut(0),N(!0);let K=new AbortController;ke.current=K,Q({verb:"Authoring",unit:"spec",total:P.length,done:0,active:[],rows:on(P),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Authoring ${w.length} screenshot spec${w.length===1?"":"s"} across ${P.length} partition${P.length===1?"":"s"} (\u2264${b} agents at once) on ${E.model}${E.forced?" (forced)":""}\u2026 (esc to stop)`});let Z=!1;try{for await(let _ of lo({cwd:e,partitions:P,promptFor:ha,concurrency:b,profileName:s,allowProdWrites:mt.current,model:E.model,signal:K.signal}))if(_.type==="partition_status")_.status==="running"?Q($=>$&&{...$,active:[...$.active,_.label],rows:Ne($.rows,_.label,"active"),lastAt:Date.now()}):Q($=>$&&{...$,active:$.active.filter(D=>D!==_.label),done:$.done+1,rows:Ne($.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_event")Q($=>{if(!$)return $;let D={...$,lastAt:Date.now()};return _.event.type==="tool"?D.tools=$.tools+1:_.event.type==="text"&&(D.chars=$.chars+_.event.delta.length),D});else if(_.type==="run_done"){$t(ee=>ee+_.totalCostUsd),xt(ee=>ee+_.results.reduce((q,z)=>q+z.outputTokens,0));let $=_.results.filter(ee=>ee.ok).length,D=_.aborted?"Stopped. ":"";Z=!_.aborted&&u.setup;let M=_.aborted?"":Z?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:_.aborted?"warn":_.ok?"ok":"warn",text:`${D}Authored specs \u2014 ${$}/${_.results.length} batches ok.${M}`})}}catch(_){d({kind:"note",tone:"error",text:`Spec authoring failed: ${_.message}`})}finally{ke.current=null,Q(null),N(!1),ae(_=>_+1)}if(Z){let _=await tn();_.kind==="forward-to-agent"&&_.prompt&&await ce(_.prompt,{display:_.display,quietUser:!0});let $=_r(e);$&&d({kind:"note",tone:"info",text:$.join(`
|
|
293
293
|
`)})}return}case"reset":{let u=Hr(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}wo.current={repoName:rn(e),targets:u,hadDevhints:Be(as(e))},d({kind:"note",tone:"warn",text:Br(e,u).join(`
|
|
294
|
-
`)}),le(rn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,bn,d,me,ce,gn,Ao,Cs]),xn=Y(l=>{let i=(l??A).trim();if(y(""),cn(null),dt(0),i.startsWith("/")&&(le(null),ct.current++,Qe(null),G(g=>Xa(g,i))),!i||Ts(i)||Ps(i))return;go.current.push(i);let a=nl(i,ps.current);i.startsWith("/")?(d({kind:"user",text:i}),Rs(a)):ce(a,{display:i})},[A,Ts,Ps,Rs,ce]),Ss=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Za(l);if(el(i)){let a=tl(++Dl.current,i);ps.current.set(a,i),T(a)}else T(i);return}T(l)},[T]),Ct=Math.max(10,je-6),Ds=Zr(()=>io(x.text,Ct),[x.text,Ct]),No=Y(l=>k(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),$n=Y(l=>k(i=>({...i,pos:rl(io(i.text,Ct),i.pos,l)})),[Ct]),Ft=Y(l=>k(i=>({...i,pos:sl(io(i.text,Ct),i.pos,l)})),[Ct]),El=["\x1B[H","\x1B[1~","\x1BOH"],Il=["\x1B[F","\x1B[4~","\x1BOF"],js=Y((l,i)=>i.leftArrow?(No(-1),!0):i.rightArrow?(No(1),!0):l&&El.includes(l)?(Ft("start"),!0):l&&Il.includes(l)?(Ft("end"),!0):i.ctrl&&l==="a"?(Ft("start"),!0):i.ctrl&&l==="e"?(Ft("end"),!0):!1,[No,Ft]);return Fp((l,i)=>{if(i.ctrl&&l==="c"){ge.current?.close(),r();return}if(!H){if(S){if(i.escape){if(ke.current){ke.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ke.current.abort());return}_t.current||(_t.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ge.current?.interrupt());return}if(i.return){let a=A.trim();if(!a)return;et.current.push(a),yo([...et.current]),y("");return}if(js(l,i))return;if(i.upArrow){$n(-1);return}if(i.downArrow){$n(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Ss(l);return}if(ze){if(i.upArrow){Ke(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ke(a=>a&&{...a,cursor:Math.min(Re.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Ke(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Re[ze.cursor];Ke(null);let{lines:g,changed:u,effective:h}=Zt(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(ks(w=>w+1),ge.current?.setModel(h));return}if(l==="s"){let a=Re[ze.cursor];Ke(null),ge.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Ke(null);return}return}if(De){if(i.upArrow){gt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){gt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){gt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=De.rows[De.cursor];gt(null),Io(a.name,i.return===!0);return}if(i.escape){gt(null);return}return}if(ko){if(i.escape){Ut(null);return}if(i.leftArrow||i.tab&&i.shift){Ut(a=>a&&{tab:(a.tab-1+xe.length)%xe.length});return}if(i.rightArrow||i.tab){Ut(a=>a&&{tab:(a.tab+1)%xe.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Ut({tab:Number(l)-1});return}return}if(Me){if(i.upArrow){wt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){wt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){wt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Me.rows[Me.cursor].name;if(wt(null),!ui(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let u=!1;try{let h=Ge(a);u=!!h&&!(_e(h)&&!h.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),G(["/login"]),ae(h=>h+1);return}if(i.escape){wt(null);return}return}if(de){if(i.upArrow){yt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){yt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=de.rows.length){yt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=de.rows[de.cursor],{profile:g,projectId:u}=de;yt(null),wn(g,u,a);return}if(i.escape){yt(null);return}return}if(we){if(i.upArrow){Xe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Xe(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.rows.length){Xe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=we.rows[we.cursor],{profile:g}=we;Xe(null),kn(g,a);return}if(i.escape){Xe(null);return}return}if(fe){if(i.upArrow){bt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){bt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){bt(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=fe.rows.filter(g=>g.checked).map(g=>g.path);if(bt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}rr(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){bt(null);return}return}if(Je){if(i.upArrow){kt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){kt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Je.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Je.rows[Je.cursor];kt(null),a.kind==="article"?Ao(a.paths[0]):gn(a.paths);return}if(i.escape){kt(null);return}return}if(ye){if(i.escape){Ze(null);return}if(i.upArrow){Ze(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ze(a=>a&&{...a,cursor:Math.min(Math.max(0,mn.length-1),a.cursor+1)});return}if(i.return){let a=mn[ye.cursor];if(a){Ze(null);try{d({kind:"preview",name:rn(a),text:hl(es(lt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){Ze(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ze(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(be){if(i.escape){tt(null);return}if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Math.max(0,hn.length-1),a.cursor+1)});return}if(i.return){let a=hn[be.cursor];if(a){tt(null),me(a.uuid),Se.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},ht(a.name),ts(a.uuid),ft.current=[];let g=Kr(e,a.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){tt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){tt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!A&&Ce){y(Ce),le(null),ct.current++;return}if(!A&&Ye.length>0&&l&&/^[1-9]$/.test(l)){let a=Ye[Number(l)-1];if(a){y(a);return}}if(!A&&(To||xo)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=To!=null;Oa(To??xo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&Ro(null)});return}if(!js(l,i)){if($s){if(i.upArrow){dt(a=>Math.max(0,a-1));return}if(i.downArrow){dt(a=>Math.min(Wt.length-1,a+1));return}if(i.tab){y("/"+(Wt[Nt]?.name??"")+" "),dt(0);return}if(i.return){let a=Wt[Nt];if(a){let g=A.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ga(a.usage)&&!g){y("/"+a.name+" "),dt(0);return}xn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(A!==""&&pt===null){$n(-1);return}let a=go.current;if(!a.length)return;let g=pt===null?a.length-1:Math.max(0,pt-1);cn(g),y(a[g]??"");return}if(i.downArrow){if(A!==""&&pt===null){$n(1);return}let a=go.current;if(pt===null)return;let g=pt+1;g>=a.length?(cn(null),y("")):(cn(g),y(a[g]??""));return}}if(i.return){xn();return}if(i.backspace||i.delete){C();return}if(i.escape){y(""),dt(0),le(null),G([]),Qe(null);return}l&&!i.ctrl&&!i.meta&&Ss(l)}}}),$e(()=>{if(S||H)return;let l=et.current.shift();l!==void 0&&(yo([...et.current]),xn(l))},[S,H,xn]),B(te,{flexDirection:"column",width:je,children:[jo!==null&&B(te,{marginTop:1,flexDirection:"column",children:[jo.truncated&&j(R,{dimColor:!0,children:"\u2026"}),j(R,{children:jo.text})]}),S&&(gs?j(Ef,{p:gs}):j(jf,{startTime:Ve.current,chars:Sl})),j(te,{borderStyle:"round",borderColor:xs.prod?"yellow":L,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:A?Ds.map((l,i)=>{let a=x.text.slice(l.start,l.end),g=i===ao(Ds,x.pos),u=Math.min(x.pos,l.end)-l.start;return B(R,{children:[j(R,{color:L,children:i===0?"> ":" "}),g?B(rs,{children:[a.slice(0,u),j(uo,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):B(R,{children:[j(R,{color:L,children:"> "}),Ce&&!S?B(rs,{children:[j(uo,{ch:Ce[0],dim:!0}),j(R,{color:"gray",children:Ce.slice(1)}),j(R,{dimColor:!0,children:" (tab)"})]}):(Do.isSetup||!Tl)&&!S?B(rs,{children:[j(uo,{ch:Do.text[0],dim:!0}),j(R,{color:"gray",children:Do.text.slice(1)})]}):j(uo,{ch:" "})]})}),hs.length>0&&j(te,{flexDirection:"column",paddingX:1,children:hs.map((l,i)=>j(R,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),ko?j(Va,{tab:ko.tab,width:je}):ze?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Select model"}),j(R,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Re.map((l,i)=>B(R,{color:i===ze.cursor?L:void 0,children:[i===ze.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===ze.current?" \u2714":""}`.padEnd(16),j(R,{color:"gray",children:l.desc})]},l.label)),j(R,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):De?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Switch connection profile"}),De.rows.map((l,i)=>B(R,{color:i===De.cursor?L:void 0,children:[i===De.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===De.current?" \u2714":""}`.padEnd(20),j(R,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(R,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(R,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Me?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Pick your Document360 environment"}),Me.rows.map((l,i)=>B(R,{color:i===Me.cursor?L:void 0,children:[i===Me.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),j(R,{color:"gray",children:l.apiUrl})]},l.name)),j(R,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):de?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Switch workspace"}),j(R,{dimColor:!0,children:`environment ${de.environment} \xB7 project ${de.projectName??`${de.projectId.slice(0,8)}\u2026`}`}),de.rows.map((l,i)=>B(R,{color:i===de.cursor?L:void 0,children:[i===de.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===de.current?" \u2714":""}`.padEnd(30),j(R,{color:"gray",children:l.type??""})]},l.id)),j(R,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):we?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Choose project"}),j(R,{dimColor:!0,children:`environment ${we.environment}`}),we.rows.map((l,i)=>B(R,{color:i===we.cursor?L:void 0,children:[i===we.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===we.current?" \u2714":""}`.padEnd(30),j(R,{color:"gray",children:l.sub??""})]},l.id)),j(R,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let i=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),a=fe.rows.slice(i,i+14),g=fe.rows.filter(u=>u.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),i>0?j(R,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,h)=>{let w=i+h;return B(R,{color:w===fe.cursor?L:void 0,children:[w===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,je-34)),j(R,{color:"gray",children:Fn(u)})]},u.path)}),i+14<fe.rows.length?j(R,{dimColor:!0,children:` \u2193 ${fe.rows.length-i-14} more`}):null,j(R,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Je?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Je.rows.map((l,i)=>{let a=i===Je.cursor,g=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return B(R,{color:a?L:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,je-24)),l.note?j(R,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(R,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ye?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),mn.length===0?j(R,{color:"gray",children:"no articles match"}):mn.map((l,i)=>B(R,{color:i===ye.cursor?L:void 0,children:[i===ye.cursor?"\u276F ":" ",l]},l)),j(R,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):be?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:`Resume session${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),hn.length===0?j(R,{color:"gray",children:"no sessions match"}):hn.map((l,i)=>B(R,{color:i===be.cursor?L:void 0,children:[i===be.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(R,{color:i===be.cursor?L:"gray",children:l.firstPrompt.slice(0,Math.max(10,je-40))})]},l.uuid)),j(R,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):$s?B(te,{flexDirection:"column",children:[Wt.map((l,i)=>B(R,{color:i===Nt?L:void 0,children:[i===Nt?"\u276F ":" ",l.usage.padEnd(22)," ",j(R,{color:i===Nt?L:"gray",children:l.name==="model"&&bo?`${l.desc} (currently ${bo})`:l.desc})]},l.name)),j(R,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!A&&Ye.length>0?B(te,{flexDirection:"column",paddingX:1,children:[ms?j(R,{color:L,children:ms}):null,Ye.map((l,i)=>{let a=l.slice(0,Math.max(20,je-5)),g=je-a.length-7,u=g>=12?qa(l).slice(0,g):"";return B(R,{children:[j(R,{color:L,children:i+1})," ",a,u?j(R,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),j(R,{dimColor:!0,children:`press 1-${Ye.length} to fill the command \xB7 esc dismiss`})]}):j(te,{paddingX:1,children:B(R,{color:"gray",children:[xs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${bo??"model n/a"}${t.kind==="api"?ys>0?` \xB7 ${pe(ys)}`:"":ws>0?` \xB7 ${He(ws)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Of}from"react/jsx-runtime";async function bl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=_f(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Nf(Of(kl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
295
|
-
`),process.exit(0)}W();import{writeCrashLog as xl,isBenignTransportError as
|
|
294
|
+
`)}),le(rn(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,bn,d,me,ce,gn,Ao,Cs]),xn=Y(l=>{let i=(l??A).trim();if(y(""),cn(null),dt(0),i.startsWith("/")&&(le(null),ct.current++,Qe(null),G(g=>Xa(g,i))),!i||Ts(i)||Ps(i))return;go.current.push(i);let a=nl(i,ps.current);i.startsWith("/")?(d({kind:"user",text:i}),Rs(a)):ce(a,{display:i})},[A,Ts,Ps,Rs,ce]),Ss=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Za(l);if(el(i)){let a=tl(++Dl.current,i);ps.current.set(a,i),T(a)}else T(i);return}T(l)},[T]),Ct=Math.max(10,je-6),Ds=Zr(()=>io(x.text,Ct),[x.text,Ct]),No=Y(l=>k(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),$n=Y(l=>k(i=>({...i,pos:rl(io(i.text,Ct),i.pos,l)})),[Ct]),Ft=Y(l=>k(i=>({...i,pos:sl(io(i.text,Ct),i.pos,l)})),[Ct]),El=["\x1B[H","\x1B[1~","\x1BOH"],Il=["\x1B[F","\x1B[4~","\x1BOF"],js=Y((l,i)=>i.leftArrow?(No(-1),!0):i.rightArrow?(No(1),!0):l&&El.includes(l)?(Ft("start"),!0):l&&Il.includes(l)?(Ft("end"),!0):i.ctrl&&l==="a"?(Ft("start"),!0):i.ctrl&&l==="e"?(Ft("end"),!0):!1,[No,Ft]);return Hp((l,i)=>{if(i.ctrl&&l==="c"){ge.current?.close(),r();return}if(!H){if(S){if(i.escape){if(ke.current){ke.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ke.current.abort());return}_t.current||(_t.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ge.current?.interrupt());return}if(i.return){let a=A.trim();if(!a)return;et.current.push(a),yo([...et.current]),y("");return}if(js(l,i))return;if(i.upArrow){$n(-1);return}if(i.downArrow){$n(1);return}if(i.backspace||i.delete){C();return}l&&!i.ctrl&&!i.meta&&Ss(l);return}if(ze){if(i.upArrow){Ke(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ke(a=>a&&{...a,cursor:Math.min(Re.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){Ke(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Re[ze.cursor];Ke(null);let{lines:g,changed:u,effective:h}=Zt(e,a.value??"default");for(let w of g)d({kind:"note",tone:w.startsWith("\u26A0")?"warn":w.startsWith("\u2713")?"ok":"info",text:w});u&&(ks(w=>w+1),ge.current?.setModel(h));return}if(l==="s"){let a=Re[ze.cursor];Ke(null),ge.current?.setModel(a.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){Ke(null);return}return}if(De){if(i.upArrow){gt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){gt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){gt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=De.rows[De.cursor];gt(null),Io(a.name,i.return===!0);return}if(i.escape){gt(null);return}return}if(ko){if(i.escape){Ut(null);return}if(i.leftArrow||i.tab&&i.shift){Ut(a=>a&&{tab:(a.tab-1+xe.length)%xe.length});return}if(i.rightArrow||i.tab){Ut(a=>a&&{tab:(a.tab+1)%xe.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Ut({tab:Number(l)-1});return}return}if(Me){if(i.upArrow){wt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){wt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Me.rows.length){wt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Me.rows[Me.cursor].name;if(wt(null),!ui(e,a).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let u=!1;try{let h=Ge(a);u=!!h&&!(_e(h)&&!h.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${a} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${a}) and pick your project. (press 1)`}),G(["/login"]),ae(h=>h+1);return}if(i.escape){wt(null);return}return}if(de){if(i.upArrow){yt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){yt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=de.rows.length){yt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=de.rows[de.cursor],{profile:g,projectId:u}=de;yt(null),wn(g,u,a);return}if(i.escape){yt(null);return}return}if(we){if(i.upArrow){Xe(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Xe(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.rows.length){Xe(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=we.rows[we.cursor],{profile:g}=we;Xe(null),kn(g,a);return}if(i.escape){Xe(null);return}return}if(fe){if(i.upArrow){bt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){bt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){bt(a=>a&&{...a,rows:a.rows.map((g,u)=>u===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=fe.rows.filter(g=>g.checked).map(g=>g.path);if(bt(null),a.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}rr(e,a),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){bt(null);return}return}if(Je){if(i.upArrow){kt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){kt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Je.rows.length){kt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Je.rows[Je.cursor];kt(null),a.kind==="article"?Ao(a.paths[0]):gn(a.paths);return}if(i.escape){kt(null);return}return}if(ye){if(i.escape){Ze(null);return}if(i.upArrow){Ze(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ze(a=>a&&{...a,cursor:Math.min(Math.max(0,mn.length-1),a.cursor+1)});return}if(i.return){let a=mn[ye.cursor];if(a){Ze(null);try{d({kind:"preview",name:rn(a),text:hl(es(lt(e,a),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){Ze(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ze(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(be){if(i.escape){tt(null);return}if(i.upArrow){tt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){tt(a=>a&&{...a,cursor:Math.min(Math.max(0,hn.length-1),a.cursor+1)});return}if(i.return){let a=hn[be.cursor];if(a){tt(null),me(a.uuid),Se.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},ht(a.name),ts(a.uuid),ft.current=[];let g=Kr(e,a.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${a.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${a.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(i.backspace||i.delete){tt(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){tt(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!A&&Ce){y(Ce),le(null),ct.current++;return}if(!A&&Ye.length>0&&l&&/^[1-9]$/.test(l)){let a=Ye[Number(l)-1];if(a){y(a);return}}if(!A&&(To||xo)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=To!=null;Oa(To??xo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?a?"\u2713 Copied the feedback to your clipboard \u2014 send it to the d360-writer team (Teams / Slack / email).":"\u2713 Copied the prompt to your clipboard \u2014 paste it into your repo's coding agent.":a?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&a&&Ro(null)});return}if(!js(l,i)){if($s){if(i.upArrow){dt(a=>Math.max(0,a-1));return}if(i.downArrow){dt(a=>Math.min(Wt.length-1,a+1));return}if(i.tab){y("/"+(Wt[Nt]?.name??"")+" "),dt(0);return}if(i.return){let a=Wt[Nt];if(a){let g=A.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ga(a.usage)&&!g){y("/"+a.name+" "),dt(0);return}xn("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(A!==""&&pt===null){$n(-1);return}let a=go.current;if(!a.length)return;let g=pt===null?a.length-1:Math.max(0,pt-1);cn(g),y(a[g]??"");return}if(i.downArrow){if(A!==""&&pt===null){$n(1);return}let a=go.current;if(pt===null)return;let g=pt+1;g>=a.length?(cn(null),y("")):(cn(g),y(a[g]??""));return}}if(i.return){xn();return}if(i.backspace||i.delete){C();return}if(i.escape){y(""),dt(0),le(null),G([]),Qe(null);return}l&&!i.ctrl&&!i.meta&&Ss(l)}}}),$e(()=>{if(S||H)return;let l=et.current.shift();l!==void 0&&(yo([...et.current]),xn(l))},[S,H,xn]),B(te,{flexDirection:"column",width:je,children:[jo!==null&&B(te,{marginTop:1,flexDirection:"column",children:[jo.truncated&&j(R,{dimColor:!0,children:"\u2026"}),j(R,{children:jo.text})]}),S&&(gs?j(If,{p:gs}):j(Af,{startTime:Ve.current,chars:Sl})),j(te,{borderStyle:"round",borderColor:xs.prod?"yellow":L,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:A?Ds.map((l,i)=>{let a=x.text.slice(l.start,l.end),g=i===ao(Ds,x.pos),u=Math.min(x.pos,l.end)-l.start;return B(R,{children:[j(R,{color:L,children:i===0?"> ":" "}),g?B(rs,{children:[a.slice(0,u),j(uo,{ch:a[u]??" "}),a.slice(u+1)]}):a||" "]},`${i}-${l.start}`)}):B(R,{children:[j(R,{color:L,children:"> "}),Ce&&!S?B(rs,{children:[j(uo,{ch:Ce[0],dim:!0}),j(R,{color:"gray",children:Ce.slice(1)}),j(R,{dimColor:!0,children:" (tab)"})]}):(Do.isSetup||!Tl)&&!S?B(rs,{children:[j(uo,{ch:Do.text[0],dim:!0}),j(R,{color:"gray",children:Do.text.slice(1)})]}):j(uo,{ch:" "})]})}),hs.length>0&&j(te,{flexDirection:"column",paddingX:1,children:hs.map((l,i)=>j(R,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),ko?j(Va,{tab:ko.tab,width:je}):ze?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Select model"}),j(R,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Re.map((l,i)=>B(R,{color:i===ze.cursor?L:void 0,children:[i===ze.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===ze.current?" \u2714":""}`.padEnd(16),j(R,{color:"gray",children:l.desc})]},l.label)),j(R,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):De?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Switch connection profile"}),De.rows.map((l,i)=>B(R,{color:i===De.cursor?L:void 0,children:[i===De.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===De.current?" \u2714":""}`.padEnd(20),j(R,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(R,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(R,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Me?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Pick your Document360 environment"}),Me.rows.map((l,i)=>B(R,{color:i===Me.cursor?L:void 0,children:[i===Me.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),j(R,{color:"gray",children:l.apiUrl})]},l.name)),j(R,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):de?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Switch workspace"}),j(R,{dimColor:!0,children:`environment ${de.environment} \xB7 project ${de.projectName??`${de.projectId.slice(0,8)}\u2026`}`}),de.rows.map((l,i)=>B(R,{color:i===de.cursor?L:void 0,children:[i===de.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===de.current?" \u2714":""}`.padEnd(30),j(R,{color:"gray",children:l.type??""})]},l.id)),j(R,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):we?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Choose project"}),j(R,{dimColor:!0,children:`environment ${we.environment}`}),we.rows.map((l,i)=>B(R,{color:i===we.cursor?L:void 0,children:[i===we.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===we.current?" \u2714":""}`.padEnd(30),j(R,{color:"gray",children:l.sub??""})]},l.id)),j(R,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let i=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),a=fe.rows.slice(i,i+14),g=fe.rows.filter(u=>u.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),i>0?j(R,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((u,h)=>{let w=i+h;return B(R,{color:w===fe.cursor?L:void 0,children:[w===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,je-34)),j(R,{color:"gray",children:Fn(u)})]},u.path)}),i+14<fe.rows.length?j(R,{dimColor:!0,children:` \u2193 ${fe.rows.length-i-14} more`}):null,j(R,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Je?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Je.rows.map((l,i)=>{let a=i===Je.cursor,g=l.indent?" ":" ",u=`${i+1}.`.padEnd(3);return B(R,{color:a?L:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,je-24)),l.note?j(R,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(R,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ye?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),mn.length===0?j(R,{color:"gray",children:"no articles match"}):mn.map((l,i)=>B(R,{color:i===ye.cursor?L:void 0,children:[i===ye.cursor?"\u276F ":" ",l]},l)),j(R,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):be?B(te,{flexDirection:"column",paddingX:1,children:[j(R,{color:L,bold:!0,children:`Resume session${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),hn.length===0?j(R,{color:"gray",children:"no sessions match"}):hn.map((l,i)=>B(R,{color:i===be.cursor?L:void 0,children:[i===be.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(R,{color:i===be.cursor?L:"gray",children:l.firstPrompt.slice(0,Math.max(10,je-40))})]},l.uuid)),j(R,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):$s?B(te,{flexDirection:"column",children:[Wt.map((l,i)=>B(R,{color:i===Nt?L:void 0,children:[i===Nt?"\u276F ":" ",l.usage.padEnd(22)," ",j(R,{color:i===Nt?L:"gray",children:l.name==="model"&&bo?`${l.desc} (currently ${bo})`:l.desc})]},l.name)),j(R,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!S&&!A&&Ye.length>0?B(te,{flexDirection:"column",paddingX:1,children:[ms?j(R,{color:L,children:ms}):null,Ye.map((l,i)=>{let a=l.slice(0,Math.max(20,je-5)),g=je-a.length-7,u=g>=12?qa(l).slice(0,g):"";return B(R,{children:[j(R,{color:L,children:i+1})," ",a,u?j(R,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),j(R,{dimColor:!0,children:`press 1-${Ye.length} to fill the command \xB7 esc dismiss`})]}):j(te,{paddingX:1,children:B(R,{color:"gray",children:[xs.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${bo??"model n/a"}${t.kind==="api"?ys>0?` \xB7 ${pe(ys)}`:"":ws>0?` \xB7 ${He(ws)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Uf}from"react/jsx-runtime";async function bl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Of(t);r.kind==="none"&&(console.error(""),console.error(v("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=_f(Uf(kl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
295
|
+
`),process.exit(0)}W();import{writeCrashLog as xl,isBenignTransportError as Mf}from"document360-engine";var $l=!1;function ls(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function vl(e){if($l)return;$l=!0;let t=(n,o)=>{if(Mf(o)){xl({kind:n,level:"transport",message:ls(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=xl({kind:n,level:"fatal",message:ls(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
296
296
|
`+v(`\u2717 d360-writer crashed: ${ls(o)}`)+`
|
|
297
297
|
`),r&&process.stderr.write(m(` Crash details: ${r}`)+`
|
|
298
298
|
`+m(" Run: d360-writer logs")+`
|
|
299
|
-
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var
|
|
299
|
+
`),process.exit(1)};process.on("uncaughtException",n=>t("uncaughtException",n)),process.on("unhandledRejection",n=>t("unhandledRejection",n))}var Hf=Wf(import.meta.url),Cl=Hf("../package.json");vl("d360-writer");var Oe=new Lf;function cs(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}Oe.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=>{cs(e),await Tn({profile:e.profile,manual:e.manual})});Oe.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{cs(e),await Hs({profile:e.profile})});Oe.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{cs(e),await Fs({profile:e.profile})});var us=Oe.command("profile").description("Manage connection profiles for the current repo");us.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>Rn(process.cwd()));us.command("use <name>").description("Set the default profile for this repo").action(e=>Sn(process.cwd(),e));us.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>Dn(process.cwd(),e));var Pl=Oe.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Pl.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>Pt(process.cwd(),e.profile));Pl.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await Is(process.cwd(),e,t.profile)});Oe.command("logs").description("Show the API + crash log files (send these to support when reporting a problem)").action(()=>Ys());Oe.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(()=>(Gn(),aa)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});Oe.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(Cl.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(Ff.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 Vs(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 Na(e.cwd,e.auth,e.profile):await bl(e.cwd,e.auth,e.profile,Cl.version)});Oe.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "document360-writer",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.17",
|
|
4
4
|
"description": "Standalone documentation agent CLI. Reads your code, writes your docs. Specialized for Document360 publishing.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"@inquirer/prompts": "^8.4.3",
|
|
35
35
|
"commander": "^14.0.3",
|
|
36
36
|
"diff": "^8.0.4",
|
|
37
|
-
"document360-engine": "^0.2.
|
|
37
|
+
"document360-engine": "^0.2.62",
|
|
38
38
|
"ink": "^5.2.1",
|
|
39
39
|
"picocolors": "^1.1.1",
|
|
40
40
|
"react": "^18.3.1",
|