document360-writer 0.4.98 → 0.5.0

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.
Files changed (2) hide show
  1. package/dist/cli.js +22 -22
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  var sl=Object.defineProperty;var bo=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var il=(e,t)=>{for(var n in t)sl(e,n,{get:t[n],enumerable:!0})};import Ne from"picocolors";var V,al,ll,cl,ds,Et,f,$,U,E,I,ee,xe,W=bo(()=>{"use strict";V="#7f56d9",[al,ll,cl]=[127,86,217],ds=e=>Ne.isColorSupported?`\x1B[38;2;${al};${ll};${cl}m${e}\x1B[39m`:e,Et=e=>Ne.bold(ds(e)),f=e=>Ne.dim(e),$=e=>Ne.red(e),U=e=>Ne.yellow(e),E=e=>Ne.green(e),I=ds,ee=e=>Ne.gray(e),xe=e=>Ne.bold(e)});import{existsSync as xn,writeFileSync as Ot,readFileSync as Kl,readdirSync as Xl}from"node:fs";import{join as Jl}from"node:path";import{devHintsGuidePath as $n,hintsDir as Ds,architectureDir as Es,messagesDir as To,creatorNotesPath as js,devhintsStatePath as Is,ensureDir as bn,writeMessage as Ql,listOpenForDev as Zl}from"document360-engine";function Ns(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
3
3
 
4
- <!-- devhints script v${ne} \xB7 maintained by document360-writer (/devhints). -->
4
+ <!-- devhints script v${oe} \xB7 maintained by document360-writer (/devhints). -->
5
5
 
6
6
  This repo's user documentation is written by **document360-writer** ("the docs agent"), a separate agent.
7
7
  It can read your code, but code alone can't tell it the *intent* \u2014 WHY a feature exists, which of a
@@ -174,11 +174,11 @@ Anything only a human knows that would help document this product. For example:
174
174
 
175
175
  (Replace these examples with your notes, or leave the file as-is to skip \u2014 it's optional.)
176
176
  `}function yt(e){bn(Ds(e)),bn(Es(e)),bn(To(e));for(let n of[Ds(e),To(e)]){let o=Jl(n,".gitkeep");xn(o)||Ot(o,`# Keeps this document360-writer inbox tracked in git even when empty.
177
- `)}xn(js(e))||Ot(js(e),ec()),Ot($n(e),Ns());let t=_e(e);return Os(e,new Date().toISOString()),t}async function _s(e,t){for(let n of kt(yt(t.cwd)))console.log(n);return{kind:"continue"}}function ze(){return[`This is document360-writer's dev hand-off setup (v${ne}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20134). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current; AND each session, check"," `.d360-writer/messages/` for open questions from the docs agent and answer them \u2014 all per"," `.d360-writer/DEV-HINTS-GUIDE.md`. If that section is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.",'5. Then ask me: "Any tribal knowledge that would help document this product? (folder map, terminology,',` what to prioritize or skip, gotchas \u2014 or say 'none')". If I give you anything, phrase it clearly and`," append it to `.d360-writer/architecture/CREATOR-NOTES.md` (keep the existing header comment and every"," note already there; only add).",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${ne},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print exactly ONE of:",' \u2022 first-time setup: "\u2705 Setup complete \u2014 go back to document360-writer and run: write the docs for this repo"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed \u2014 back in document360-writer, run: write the docs for this repo"'].join(`
178
- `)}function So(e){try{let t=Kl(Is(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Os(e,t){let o={...So(e)??{},emittedVersion:ne,emittedAt:t};Ot(Is(e),`${JSON.stringify(o,null,2)}
179
- `)}function Us(e){try{return Xl(Es(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function _e(e){let n=So(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ne?"stale":"current",completedVersion:n}}function vn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ne};try{if(!xn($n(e)))return n;let o=So(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ne>r&&(bn(To(e)),Ot($n(e),Ns()),Os(e,t),n.guideRefreshed=!0),ne>s&&(Zl(e).some(p=>p.kind==="request"&&p.subject.startsWith(As))||(Ql(e,{id:`onb${ne}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${As}${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:","",ze()].join(`
180
- `)}),n.notifiedBuilder=!0))}catch{}return n}function Cn(e){if(!xn($n(e)))return[];let t=_e(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}`,wt,ze(),wt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Ro(){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 Pn(){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):",wt,Ro(),wt]}function kt(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):",wt,ze(),wt,"","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 here and run: write the docs for this repo"]}var wt,ne,As,Ke=bo(()=>{"use strict";wt="-".repeat(64),ne=5;As="Re-run dev\u2194docs onboarding (protocol v"});var Fi={};il(Fi,{doctorCommand:()=>qt,renderDoctorChecks:()=>Wi,runDoctorChecks:()=>Mi});import{existsSync as Oi}from"node:fs";import{d360GetAll as $u,getAccessToken as vu,isExpired as fr,loadProfileMap as Cu,loadTokens as Pu,packageSkillsDir as Ui,projectConfigPath as Tu,readProjectConfig as Su,DEFAULT_DOCS_DIR as Ru,resolveActiveProfile as Du,classifyClaudeAuth as ju,CLAUDE_CODE_SETUP_HINT as Li,resolveModelSetting as Au,devHintsGuidePath as Eu}from"document360-engine";async function Mi(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=ju();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. ${Li}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Li});let r=Au(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=Su(e);if(!s)return t.push({level:"fail",label:`No ${Tu(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Ru).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 h;try{h=Du(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(k){return t.push({level:"fail",label:`Profile config: ${k.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=Pu(h.name);b?fr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):fr(b)?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(b.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let w=Cu(e,h.name);w?w.projectId&&h.project.projectId&&w.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${w.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(w.articles).length} articles, ${Object.keys(w.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(Oi(Ui())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ui()}`,fix:"Reinstall document360-writer (broken install)"});let R=_e(e);if((Oi(Eu(e))||R.status!=="unset")&&(R.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ne})`}):R.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.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)"})),b&&(!fr(b)||b.refreshToken)){let k={profile:h.name,connection:h.connection};try{await vu(k);let C=await $u(k,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.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"})}}return t}function Wi(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?U("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${I(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?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function qt(e,t){console.log(f("Running checks\u2026"));for(let n of Wi(await Mi(t.cwd)))console.log(n);return{kind:"continue"}}var On=bo(()=>{"use strict";Ke();W()});import{Command as Vp}from"commander";import{createRequire as Yp}from"node:module";import{AUTH_MODES as zp}from"document360-engine";import{input as vl}from"@inquirer/prompts";import{loginPkce as Cl,refreshTokens as Pl,toStoredTokens as ys,clearTokens as Tl,decodeJwtClaims as ws,isExpired as Sl,loadTokens as Rl,saveTokens as ks,resolveActiveProfile as fn,setProfileProject as Dl,readProjectConfig as jl}from"document360-engine";W();import{select as ul}from"@inquirer/prompts";import{resolveActiveProfile as dl,setProfileProject as pl,resolveProjectId as fl,listWorkspaces as ml}from"document360-engine";async function It(e,t){let n=dl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??fl(o);return{workspaces:await ml(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ps=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function xo(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 pn(e,t,n,o,r){pl(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function fs(e,t,n){let o;try{o=await It(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=xo(o.workspaces,t);return r?(pn(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function ht(e,t){let n;try{n=await It(e,t)}catch(b){console.log($(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===c?I("\u25CF"):" "} ${ps(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await ul({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${ps(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);pn(e,s,r,p,h?.name),console.log(E(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as hl}from"@inquirer/prompts";import{resolveActiveProfile as gl,setProfileProject as wl,listProjects as yl}from"document360-engine";async function gt(e,t){let n=gl(e,t),o={profile:n.name,connection:n.connection};return{projects:await yl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ms=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function hs(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 $o(e,t,n,o){wl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function gs(e,t){let n;try{n=await gt(e,t)}catch(h){console.log($(`Could not list projects: ${h.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===s?I("\u25CF"):" "} ${ms(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await hl({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${ms(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);$o(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import kl from"picocolors";function bl(e=process.env){return e.FORCE_HYPERLINK==="0"||!kl.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 xl(e,t=e,n){return bl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var $l=/https?:\/\/[^\s\x1b]+/g;function Nt(e,t){return e.replace($l,n=>xl(n,n,t))}function bs(e){return{...ws(e.idToken)??{},...ws(e.accessToken)??{}}}function mn(e){let t=bs(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 hn(e){let t=fn(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Cl(n,{manual:e.manual,promptForRedirect:s=>vl({message:s})},s=>console.log(Nt(s))),r=ys(t.name,o);if(ks(r),await vo(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${mn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{jl(process.cwd())?.profiles?.[t.name]&&(console.log(""),await ht(process.cwd(),t.name))}catch{}}async function vo(e,t,n){let r=bs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(fn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await gt(process.cwd(),t);c=p.find(h=>h.id===r)?.name}catch{}Dl(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function xs(e){let t=fn(process.cwd(),e.profile),n=t.connection,o=Rl(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${I(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${mn(o)}`),Sl(o))if(o.refreshToken)try{let r=ys(t.name,await Pl(n,o.refreshToken));ks(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(U("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function $s(e){let t=fn(process.cwd(),e.profile);Tl(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as vs,writeProjectConfig as Al,resolveActiveProfile as El,loadTokens as Il,isExpired as Nl}from"document360-engine";function gn(e){let t=vs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?I("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Il(n),h=p?Nl(p)&&!p.refreshToken?U("expired"):f("logged in"):f("not logged in");console.log(`${r}${I(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function wn(e,t){let n=vs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Al(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function yn(e,t){try{let n=El(e,t);console.log(""),console.log(`Profile ${I(n.name)}${n.production?U(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as _l,readdirSync as Ol,statSync as Ul}from"node:fs";import{join as Ll}from"node:path";import{apiLogDir as Ml}from"document360-engine";function Cs(){let e=Ml();if(console.log(""),console.log(`Document360 API logs: ${I(e)}`),!_l(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ol(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let n of t.slice(0,14)){let o=(Ul(Ll(e,n)).size/1024).toFixed(1);console.log(` ${n} ${f(`${o} KB`)}`)}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Wl,resolveAuth as Fl,findByName as Hl,slugify as ql,touchSession as Bl,upsertSession as Gl,resolveActiveProfile as Vl}from"document360-engine";async function Ps(e,t,n,o,r,s){let c=Fl(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Vl(e,r)}catch(k){console.error($(`Document360 profile error: ${k.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let k=Hl(e,o);k||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=k.uuid,console.error(f(`Resuming "${k.name}"`))}let b=Wl({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),w=h??null,R=1;for await(let k of b.send(t))switch(k.type){case"session":if(!w){w=k.sessionId;let C=new Date().toISOString();Gl({uuid:w,name:ql(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:C,updatedAt:C})}break;case"text":process.stdout.write(k.delta);break;case"tool":console.error(ee(` \u2699 ${k.name}`));break;case"result":R=k.ok?0:1,console.error(f(`(${k.inputTokens}\u2192${k.outputTokens} tokens`+(k.costUsd>0?`, $${k.costUsd<.01?k.costUsd.toFixed(4):k.costUsd.toFixed(2)}`:"")+")")),k.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${k.message}`)),process.exit(1)}w&&Bl(w),process.stdout.write(`
177
+ `)}xn(js(e))||Ot(js(e),ec()),Ot($n(e),Ns());let t=_e(e);return Os(e,new Date().toISOString()),t}async function _s(e,t){for(let n of kt(yt(t.cwd)))console.log(n);return{kind:"continue"}}function ze(){return[`This is document360-writer's dev hand-off setup (v${oe}).`,'Connect this repository to document360-writer (its "docs agent" \u2014 a separate tool that writes this',"product's user documentation from your code, but needs your intent). This prompt is SAFE TO RUN MORE","THAN ONCE \u2014 paste it again whenever the product changes. At each step: create what is missing, reconcile","what already exists, and never duplicate, clobber a refined file, or delete human-written notes. In order:","","1. Read `.d360-writer/DEV-HINTS-GUIDE.md` \u2014 the full dev\u2192docs hand-off protocol (Parts 1\u20134). Follow it.","2. Architecture brief in `.d360-writer/architecture/` (per the guide). First read"," `.d360-writer/architecture/CREATOR-NOTES.md` and treat it as authoritative (it may be empty; never"," modify it). Then:"," \u2022 If no brief exists yet, write it now \u2014 a USER-DOC-enabling brief: product intent, user-facing"," surfaces, features and why a user reaches for each, roles/permission gating, core workflows,"," terminology \u2014 every claim citing the source file(s) that prove it. Skip internals (services, data"," access, infra, build/CI, tests)."," \u2022 If a brief already exists, UPDATE it to match the current code: add new surfaces/features, correct"," what changed, remove what was deleted \u2014 but preserve accurate existing content and any human edits."," Do NOT rewrite it from scratch. If nothing changed, leave it as is.","3. Persist the ongoing rule so teammates' agents inherit it: this repo's agent-memory file (CLAUDE.md,"," or AGENTS.md \u2014 whichever this repo already uses; create CLAUDE.md if neither exists) should contain a",' short "Documentation hand-off" section saying: on every user-facing change, drop a hint file in'," `.d360-writer/hints/` and keep `.d360-writer/architecture/` current; AND each session, check"," `.d360-writer/messages/` for open questions from the docs agent and answer them \u2014 all per"," `.d360-writer/DEV-HINTS-GUIDE.md`. If that section is already there, leave it (refine in place only if"," wrong) \u2014 do NOT add a duplicate. Then commit `.d360-writer/` and the memory-file change ONLY if"," something actually changed.","4. Two-way messages (Part 3): check `.d360-writer/messages/` for open questions addressed to you"," (`from: docs`, `status: open`). Answer each \u2014 fold durable facts into the architecture brief and/or drop"," a reply (`from: dev`, `kind: answer`, `re: <id>`) \u2014 then set the question's frontmatter `status: done`."," If there are none, continue.",'5. Then ask me: "Any tribal knowledge that would help document this product? (folder map, terminology,',` what to prioritize or skip, gotchas \u2014 or say 'none')". If I give you anything, phrase it clearly and`," append it to `.d360-writer/architecture/CREATOR-NOTES.md` (keep the existing header comment and every"," note already there; only add).",`6. Record completion: write/merge \`.d360-writer/devhints-state.json\` with {"completedVersion": ${oe},`,' "completedAt": "<UTC now>", "completedCommit": "<current HEAD short sha>"} (preserve any other keys'," already in the file, e.g. emittedAt). Include this file in the commit from step 3.","7. When everything is done, print exactly ONE of:",' \u2022 first-time setup: "\u2705 Setup complete \u2014 go back to document360-writer and run: write the docs for this repo"',' \u2022 a refresh (brief/notes already existed): "\u2705 Hand-off refreshed \u2014 back in document360-writer, run: write the docs for this repo"'].join(`
178
+ `)}function So(e){try{let t=Kl(Is(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}function Os(e,t){let o={...So(e)??{},emittedVersion:oe,emittedAt:t};Ot(Is(e),`${JSON.stringify(o,null,2)}
179
+ `)}function Us(e){try{return Xl(Es(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function _e(e){let n=So(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<oe?"stale":"current",completedVersion:n}}function vn(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:oe};try{if(!xn($n(e)))return n;let o=So(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;oe>r&&(bn(To(e)),Ot($n(e),Ns()),Os(e,t),n.guideRefreshed=!0),oe>s&&(Zl(e).some(p=>p.kind==="request"&&p.subject.startsWith(As))||(Ql(e,{id:`onb${oe}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${As}${oe})`,status:"open",body:[`The dev\u2194docs onboarding protocol moved to v${oe}${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:","",ze()].join(`
180
+ `)}),n.notifiedBuilder=!0))}catch{}return n}function Cn(e){if(!xn($n(e)))return[];let t=_e(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${oe}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,wt,ze(),wt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Ro(){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 Pn(){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):",wt,Ro(),wt]}function kt(e){return[...e?.status==="stale"?[`\u26A0 Your builder last completed devhints v${e.completedVersion}; this hand-off is v${oe}.`," 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):",wt,ze(),wt,"","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 here and run: write the docs for this repo"]}var wt,oe,As,Ke=bo(()=>{"use strict";wt="-".repeat(64),oe=5;As="Re-run dev\u2194docs onboarding (protocol v"});var Fi={};il(Fi,{doctorCommand:()=>qt,renderDoctorChecks:()=>Wi,runDoctorChecks:()=>Mi});import{existsSync as Oi}from"node:fs";import{d360GetAll as $u,getAccessToken as vu,isExpired as fr,loadProfileMap as Cu,loadTokens as Pu,packageSkillsDir as Ui,projectConfigPath as Tu,readProjectConfig as Su,DEFAULT_DOCS_DIR as Ru,resolveActiveProfile as Du,classifyClaudeAuth as ju,CLAUDE_CODE_SETUP_HINT as Li,resolveModelSetting as Au,devHintsGuidePath as Eu}from"document360-engine";async function Mi(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=ju();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. ${Li}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:Li});let r=Au(e);t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`});let s=Su(e);if(!s)return t.push({level:"fail",label:`No ${Tu(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??Ru).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 h;try{h=Du(e),t.push({level:"ok",label:`Profile: ${h.name} (${h.connection.name})${h.production?" \u26A0 PRODUCTION":""}`})}catch(k){return t.push({level:"fail",label:`Profile config: ${k.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=Pu(h.name);b?fr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):fr(b)?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(b.expiresAt).toLocaleString()})`}):t.push({level:"fail",label:"Document360: not logged in",fix:`Run: /login (or d360-writer login --profile ${h.name})`}),t.push(h.project.workspaceId?{level:"ok",label:`Workspace: ${h.project.workspaceName??h.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let w=Cu(e,h.name);w?w.projectId&&h.project.projectId&&w.projectId!==h.project.projectId?t.push({level:"fail",label:`Category map projectId (${w.projectId}) \u2260 profile projectId (${h.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(w.articles).length} articles, ${Object.keys(w.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${h.name}" (created on first /publish)`}),t.push(Oi(Ui())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${Ui()}`,fix:"Reinstall document360-writer (broken install)"});let R=_e(e);if((Oi(Eu(e))||R.status!=="unset")&&(R.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${oe})`}):R.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${R.completedVersion}, current is v${oe}`,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)"})),b&&(!fr(b)||b.refreshToken)){let k={profile:h.name,connection:h.connection};try{await vu(k);let C=await $u(k,"/v3/projects");t.push({level:"ok",label:`API reachable (${h.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"})}}return t}function Wi(e){let t=[""];for(let r of e){let s=r.level==="ok"?E("\u2713"):r.level==="warn"?U("\u26A0"):$("\u2717");t.push(` ${s} ${r.label}${r.detail?f(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${f("fix:")} ${I(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?E(`\u2713 ${o===0?"All checks passed":`Healthy (${o} warning${o===1?"":"s"})`}`):$(`\u2717 ${n} problem${n===1?"":"s"} found`)),t.push(""),t}async function qt(e,t){console.log(f("Running checks\u2026"));for(let n of Wi(await Mi(t.cwd)))console.log(n);return{kind:"continue"}}var On=bo(()=>{"use strict";Ke();W()});import{Command as Yp}from"commander";import{createRequire as zp}from"node:module";import{AUTH_MODES as Kp}from"document360-engine";import{input as vl}from"@inquirer/prompts";import{loginPkce as Cl,refreshTokens as Pl,toStoredTokens as ys,clearTokens as Tl,decodeJwtClaims as ws,isExpired as Sl,loadTokens as Rl,saveTokens as ks,resolveActiveProfile as fn,setProfileProject as Dl,readProjectConfig as jl}from"document360-engine";W();import{select as ul}from"@inquirer/prompts";import{resolveActiveProfile as dl,setProfileProject as pl,resolveProjectId as fl,listWorkspaces as ml}from"document360-engine";async function It(e,t){let n=dl(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??fl(o);return{workspaces:await ml(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var ps=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function xo(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 pn(e,t,n,o,r){pl(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function fs(e,t,n){let o;try{o=await It(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=xo(o.workspaces,t);return r?(pn(e,o.profile,o.projectId,r.id,r.name),console.log(E(`\u2713 Workspace set to "${r.name??r.id}" for profile "${o.profile}".`)),0):(console.log($(`No workspace matches "${t}". Available: ${o.workspaces.map(s=>s.name??s.id).join(", ")}`)),1)}async function ht(e,t){let n;try{n=await It(e,t)}catch(b){console.log($(`Could not list workspaces: ${b.message}`));return}let{workspaces:o,projectId:r,profile:s,current:c}=n;if(o.length===0){console.log(f("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===c?I("\u25CF"):" "} ${ps(b)} ${f(b.id)}`);console.log(f("Run: d360-writer workspace use <name>"));return}let p=await ul({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${ps(b)}${b.id===c?" (current)":""}`,value:b.id}))}),h=o.find(b=>b.id===p);pn(e,s,r,p,h?.name),console.log(E(`\u2713 Workspace set to "${h?.name??p}" for profile "${s}".`))}W();import{select as hl}from"@inquirer/prompts";import{resolveActiveProfile as gl,setProfileProject as wl,listProjects as yl}from"document360-engine";async function gt(e,t){let n=gl(e,t),o={profile:n.name,connection:n.connection};return{projects:await yl(o),profile:n.name,environment:n.connection.name,current:n.project.projectId}}var ms=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function hs(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 $o(e,t,n,o){wl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function gs(e,t){let n;try{n=await gt(e,t)}catch(h){console.log($(`Could not list projects: ${h.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(f("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let h of o)console.log(` ${h.id===s?I("\u25CF"):" "} ${ms(h)} ${f(h.id)}`);console.log(f("Run: d360-writer project use <name>"));return}let c=await hl({message:"Select the Document360 project for this repo:",choices:o.map(h=>({name:`${ms(h)}${h.id===s?" (current)":""}`,value:h.id}))}),p=o.find(h=>h.id===c);$o(e,r,c,p?.name),console.log(E(`\u2713 Project set to "${p?.name??c}" for profile "${r}". Next: pick a workspace.`))}W();import kl from"picocolors";function bl(e=process.env){return e.FORCE_HYPERLINK==="0"||!kl.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 xl(e,t=e,n){return bl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var $l=/https?:\/\/[^\s\x1b]+/g;function Nt(e,t){return e.replace($l,n=>xl(n,n,t))}function bs(e){return{...ws(e.idToken)??{},...ws(e.accessToken)??{}}}function mn(e){let t=bs(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 hn(e){let t=fn(process.cwd(),e.profile),n=t.connection;console.log(f(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Cl(n,{manual:e.manual,promptForRedirect:s=>vl({message:s})},s=>console.log(Nt(s))),r=ys(t.name,o);if(ks(r),await vo(r,t.name,s=>console.log(f(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${mn(r)}`)),console.log(f(` access token expires: ${r.expiresAt}`)),console.log(f(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{jl(process.cwd())?.profiles?.[t.name]&&(console.log(""),await ht(process.cwd(),t.name))}catch{}}async function vo(e,t,n){let r=bs(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if(fn(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await gt(process.cwd(),t);c=p.find(h=>h.id===r)?.name}catch{}Dl(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function xs(e){let t=fn(process.cwd(),e.profile),n=t.connection,o=Rl(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${I(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${mn(o)}`),Sl(o))if(o.refreshToken)try{let r=ys(t.name,await Pl(n,o.refreshToken));ks(r),console.log(E(`\u2713 Session refreshed \u2014 expires ${r.expiresAt}`))}catch(r){console.log(U(`Session expired and refresh failed (${r.message.slice(0,120)})`)),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(U("Session expired (no refresh token).")),console.log(f(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(f(` expires: ${o.expiresAt}`))}async function $s(e){let t=fn(process.cwd(),e.profile);Tl(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(f(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as vs,writeProjectConfig as Al,resolveActiveProfile as El,loadTokens as Il,isExpired as Nl}from"document360-engine";function gn(e){let t=vs(e);if(!t?.profiles||Object.keys(t.profiles).length===0){console.log($("No profiles in .d360-writer.json. Run: d360-writer init")),process.exitCode=1;return}console.log("");for(let[n,o]of Object.entries(t.profiles)){let r=n===t.defaultProfile?I("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=Il(n),h=p?Nl(p)&&!p.refreshToken?U("expired"):f("logged in"):f("not logged in");console.log(`${r}${I(n)} \u2192 ${c}${s} [${h}]`)}console.log(""),console.log(f("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function wn(e,t){let n=vs(e);if(!n?.profiles?.[t]){let r=n?.profiles?Object.keys(n.profiles).join(", "):"(none \u2014 run init)";console.log($(`Unknown profile "${t}". Available: ${r}`)),process.exitCode=1;return}n.defaultProfile=t,Al(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function yn(e,t){try{let n=El(e,t);console.log(""),console.log(`Profile ${I(n.name)}${n.production?U(" \u26A0 PRODUCTION"):""}`),console.log(f(` api: ${n.connection.apiUrl}`)),console.log(f(` identity: ${n.connection.authorizationUrl}`)),console.log(f(` clientId: ${n.connection.clientId}`)),console.log(f(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(f(` project: ${n.project.projectId??"(set at login)"}`)),console.log(f(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as _l,readdirSync as Ol,statSync as Ul}from"node:fs";import{join as Ll}from"node:path";import{apiLogDir as Ml}from"document360-engine";function Cs(){let e=Ml();if(console.log(""),console.log(`Document360 API logs: ${I(e)}`),!_l(e)){console.log(f(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=Ol(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();t.length===0&&console.log(f(" No logs yet \u2014 they appear after the first Document360 API call."));for(let n of t.slice(0,14)){let o=(Ul(Ll(e,n)).size/1024).toFixed(1);console.log(` ${n} ${f(`${o} KB`)}`)}console.log(""),console.log(f("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(f("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as Wl,resolveAuth as Fl,findByName as Hl,slugify as ql,touchSession as Bl,upsertSession as Gl,resolveActiveProfile as Vl}from"document360-engine";async function Ps(e,t,n,o,r,s){let c=Fl(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(f("Using your Claude subscription (no API key set)."));let p=null;try{p=Vl(e,r)}catch(k){console.error($(`Document360 profile error: ${k.message}`)),process.exit(2)}p.production&&(console.error(U(`\u26A0 Profile "${p.name}" is PRODUCTION.`)),s||(console.error($("Refusing to run against a production profile without --yes.")),process.exit(2)),console.error(f(" --yes given \u2014 proceeding against production.")));let h;if(o){let k=Hl(e,o);k||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(f("List sessions inside the REPL with /resume.")),process.exit(2)),h=k.uuid,console.error(f(`Resuming "${k.name}"`))}let b=Wl({cwd:e,resume:h,profileName:r,allowProdWrites:s===!0}),w=h??null,R=1;for await(let k of b.send(t))switch(k.type){case"session":if(!w){w=k.sessionId;let C=new Date().toISOString();Gl({uuid:w,name:ql(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:C,updatedAt:C})}break;case"text":process.stdout.write(k.delta);break;case"tool":console.error(ee(` \u2699 ${k.name}`));break;case"result":R=k.ok?0:1,console.error(f(`(${k.inputTokens}\u2192${k.outputTokens} tokens`+(k.costUsd>0?`, $${k.costUsd<.01?k.costUsd.toFixed(4):k.costUsd.toFixed(2)}`:"")+")")),k.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${k.message}`)),process.exit(1)}w&&Bl(w),process.stdout.write(`
182
182
  `),process.exit(R)}import{createInterface as xd}from"node:readline/promises";import{createSession as Dr,resolveAuth as $d,getSession as vd,setTitle as Cd,slugify as Pd,touchSession as pa,upsertSession as Td,generateTitle as Sd,resolveActiveProfile as fa,resolveModelSetting as Rd,readProjectConfig as Dd,decodeJwtClaims as ua,isExpired as jd,loadTokens as Ad}from"document360-engine";var _t=[{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 [--all|--scope <cat>|<path>] [--run]",desc:"Author the planned articles in parallel (bare = preview + cost; --run starts)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit",desc:"Gap analysis: code vs docs vs Document360 (what changed)",group:"publish"},{name:"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]",desc:"Drift report local vs Document360; pull portal edits",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"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"}],Yl=[{key:"start",label:"Start here"},{key:"docs",label:"Write & screenshots"},{key:"publish",label:"Publish & keep in sync"},{key:"setup",label:"Setup & health"},{key:"session",label:"Session"}];function kn(){let e=Math.max(..._t.map(n=>n.usage.length))+2,t=["document360-writer \u2014 commands","","New here? Four steps from a fresh repo to published docs:"," 1. /init \u2192 connect, scaffold config, AND print a one-paste hand-off prompt for your source repo"," 2. run that prompt in your repo's coding agent (Claude Code / Codex / Cursor)",' 3. "write the docs for this repo" \u2192 back here, the agent authors the articles'," 4. /publish \u2192 dual-publish to Document360",""," Screenshots are optional \u2014 add them anytime:"," /screenshot --all \u2192 d360-capture capture \u2192 re-/publish"];for(let{key:n,label:o}of Yl){t.push("",o);for(let r of _t.filter(s=>s.group===n))t.push(` ${r.usage.padEnd(e)}${r.desc}`)}return t.push("","Tip: anything not starting with / is sent to the agent."),t}function Ts(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return _t.filter(n=>n.name.startsWith(t))}function Ss(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}async function Co(){console.log("");for(let e of kn())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 zl}from"document360-engine";async function Rs(e,t){let n=t.currentUuid(),o=n?zl(n):void 0;return console.log(o?f(`
183
183
  (conversation reset \u2014 "${o.name}" is still available via /resume)
184
184
  `):f(`
@@ -249,7 +249,7 @@ Articles:
249
249
  `);return{lines:s.slice(0,t).map(c=>fe(c,Rr)),hidden:Math.max(0,s.length-t)}}function qn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Bn(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 Gn(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 Ed=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Id(e,t,n,o){if(Ed.test(e))try{let r=fa(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Bn(t,n),p=Gn(n);e.endsWith("publish_article")&&p&&console.log(I(` \u2B95 Live: ${p}`)),c&&s&&console.log(I(` \u2B95 Preview: ${qn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function ma(e=process.cwd(),t="auto",n){let o=$d(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${I("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${I('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),Nd(e,n),o.kind==="subscription"&&(o.stored?console.log(f(" Using your Claude subscription (no API key set).")):console.log(f(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=Dr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=xd({input:process.stdin,output:process.stdout}),h=[],b=null,w=!1;p.on("line",C=>{if(b){let P=b;b=null,P(C)}else h.push(C)}),p.on("close",()=>{if(w=!0,b){let C=b;b=null,C(null)}});function R(){return h.length>0?Promise.resolve(h.shift()):w?Promise.resolve(null):(process.stdout.write(I("> ")),new Promise(C=>{b=C}))}let k={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Dr({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async C=>s.setModel(C),withPausedInput:async C=>{p.pause();try{return await C()}finally{p.resume()}}};try{for(;;){let C=await R();if(C===null)break;let P=C.trim();if(P){if(P.startsWith("/")){let N=ia(P);if(!N)continue;let O=sa[N.name];if(!O){console.log($(`Unknown command: /${N.name}`)),console.log(f("Type /help for the list."));continue}let q=await O(N.args,k);if(q.kind==="exit")break;if(q.kind==="clear"){k.restartAgent();continue}if(q.kind==="allow-prod"){r=!0,k.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(q.kind==="resume"){s.close(),s=Dr({cwd:e,resume:q.uuid,profileName:n,allowProdWrites:r});let te=vd(q.uuid);c={uuid:q.uuid,firstPrompt:te?.firstPrompt??null,titleFired:!0},pa(q.uuid),console.log(E(`\u2713 Resumed "${q.name}"`)),console.log("");continue}q.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=q.display??q.prompt),await da(s,q.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=P),await da(s,P,o,c,e)}}}finally{s.close(),p.close()}}function Nd(e,t){console.log(""),console.log(Et("document360-writer")),console.log(f(` cwd: ${e}`));let n=Rd(e);if(console.log(f(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(_d(e,t)),!Dd(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{vn(e);for(let o of Cn(e))console.log(U(` ${o}`))}catch{}try{let o=vt($t(e));o&&console.log(U(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(f(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function _d(e,t){try{let n=fa(e,t),o=n.production?U(" \u26A0 PRODUCTION"):"",r=Ad(n.name);if(!r)return f(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...ua(r.idToken)??{},...ua(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return jd(r)&&!r.refreshToken?U(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):f(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return f(` Document360: ${n.message.split(".")[0]}`)}}function Od(){console.error(""),console.error(`Sign in with your Claude subscription: run ${I("claude")} once, then retry.`),console.error(` (No Claude Code? ${I("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${I("https://console.anthropic.com/settings/keys")}`)}function Ud(e,t,n){e.uuid=t;let o=new Date().toISOString();Td({uuid:t,name:Pd(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function Ld(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||Sd(o,t).then(r=>{r&&Cd(n,r)}).catch(()=>{})}async function da(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))Md(c,o,r,n,s)}function Md(e,t,n,o,r){switch(e.type){case"session":t.uuid||Ud(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=Fn(e.name,e.input);s&&(process.stdout.write(`
250
250
 
251
251
  `),console.log(`${E("\u25CF")} ${xe(s.title)}${s.arg!==null?ee(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=Xe(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(ee(` \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(f(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=Hn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:ee;c.lines.forEach((h,b)=>console.log(p((b===0?" \u23BF ":" ")+h))),c.hidden>0&&console.log(f(` \u2026 +${c.hidden} lines`)),e.isError||Id(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
252
- `),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(pa(t.uuid),t.titleFired||Ld(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Od();break}}import{render as qp}from"ink";import{resolveAuth as Bp}from"document360-engine";import{useCallback as Y,useEffect as ve,useMemo as _r,useRef as X,useState as F}from"react";import{Box as Z,Text as T,useApp as Qd,useInput as Zd,useStdout as ep}from"ink";import{existsSync as Yt,readFileSync as Or,readdirSync as qa}from"node:fs";import{basename as zt,isAbsolute as tp,join as Kt}from"node:path";import{createSession as Na,classifyClaudeAuth as Ba,CLAUDE_CODE_SETUP_HINT as np,loginPkce as op,toStoredTokens as rp,saveTokens as sp,getAccessToken as ip,resolveActiveProfile as ce,resolveProjectId as ap,getArticle as lp,decodeJwtClaims as Ct,isExpired as De,loadTokens as Me,clearTokens as cp,clearProfileProject as up,setTitle as dp,slugify as pp,touchSession as Ur,upsertSession as fp,generateTitle as _a,findByName as mp,listSessions as hp,renameSession as gp,suggestNextAction as wp,readProjectConfig as Q,writeProjectConfig as yp,resolveModelSetting as Hr,loadProfileMap as Lr,applyPull as kp,computeSyncStatus as Mr,planPull as bp,inventoryRepo as xp,knownEnvironments as $p,resolveEnvironment as vp,planPartitions as Wr,partitionEvenly as Cp,screenshotPlaceholderIds as Pp,trackedArticlePaths as Tp,runPartitioned as Jn,estimateBulkCost as Oa,resolveModelForOperation as Qn,readDocsPlan as Sp,checkForUpdate as Rp,detectInstallKind as Dp,isSelfUpdatable as jp,devHintsGuidePath as Ua,toolFeedbackPath as Ap,DEFAULT_DOCS_DIR as Ga,setProfileProject as Ep}from"document360-engine";Ke();import{spawn as ha}from"node:child_process";function Wd(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Fd(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?ha([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):ha(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 ga(e){for(let[t,n]of Wd())if(await Fd(t,n,e))return!0;return!1}var Hd=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function jr(e,t){if(t.closed)return e;let n=e.split(`
252
+ `),console.log(f(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(pa(t.uuid),t.titleFired||Ld(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&Od();break}}import{render as Bp}from"ink";import{resolveAuth as Gp}from"document360-engine";import{useCallback as Y,useEffect as ve,useMemo as _r,useRef as X,useState as F}from"react";import{Box as Z,Text as T,useApp as Qd,useInput as Zd,useStdout as ep}from"ink";import{existsSync as Yt,readFileSync as Or,readdirSync as qa}from"node:fs";import{spawnSync as tp}from"node:child_process";import{basename as zt,isAbsolute as np,join as Kt}from"node:path";import{createSession as Na,classifyClaudeAuth as Ba,CLAUDE_CODE_SETUP_HINT as op,loginPkce as rp,toStoredTokens as sp,saveTokens as ip,getAccessToken as ap,resolveActiveProfile as ce,resolveProjectId as lp,getArticle as cp,decodeJwtClaims as Ct,isExpired as De,loadTokens as Me,clearTokens as up,clearProfileProject as dp,setTitle as pp,slugify as fp,touchSession as Ur,upsertSession as mp,generateTitle as _a,findByName as hp,listSessions as gp,renameSession as wp,suggestNextAction as yp,readProjectConfig as Q,writeProjectConfig as kp,resolveModelSetting as Hr,loadProfileMap as Lr,applyPull as bp,computeSyncStatus as Mr,planPull as xp,inventoryRepo as $p,knownEnvironments as vp,resolveEnvironment as Cp,planPartitions as Wr,partitionEvenly as Pp,screenshotPlaceholderIds as Tp,trackedArticlePaths as Sp,runPartitioned as Jn,estimateBulkCost as Oa,resolveModelForOperation as Qn,readDocsPlan as Rp,checkForUpdate as Dp,detectInstallKind as jp,isSelfUpdatable as Ap,devHintsGuidePath as Ua,toolFeedbackPath as Ep,DEFAULT_DOCS_DIR as Ga,setProfileProject as Ip}from"document360-engine";Ke();import{spawn as ha}from"node:child_process";function Wd(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function Fd(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?ha([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):ha(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 ga(e){for(let[t,n]of Wd())if(await Fd(t,n,e))return!0;return!1}var Hd=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function jr(e,t){if(t.closed)return e;let n=e.split(`
253
253
  `),o=!1;for(let r=0;r<n.length&&!t.closed;r++){let s=n[r];if(!t.cueSeen){Hd.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
254
  `)}import{existsSync as qd,mkdirSync as Bd,readFileSync as Gd,writeFileSync as Vd}from"node:fs";import{join as wa}from"node:path";import{writerDir as Yd}from"document360-engine";function ya(e){return wa(Yd(e),".sessions")}function ka(e,t){return wa(ya(e),`${t}.json`)}function ba(e,t,n){try{Bd(ya(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Vd(ka(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Ar(e,t){try{let n=ka(e,t);if(!qd(n))return[];let o=JSON.parse(Gd(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var zd=e=>`\x1B]0;${e}\x07`,Kd=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function xa(e){process.stdout.isTTY&&process.stdout.write(e)}function Gt(e){xa(zd(e))}function Vn(e){xa(Kd(e))}var Yn=["\xB7 "," \xB7"],Er="\u{1F7E3}";On();var Xd=/^(?:\d+[.)]|[-*•])\s+/;function $a(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
255
255
  `)){let c=s.trim().replace(Xd,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let h=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!h||!o.has(h[1].toLowerCase()))continue;let b=`/${h[1].toLowerCase()}${h[2]?` ${h[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}W();function Vt(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Re(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function Ir(e){return e.replace(/^[\w.-]+\//,"")}var zn=16,va={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Nr(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Ca(e,t){let n=Nr(t);return e.some(r=>r.trim()===t.trim()||!!n&&Nr(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Nr(r)===n)):[]}var Jd=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Pa(e){return e.replace(/\r\n?/g,`
@@ -259,33 +259,33 @@ Articles:
259
259
  `)){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 Xn(e,t){let n=0;for(let o=0;o<e.length&&e[o].start<=t;o++)n=o;return n}function ja(e,t,n){let o=Xn(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 Aa(e,t,n){let o=e[Xn(e,t)];return n==="start"?o.start:o.end}function Ea(e,t,n){let o=Math.max(1,n),r=e.split(`
260
260
  `),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 h=s-t;return{text:[h>0?p.slice(h*o):p,...r.slice(c+1)].join(`
261
261
  `),truncated:c>0||h>0}}}return{text:e,truncated:!1}}function Ia(e){let t=!1,n=0,o=0;for(let r of e.split(`
262
- `)){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 Fr,jsx as S,jsxs as H}from"react/jsx-runtime";var Ip={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},La=` 1. /init \u2014 pick your Document360 environment & scaffold config
262
+ `)){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 Fr,jsx as S,jsxs as H}from"react/jsx-runtime";var Np={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},La=` 1. /init \u2014 pick your Document360 environment & scaffold config
263
263
  2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
264
- 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function Np(e,t,n,o){let r=Ba(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=Hr(e),p=Q(e),h=(p?.docsDir??Ga).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,w={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Ip[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return w;try{let R=ce(e,o);w.profile=R.name,w.apiUrl=R.connection.apiUrl,w.prod=R.production,w.project=R.project.projectName??R.project.projectId??"(chosen at login)";let k=Me(R.name);if(k){let C={...Ct(k.idToken)??{},...Ct(k.accessToken)??{}},P=C.email??C.preferred_username??"signed in";De(k)?k.refreshToken&&(w.who=P,w.loggedOut=!1,w.sessionHint="session expired \u2014 refreshing\u2026"):(w.who=P,w.loggedOut=!1,w.sessionHint=`session valid until ${new Date(k.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return w}function _p(e,t){try{let n=ce(e,t),o=Me(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ct(o.idToken)??{},...Ct(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return De(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 Ma=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],eo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Op="Ask me to write or update an article\u2026";function Zn({ch:e,dim:t}){let[n,o]=F(!0);return ve(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),S(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Up=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Wa(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Lp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fa(e){try{return qa(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Ha(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Fa(Kt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Fa(Kt(e,o)))}function Mp({startTime:e,chars:t}){let[n,o]=F(0);ve(()=>{let h=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(h)},[]);let r=eo[n%eo.length],s=Ma[Math.floor(n/16)%Ma.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return H(Z,{children:[S(T,{color:V,children:` ${r} ${s}\u2026 `}),S(T,{color:"gray",children:`(${Mt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Wp=12e4;function Fp({p:e}){let[t,n]=F(0);ve(()=>{let O=setInterval(()=>n(q=>q+1),150);return()=>clearInterval(O)},[]);let o=eo[t%eo.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>=Wp,h=e.verb??"Converting",b=e.unit??"article",w=e.rows.reduce((O,q)=>O+q.items,0),R=h.toLowerCase(),k=e.rows,C=0;if(k.length>zn){let O=k.findIndex(te=>te.status==="active"||te.status==="pending"),q=Math.max(0,Math.min(O-2,k.length-zn));C=k.slice(0,q).filter(te=>te.status==="done").length,k=k.slice(q,q+zn)}let P=Math.min(40,Math.max(...k.map(O=>Ir(O.label).length),0)),N=O=>O==="failed"?"red":O==="active"?V:void 0;return H(Z,{flexDirection:"column",children:[H(Z,{children:[S(T,{color:V,children:` ${o} ${h} ${w} ${b}${w===1?"":"s"} `}),S(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Mt(r)} \xB7 esc to stop`})]}),C>0&&S(T,{dimColor:!0,children:` \u2714 +${C} done`}),k.map(O=>H(T,{color:N(O.status),dimColor:O.status==="done"||O.status==="pending",children:[` ${va[O.status]} ${Ir(O.label).padEnd(P)}`,O.status!=="pending"?` (${O.items} ${b}${O.items===1?"":"s"})`:"",O.status==="active"?` \u2190 ${R}\u2026`:""]},O.label)),p&&S(T,{color:"yellow",children:` \u26A0 no activity for ${Mt(s)} \u2014 press esc to stop if it's wedged`})]})}var Hp=10800*1e3;function Va({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Qd(),[s,c]=F(n),[p,h]=F(null),[b,w]=F({text:"",pos:0}),R=b.text,k=Y(l=>{w(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),C=Y(l=>{w(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),P=Y(()=>{w(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Da(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,O]=F(!1),[q,te]=F(!1),[Ce,re]=F(0),[ke,se]=F(null),[Pt,B]=F([]),Qe=X(0),[Xa,Xt]=F(!1),[Ja,Ze]=F(0),We=X(0),[Tt,et]=F(0),[tt,Jt]=F(null),Gr=X(new Map),Qa=X(0),nt=X([]),me=X(null);me.current===null&&(me.current=Na({cwd:e,profileName:s,allowProdWrites:!1}));let Pe=X({uuid:null,firstPrompt:null,titleFired:!1}),Qt=X(new Map),ot=X(!1),to=X([]),Ae=X([]),no=X(null),[Vr,rt]=F(null),[Fe,He]=F(null),[Te,st]=F(null),[Ee,it]=F(null),[ie,at]=F(null),[he,lt]=F(null),[qe,ct]=F(null),[Yr,Zt]=F(null),[ge,Be]=F(null),[ue,ut]=F(null),[zr,oo]=F([]),Ge=X([]),St=X(!1),we=X(null),[Kr,J]=F(null),en=X(!1),tn=X(null),Rt=X(null),[ye,Ve]=F(null),[Xr,dt]=F(0),[Jr,pt]=F(0),[Za,Qr]=F(0),ro=_r(()=>{try{return Hr(e).model??"auto"}catch{return null}},[e,Za]),{stdout:be}=ep(),[,el]=F(0),Zr=X(`${be.columns??80}x${be.rows??24}`),Ie=Y(()=>Math.max(20,(be.columns??80)-1),[be]),u=Y(l=>{nt.current.push(l),console.log(Oo(l,Ie()))},[Ie]),[so,io]=F(null),ft=Y(l=>{io(l),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),ao=X(!1),lo=Y(async()=>{try{if(ao.current||!jp(Dp())||Q(e)?.mode==="engineer")return;let l=await Rp({pkg:Je,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;ao.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Je} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),(await Mn()).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),B(a=>a.includes("/exit")?a:[...a,"/exit"])):u({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Ln}`})}catch{}},[e,o,u]),co=Y(l=>{let i=Se(e,s);return i.ok?!0:(u({kind:"note",tone:"warn",text:i.reason}),Rt.current=l,B(["/login"]),!1)},[e,s,u]),[uo,po]=F(null),Dt=X(!0),nn=X(0);ve(()=>{let l=setInterval(()=>{if(N||Dt.current){nn.current=0;return}try{if(!Yt(Ua(e)))return;if(_e(e).status==="current"){Dt.current=!0,nn.current=0,u({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."}),io(null),se("write the docs for this repo");return}nn.current+=1;let i=nn.current;(i===1||i%7===0)&&u({kind:"note",tone:"info",text:Us(e)?"\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.":"\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."})}catch{}},4e3);return()=>clearInterval(l)},[e,N,u]),ve(()=>{let l=`d360-writer \xB7 ${Vr??zt(e)}`;if(!N){Vn(0),Gt(`${Er} ${l}`);return}Vn(3);let i=0;Gt(`${Yn[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%Yn.length,Gt(`${Yn[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,Vr]),ve(()=>()=>Vn(0),[]),ve(()=>{u({kind:"banner",info:Np(e,o,t,s)});let l=Ba(t).state==="missing";if(l&&u({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.
265
- ${np}
264
+ 3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function _p(e,t,n,o){let r=Ba(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=Hr(e),p=Q(e),h=(p?.docsDir??Ga).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${h}/ + config`,w={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:Np[c.source],who:null,sessionHint:null,profile:"\u2014",apiUrl:"\u2014",project:"\u2014",cwd:e,prod:!1,loggedOut:!0,configured:p!==null,mode:b};if(p===null)return w;try{let R=ce(e,o);w.profile=R.name,w.apiUrl=R.connection.apiUrl,w.prod=R.production,w.project=R.project.projectName??R.project.projectId??"(chosen at login)";let k=Me(R.name);if(k){let C={...Ct(k.idToken)??{},...Ct(k.accessToken)??{}},P=C.email??C.preferred_username??"signed in";De(k)?k.refreshToken&&(w.who=P,w.loggedOut=!1,w.sessionHint="session expired \u2014 refreshing\u2026"):(w.who=P,w.loggedOut=!1,w.sessionHint=`session valid until ${new Date(k.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return w}function Op(e,t){try{let n=ce(e,t),o=Me(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Ct(o.idToken)??{},...Ct(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return De(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 Ma=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],eo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Up="Ask me to write or update an article\u2026";function Zn({ch:e,dim:t}){let[n,o]=F(!0);return ve(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),S(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var Lp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function Wa(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Mp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fa(e){try{return qa(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function Ha(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>Fa(Kt(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&Fa(Kt(e,o)))}function Wp({startTime:e,chars:t}){let[n,o]=F(0);ve(()=>{let h=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(h)},[]);let r=eo[n%eo.length],s=Ma[Math.floor(n/16)%Ma.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return H(Z,{children:[S(T,{color:V,children:` ${r} ${s}\u2026 `}),S(T,{color:"gray",children:`(${Mt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Fp=12e4;function Hp({p:e}){let[t,n]=F(0);ve(()=>{let O=setInterval(()=>n(q=>q+1),150);return()=>clearInterval(O)},[]);let o=eo[t%eo.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>=Fp,h=e.verb??"Converting",b=e.unit??"article",w=e.rows.reduce((O,q)=>O+q.items,0),R=h.toLowerCase(),k=e.rows,C=0;if(k.length>zn){let O=k.findIndex(te=>te.status==="active"||te.status==="pending"),q=Math.max(0,Math.min(O-2,k.length-zn));C=k.slice(0,q).filter(te=>te.status==="done").length,k=k.slice(q,q+zn)}let P=Math.min(40,Math.max(...k.map(O=>Ir(O.label).length),0)),N=O=>O==="failed"?"red":O==="active"?V:void 0;return H(Z,{flexDirection:"column",children:[H(Z,{children:[S(T,{color:V,children:` ${o} ${h} ${w} ${b}${w===1?"":"s"} `}),S(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${Mt(r)} \xB7 esc to stop`})]}),C>0&&S(T,{dimColor:!0,children:` \u2714 +${C} done`}),k.map(O=>H(T,{color:N(O.status),dimColor:O.status==="done"||O.status==="pending",children:[` ${va[O.status]} ${Ir(O.label).padEnd(P)}`,O.status!=="pending"?` (${O.items} ${b}${O.items===1?"":"s"})`:"",O.status==="active"?` \u2190 ${R}\u2026`:""]},O.label)),p&&S(T,{color:"yellow",children:` \u26A0 no activity for ${Mt(s)} \u2014 press esc to stop if it's wedged`})]})}var qp=10800*1e3;function Va({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Qd(),[s,c]=F(n),[p,h]=F(null),[b,w]=F({text:"",pos:0}),R=b.text,k=Y(l=>{w(i=>{let a=typeof l=="function"?l(i.text):l;return{text:a,pos:a.length}})},[]),C=Y(l=>{w(i=>({text:i.text.slice(0,i.pos)+l+i.text.slice(i.pos),pos:i.pos+l.length}))},[]),P=Y(()=>{w(l=>{if(l.pos===0)return l;let i=l.text.slice(0,l.pos),a=Da(i)??i.slice(0,-1);return{text:a+l.text.slice(l.pos),pos:a.length}})},[]),[N,O]=F(!1),[q,te]=F(!1),[Ce,re]=F(0),[ke,se]=F(null),[Pt,B]=F([]),Qe=X(0),[Xa,Xt]=F(!1),[Ja,Ze]=F(0),We=X(0),[Tt,et]=F(0),[tt,Jt]=F(null),Gr=X(new Map),Qa=X(0),nt=X([]),me=X(null);me.current===null&&(me.current=Na({cwd:e,profileName:s,allowProdWrites:!1}));let Pe=X({uuid:null,firstPrompt:null,titleFired:!1}),Qt=X(new Map),ot=X(!1),to=X([]),Ae=X([]),no=X(null),[Vr,rt]=F(null),[Fe,He]=F(null),[Te,st]=F(null),[Ee,it]=F(null),[ie,at]=F(null),[he,lt]=F(null),[qe,ct]=F(null),[Yr,Zt]=F(null),[ge,Be]=F(null),[ue,ut]=F(null),[zr,oo]=F([]),Ge=X([]),St=X(!1),we=X(null),[Kr,J]=F(null),en=X(!1),tn=X(null),Rt=X(null),[ye,Ve]=F(null),[Xr,dt]=F(0),[Jr,pt]=F(0),[Za,Qr]=F(0),ro=_r(()=>{try{return Hr(e).model??"auto"}catch{return null}},[e,Za]),{stdout:be}=ep(),[,el]=F(0),Zr=X(`${be.columns??80}x${be.rows??24}`),Ie=Y(()=>Math.max(20,(be.columns??80)-1),[be]),u=Y(l=>{nt.current.push(l),console.log(Oo(l,Ie()))},[Ie]),[so,io]=F(null),ft=Y(l=>{io(l),u({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[u]),ao=X(!1),lo=Y(async()=>{try{if(ao.current||!Ap(jp())||Q(e)?.mode==="engineer")return;let l=await Dp({pkg:Je,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;ao.current=!0,u({kind:"note",tone:"info",text:`\u2B06 Updating ${Je} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),(await Mn()).ok?(u({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),B(a=>a.includes("/exit")?a:[...a,"/exit"])):u({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Ln}`})}catch{}},[e,o,u]),co=Y(l=>{let i=Se(e,s);return i.ok?!0:(u({kind:"note",tone:"warn",text:i.reason}),Rt.current=l,B(["/login"]),!1)},[e,s,u]),[uo,po]=F(null),Dt=X(!0),nn=X(0);ve(()=>{let l=setInterval(()=>{if(N||Dt.current){nn.current=0;return}try{if(!Yt(Ua(e)))return;if(_e(e).status==="current"){Dt.current=!0,nn.current=0,u({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."}),io(null),se("write the docs for this repo");return}nn.current+=1;let i=nn.current;(i===1||i%7===0)&&u({kind:"note",tone:"info",text:Us(e)?"\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.":"\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."})}catch{}},4e3);return()=>clearInterval(l)},[e,N,u]),ve(()=>{let l=`d360-writer \xB7 ${Vr??zt(e)}`;if(!N){Vn(0),Gt(`${Er} ${l}`);return}Vn(3);let i=0;Gt(`${Yn[0]} ${l}`);let a=setInterval(()=>{i=(i+1)%Yn.length,Gt(`${Yn[i]} ${l}`)},400);return()=>clearInterval(a)},[N,e,Vr]),ve(()=>()=>Vn(0),[]),ve(()=>{u({kind:"banner",info:_p(e,o,t,s)});let l=Ba(t).state==="missing";if(l&&u({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.
265
+ ${op}
266
266
  Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!Q(e)){u({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
267
- ${La}`}),B(l?["/doctor","/init"]:["/init"]);return}l&&B(["/doctor"]);try{let i=ce(e,s),a=Me(i.name);a&&De(a)&&a.refreshToken?ip({profile:i.name,connection:i.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),re(g=>g+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),B(["/login"])}):(!a||De(a))&&(u({kind:"note",tone:"warn",text:`Profile "${i.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"]))}catch{}try{let i=Q(e),a=ce(e,s),g=Me(a.name);i&&g&&!De(g)&&Ha(e,i.authoritativeSourceFiles)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),B(["/scope"]))}catch{}try{vn(e);let i=Cn(e);i.length&&(u({kind:"note",tone:"warn",text:i.join(`
268
- `)}),ft(ze()),Dt.current=!1)}catch{}try{let i=Q(e),a=ce(e,s),g=Me(a.name),d=!!g&&(!De(g)||!!g.refreshToken),m=!i||!Ha(e,i.authoritativeSourceFiles);if(i&&d&&m&&!l){let y=Lr(e,a.name),v=y?Object.keys(y.articles).length:0,D=vt($t(e));if(v>0){let j=D?["/catch-up","/audit"]:["/audit","/sync"],oe={"/catch-up":"write up everything your builder flagged","/audit":D?"also scan the code for other changes":"check the code for anything new or missing in the docs","/sync":"check Document360 for changes made there"},K=D?`\u{1F4CB} Your builder left ${D} for the docs:`:`\u{1F4DA} ${v} article${v===1?"":"s"} tracked for "${a.name}". What next?`;u({kind:"note",tone:"info",text:[K,...j.map((_,x)=>` ${x+1} ${_.padEnd(9)} ${oe[_]}`),"Or just tell me what to write or update."].join(`
269
- `)}),B(j)}else u({kind:"note",tone:"info",text:'\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.'}),se("write the docs for this repo"),B(D?["/catch-up","/audit"]:["/audit"])}}catch{}lo()},[]),ve(()=>{let l=setInterval(()=>{lo()},Hp);return()=>clearInterval(l)},[lo]),ve(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${be.columns??80}x${be.rows??24}`;g!==Zr.current&&(Zr.current=g,el(d=>d+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+ni(nt.current,Ie())+"\x1B[?2026l")},80))},400)};return be.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),be.off("resize",a)}},[be,Ie]);let Ye=Math.max(20,(be.columns??80)-1),es=_r(()=>_p(e,s),[e,s,Ce]),fo=(()=>{let l=Q(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=Kt(e,(l.docsDir??Ga).replace(/\/+$/,"")),a=(()=>{try{return Yt(i)&&qa(i).length>0}catch{return!1}})();try{let g=ce(e,s),d=Me(g.name);if(!(!!d&&!(De(d)&&!d.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:Op,isSetup:!1}:so?{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}})(),jt=Ts(R),ts=jt.length>0&&!N,mo=p!==null?Ea(p,8,Ye):null,on=ge?ge.paths.filter(l=>!ge.query||l.toLowerCase().includes(ge.query.toLowerCase())).slice(0,8):[],rn=ye?ye.sessions.filter(l=>{let i=ye.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],de=Y((l,i)=>{me.current?.close(),me.current=Na({cwd:e,resume:l,profileName:i??s,allowProdWrites:ot.current}),l||(Pe.current={uuid:null,firstPrompt:null,titleFired:!1},rt(null)),dt(0),pt(0)},[e,s]),ns=Y((l,i,a)=>{if(Up.test(l))try{let g=ce(e,s),d=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=Bn(i,a),y=[],v=Gn(a);l.endsWith("publish_article")&&v&&y.push(`Live: ${v}`),m&&d&&y.push(`Preview: ${qn(g.connection.portalUrl,d,m,g.project.languageCode??"en")}`),y.length>0&&u({kind:"link",lines:y})}catch{}},[e,s,u]),pe=Y(async(l,i)=>{Xt(!0),se(null),B([]),Zt(null),io(null),po(null);let a=++Qe.current;i?.quietUser||u({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Pe.current;g.firstPrompt||(g.firstPrompt=i?.display??l),We.current=Date.now(),Ze(0),O(!0),Qt.current.clear();let d="",m=!1,y=!1,v="",D={num:0,closed:!1,cueSeen:!1},j=null,oe=()=>{j||(j=setTimeout(()=>{j=null,h(v.length>0?v:null)},60))},K=()=>{j&&clearTimeout(j),j=null,h(null)},_=()=>{if(v.trim()){let x=jr(v.trimEnd(),D);u({kind:"assistant",text:x})}v="",K()};try{for await(let x of me.current.send(l))if(x.type==="session"){if(!g.uuid){g.uuid=x.sessionId;let A=new Date().toISOString(),M=pp(g.firstPrompt??"session");fp({uuid:x.sessionId,name:M,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:A,updatedAt:A}),rt(M)}}else if(x.type==="text"){v+=x.delta,d+=x.delta;let A=Ia(v);if(A>0){let M=v.slice(0,A).trimEnd();M&&u({kind:"assistant",text:jr(M,D)}),v=v.slice(A)}oe(),Ze(M=>M+x.delta.length)}else if(x.type==="tool"){m=!0;let A=Fn(x.name,x.input);A&&(_(),u({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),Qt.current.set(x.id,{name:x.name,input:x.input}))}else if(x.type==="article_diff"){let A=Xe(x.oldContent,x.newContent,Ie());A&&(_(),u({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(x.type==="tool_result"){x.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(x.output)&&(en.current=!0);let A=Qt.current.get(x.id);if(A){Qt.current.delete(x.id),_();let M=Hn(x.output,4,x.isError?void 0:A.name,A.input);u({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:x.isError}),x.isError||ns(A.name,A.input,x.output)}}else if(x.type==="result"){if(_(),dt(M=>M+x.outputTokens),pt(M=>M+x.costUsd),u({kind:"done",seconds:Math.round((Date.now()-We.current)/1e3),tokens:x.outputTokens,costUsd:x.costUsd,ok:x.ok}),!y&&!m&&!d.trim()&&!St.current&&u({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)."}),x.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let M=Ap(e);if(Yt(M)){let L=Or(M,"utf8").trim();L&&(po(L),u({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 A=x.ok?$a(d,_t.map(M=>M.name)):[];if(A.length>0?B(A):x.ok&&d.trim()&&wp(l,d,e).then(M=>{M&&Qe.current===a&&se(M)}).catch(()=>{}),g.uuid&&(Ur(g.uuid),!g.titleFired)){g.titleFired=!0;let M=g.uuid,L=g.firstPrompt;L&&_a(L,e).then(G=>{G&&(dp(M,G),rt(G))}).catch(()=>{})}}else x.type==="error"&&(_(),y=!0,x.kind==="auth"&&(en.current=!0),u({kind:"note",text:`agent error: ${x.message}`,tone:"error"}))}finally{O(!1),K(),re(x=>x+1),Pe.current.uuid&&ba(e,Pe.current.uuid,nt.current),en.current&&(en.current=!1,tn.current=i?.display??l,B(["/login"])),St.current&&(St.current=!1,Ge.current.length>0&&(u({kind:"note",tone:"info",text:`(${Ge.current.length} queued message(s) discarded)`}),Ge.current=[],oo([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,ns,Ie]),sn=Y(async l=>{let i=Wr(l),a=Qn(e,"standard");We.current=Date.now(),Ze(0),O(!0);let g=new AbortController;we.current=g,J({verb:"Publishing",total:i.length,done:0,active:[],rows:Vt(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Wt} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let d of Jn({cwd:e,partitions:i,promptFor:m=>Dn(m.paths),concurrency:Wt,profileName:s,allowProdWrites:ot.current,model:a.model,signal:g.signal}))if(d.type==="partition_status")d.status==="running"?J(m=>m&&{...m,active:[...m.active,d.label],rows:Re(m.rows,d.label,"active"),lastAt:Date.now()}):J(m=>m&&{...m,active:m.active.filter(y=>y!==d.label),done:m.done+1,rows:Re(m.rows,d.label,d.status==="done"?"done":"failed"),lastAt:Date.now()});else if(d.type==="partition_event")J(m=>{if(!m)return m;let y={...m,lastAt:Date.now()};return d.event.type==="tool"?y.tools=m.tools+1:d.event.type==="text"&&(y.chars=m.chars+d.event.delta.length),y});else if(d.type==="run_done"){pt(v=>v+d.totalCostUsd),dt(v=>v+d.results.reduce((D,j)=>D+j.outputTokens,0));let m=d.aborted?"Stopped. ":"",y=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+Wo(d.results,i,y).join(`
270
- `)})}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{we.current=null,J(null),O(!1),re(d=>d+1)}},[e,s,u,t]),ho=Y(async l=>{await pe(Mo(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await jn(e,s,l.replace(/\\/g,"/"));i.length>0&&(Zt(`Related articles not yet published (${i.length}):`),B([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,pe]),go=Y(l=>{let i=Me(l);if(!i||De(i)&&!i.refreshToken)return null;let a={...Ct(i.idToken)??{},...Ct(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),wo=Y((l,i)=>{if(i){let a=Q(e);a&&(a.defaultProfile=l,yp(a,e))}c(l),de(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),go(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"])),re(a=>a+1)},[e,u,de,go]),an=Y((l,i,a)=>{pn(e,l,i,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),de(),Lr(e,l)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({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:"}),u({kind:"note",tone:"info",text:kt(yt(e)).join(`
271
- `)}),ft(ze()),Dt.current=_e(e).status==="current",u({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,u,de,ft]),ln=Y(async l=>{let i;try{i=await It(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),B(["/workspace"]);return}if(i.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let d=g[0],m=i.workspaces.length-g.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),an(i.profile,i.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),B(["/workspace"])},[e,u,an]),os=Y((l,i)=>{$o(e,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),de(),ln(l)},[e,u,de,ln]),rs=Y(async l=>{let i;try{i=ce(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await gt(e,i.name),g=a.find(d=>d.id===i.project.projectId);g?.name&&Ep(e,i.name,{projectName:g.name})}catch{}await ln(i.name);return}u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),B(["/project"])}},[e,u,ln]),cn=Y(()=>{let l=Ae.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=Xe(l.oldContent,l.newContent,Ie());u(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."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,Ie]),ss=Y(l=>{if(Ae.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Ae.current.shift();try{kp({cwd:e,profileName:s},a),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Ae.current.length===0&&B(g=>g.length>0?g:["/sync"])}catch(g){u({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=Ae.current.shift();u({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Ae.current.length;return Ae.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return cn(),!0},[e,s,cn,u]),is=Y(l=>{let i=no.current;if(!i)return!1;if(no.current=null,se(null),Qe.current++,l.trim()!==i.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=Pr(e,i.targets);u({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 d of g)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return i.hadDevhints&&(u({kind:"note",tone:"warn",text:Pn().join(`
267
+ ${La}`}),B(l?["/doctor","/init"]:["/init"]);return}l&&B(["/doctor"]);try{let i=ce(e,s),a=Me(i.name);a&&De(a)&&a.refreshToken?ap({profile:i.name,connection:i.connection}).then(()=>{u({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),re(g=>g+1)}).catch(()=>{u({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),B(["/login"])}):(!a||De(a))&&(u({kind:"note",tone:"warn",text:`Profile "${i.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"]))}catch{}try{let i=Q(e),a=ce(e,s),g=Me(a.name);i&&g&&!De(g)&&Ha(e,i.authoritativeSourceFiles)&&(u({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),B(["/scope"]))}catch{}try{vn(e);let i=Cn(e);i.length&&(u({kind:"note",tone:"warn",text:i.join(`
268
+ `)}),ft(ze()),Dt.current=!1)}catch{}try{let i=Q(e),a=ce(e,s),g=Me(a.name),d=!!g&&(!De(g)||!!g.refreshToken),m=!i||!Ha(e,i.authoritativeSourceFiles);if(i&&d&&m&&!l){let y=Lr(e,a.name),v=y?Object.keys(y.articles).length:0,D=vt($t(e));if(v>0){let j=0;if(y?.lastAnalyzedCommit)try{let x=tp("git",["rev-list","--count",`${y.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:3e3});x.status===0&&(j=parseInt((x.stdout||"").trim(),10)||0)}catch{}let ne=D?["/catch-up","/audit"]:["/audit","/sync"],K={"/catch-up":"write up everything your builder flagged","/audit":D?"also scan the code for other changes":"check the code for anything new or missing in the docs","/sync":"check Document360 for changes made there"},_=D?`\u{1F4CB} Your builder left ${D} for the docs:`:j>0?`\u{1F4CB} ${j} code change${j===1?"":"s"} since your last docs check \u2014 /audit to see what needs updating:`:`\u{1F4DA} ${v} article${v===1?"":"s"} tracked for "${a.name}". What next?`;u({kind:"note",tone:"info",text:[_,...ne.map((x,A)=>` ${A+1} ${x.padEnd(9)} ${K[x]}`),"Or just tell me what to write or update."].join(`
269
+ `)}),B(ne)}else u({kind:"note",tone:"info",text:'\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.'}),se("write the docs for this repo"),B(D?["/catch-up","/audit"]:["/audit"])}}catch{}lo()},[]),ve(()=>{let l=setInterval(()=>{lo()},qp);return()=>clearInterval(l)},[lo]),ve(()=>{let l=null,i=null,a=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${be.columns??80}x${be.rows??24}`;g!==Zr.current&&(Zr.current=g,el(d=>d+1),i&&clearTimeout(i),i=setTimeout(()=>{i=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+ni(nt.current,Ie())+"\x1B[?2026l")},80))},400)};return be.on("resize",a),()=>{l&&clearTimeout(l),i&&clearTimeout(i),be.off("resize",a)}},[be,Ie]);let Ye=Math.max(20,(be.columns??80)-1),es=_r(()=>Op(e,s),[e,s,Ce]),fo=(()=>{let l=Q(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let i=Kt(e,(l.docsDir??Ga).replace(/\/+$/,"")),a=(()=>{try{return Yt(i)&&qa(i).length>0}catch{return!1}})();try{let g=ce(e,s),d=Me(g.name);if(!(!!d&&!(De(d)&&!d.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:Up,isSetup:!1}:so?{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}})(),jt=Ts(R),ts=jt.length>0&&!N,mo=p!==null?Ea(p,8,Ye):null,on=ge?ge.paths.filter(l=>!ge.query||l.toLowerCase().includes(ge.query.toLowerCase())).slice(0,8):[],rn=ye?ye.sessions.filter(l=>{let i=ye.query.toLowerCase();return!i||l.name.toLowerCase().includes(i)||l.firstPrompt.toLowerCase().includes(i)}).slice(0,8):[],de=Y((l,i)=>{me.current?.close(),me.current=Na({cwd:e,resume:l,profileName:i??s,allowProdWrites:ot.current}),l||(Pe.current={uuid:null,firstPrompt:null,titleFired:!1},rt(null)),dt(0),pt(0)},[e,s]),ns=Y((l,i,a)=>{if(Lp.test(l))try{let g=ce(e,s),d=typeof i.project_id=="string"&&i.project_id||g.project.projectId,m=Bn(i,a),y=[],v=Gn(a);l.endsWith("publish_article")&&v&&y.push(`Live: ${v}`),m&&d&&y.push(`Preview: ${qn(g.connection.portalUrl,d,m,g.project.languageCode??"en")}`),y.length>0&&u({kind:"link",lines:y})}catch{}},[e,s,u]),pe=Y(async(l,i)=>{Xt(!0),se(null),B([]),Zt(null),io(null),po(null);let a=++Qe.current;i?.quietUser||u({kind:"user",text:i?.echoDisplay&&i.display?i.display:l});let g=Pe.current;g.firstPrompt||(g.firstPrompt=i?.display??l),We.current=Date.now(),Ze(0),O(!0),Qt.current.clear();let d="",m=!1,y=!1,v="",D={num:0,closed:!1,cueSeen:!1},j=null,ne=()=>{j||(j=setTimeout(()=>{j=null,h(v.length>0?v:null)},60))},K=()=>{j&&clearTimeout(j),j=null,h(null)},_=()=>{if(v.trim()){let x=jr(v.trimEnd(),D);u({kind:"assistant",text:x})}v="",K()};try{for await(let x of me.current.send(l))if(x.type==="session"){if(!g.uuid){g.uuid=x.sessionId;let A=new Date().toISOString(),M=fp(g.firstPrompt??"session");mp({uuid:x.sessionId,name:M,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:A,updatedAt:A}),rt(M)}}else if(x.type==="text"){v+=x.delta,d+=x.delta;let A=Ia(v);if(A>0){let M=v.slice(0,A).trimEnd();M&&u({kind:"assistant",text:jr(M,D)}),v=v.slice(A)}ne(),Ze(M=>M+x.delta.length)}else if(x.type==="tool"){m=!0;let A=Fn(x.name,x.input);A&&(_(),u({kind:"tool",title:A.title,sep:A.sep,arg:A.arg}),Qt.current.set(x.id,{name:x.name,input:x.input}))}else if(x.type==="article_diff"){let A=Xe(x.oldContent,x.newContent,Ie());A&&(_(),u({kind:"diff",added:A.added,removed:A.removed,lines:A.lines,hidden:A.hidden}))}else if(x.type==="tool_result"){x.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(x.output)&&(en.current=!0);let A=Qt.current.get(x.id);if(A){Qt.current.delete(x.id),_();let M=Hn(x.output,4,x.isError?void 0:A.name,A.input);u({kind:"tool-result",lines:M.lines,hidden:M.hidden,isError:x.isError}),x.isError||ns(A.name,A.input,x.output)}}else if(x.type==="result"){if(_(),dt(M=>M+x.outputTokens),pt(M=>M+x.costUsd),u({kind:"done",seconds:Math.round((Date.now()-We.current)/1e3),tokens:x.outputTokens,costUsd:x.costUsd,ok:x.ok}),!y&&!m&&!d.trim()&&!St.current&&u({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)."}),x.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(d))try{let M=Ep(e);if(Yt(M)){let L=Or(M,"utf8").trim();L&&(po(L),u({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 A=x.ok?$a(d,_t.map(M=>M.name)):[];if(A.length>0?B(A):x.ok&&d.trim()&&yp(l,d,e).then(M=>{M&&Qe.current===a&&se(M)}).catch(()=>{}),g.uuid&&(Ur(g.uuid),!g.titleFired)){g.titleFired=!0;let M=g.uuid,L=g.firstPrompt;L&&_a(L,e).then(G=>{G&&(pp(M,G),rt(G))}).catch(()=>{})}}else x.type==="error"&&(_(),y=!0,x.kind==="auth"&&(en.current=!0),u({kind:"note",text:`agent error: ${x.message}`,tone:"error"}))}finally{O(!1),K(),re(x=>x+1),Pe.current.uuid&&ba(e,Pe.current.uuid,nt.current),en.current&&(en.current=!1,tn.current=i?.display??l,B(["/login"])),St.current&&(St.current=!1,Ge.current.length>0&&(u({kind:"note",tone:"info",text:`(${Ge.current.length} queued message(s) discarded)`}),Ge.current=[],oo([])),u({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,u,ns,Ie]),sn=Y(async l=>{let i=Wr(l),a=Qn(e,"standard");We.current=Date.now(),Ze(0),O(!0);let g=new AbortController;we.current=g,J({verb:"Publishing",total:i.length,done:0,active:[],rows:Vt(i),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${i.length} partition${i.length===1?"":"s"} (\u2264${Wt} agents at once) on ${a.model}\u2026 (esc to stop)`});try{for await(let d of Jn({cwd:e,partitions:i,promptFor:m=>Dn(m.paths),concurrency:Wt,profileName:s,allowProdWrites:ot.current,model:a.model,signal:g.signal}))if(d.type==="partition_status")d.status==="running"?J(m=>m&&{...m,active:[...m.active,d.label],rows:Re(m.rows,d.label,"active"),lastAt:Date.now()}):J(m=>m&&{...m,active:m.active.filter(y=>y!==d.label),done:m.done+1,rows:Re(m.rows,d.label,d.status==="done"?"done":"failed"),lastAt:Date.now()});else if(d.type==="partition_event")J(m=>{if(!m)return m;let y={...m,lastAt:Date.now()};return d.event.type==="tool"?y.tools=m.tools+1:d.event.type==="text"&&(y.chars=m.chars+d.event.delta.length),y});else if(d.type==="run_done"){pt(v=>v+d.totalCostUsd),dt(v=>v+d.results.reduce((D,j)=>D+j.outputTokens,0));let m=d.aborted?"Stopped. ":"",y=t.kind==="api"?"api":"subscription";u({kind:"note",tone:d.aborted?"warn":d.ok?"ok":"warn",text:m+Wo(d.results,i,y).join(`
270
+ `)})}}catch(d){u({kind:"note",tone:"error",text:`Publish run failed: ${d.message}`})}finally{we.current=null,J(null),O(!1),re(d=>d+1)}},[e,s,u,t]),ho=Y(async l=>{await pe(Mo(l),{display:`/publish ${l}`,quietUser:!0});try{let i=await jn(e,s,l.replace(/\\/g,"/"));i.length>0&&(Zt(`Related articles not yet published (${i.length}):`),B([`/publish --related ${l}`,...i.map(a=>`/publish ${a}`)]))}catch{}},[e,s,pe]),go=Y(l=>{let i=Me(l);if(!i||De(i)&&!i.refreshToken)return null;let a={...Ct(i.idToken)??{},...Ct(i.accessToken)??{}};return a.email??a.preferred_username??"signed in"},[]),wo=Y((l,i)=>{if(i){let a=Q(e);a&&(a.defaultProfile=l,kp(a,e))}c(l),de(void 0,l),u({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${i?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),go(l)||(u({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),B(["/login"])),re(a=>a+1)},[e,u,de,go]),an=Y((l,i,a)=>{pn(e,l,i,a.id,a.name),u({kind:"note",tone:"ok",text:`Switched to workspace "${a.name??a.id}" (agent restarted).`}),de(),Lr(e,l)||(u({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),u({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:"}),u({kind:"note",tone:"info",text:kt(yt(e)).join(`
271
+ `)}),ft(ze()),Dt.current=_e(e).status==="current",u({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,u,de,ft]),ln=Y(async l=>{let i;try{i=await It(e,l)}catch{u({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),B(["/workspace"]);return}if(i.workspaces.length===0){u({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let a=i.workspaces.filter(d=>(d.workspace_type??"").toLowerCase()!=="apidocumentation"),g=a.length>0?a:i.workspaces;if(g.length===1){let d=g[0],m=i.workspaces.length-g.length;u({kind:"note",tone:"ok",text:`Selected the "${d.name??d.id}" workspace${m>0?" (skipped the API-documentation workspace)":""}.`}),an(i.profile,i.projectId,d);return}u({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),B(["/workspace"])},[e,u,an]),os=Y((l,i)=>{$o(e,l,i.id,i.name),u({kind:"note",tone:"ok",text:`Project set to "${i.name??i.id}" (agent restarted).`}),de(),ln(l)},[e,u,de,ln]),rs=Y(async l=>{let i;try{i=ce(e,l)}catch{return}if(!i.project.workspaceId){if(i.project.projectId){if(!i.project.projectName)try{let{projects:a}=await gt(e,i.name),g=a.find(d=>d.id===i.project.projectId);g?.name&&Ip(e,i.name,{projectName:g.name})}catch{}await ln(i.name);return}u({kind:"note",tone:"info",text:"Next: pick the Document360 project."}),B(["/project"])}},[e,u,ln]),cn=Y(()=>{let l=Ae.current[0];if(!l)return;u({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let a of l.notes)u({kind:"note",tone:"warn",text:`\u26A0 ${a}`});l.overwritesLocalChanges&&u({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let i=Xe(l.oldContent,l.newContent,Ie());u(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."}),u({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[u,Ie]),ss=Y(l=>{if(Ae.current.length===0)return!1;let i=l.trim().toLowerCase();if(i==="y"||i==="yes"){let a=Ae.current.shift();try{bp({cwd:e,profileName:s},a),u({kind:"note",tone:"ok",text:`\u2713 Pulled ${a.path} (sync base advanced).`}),Ae.current.length===0&&B(g=>g.length>0?g:["/sync"])}catch(g){u({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(i==="n"||i==="no"){let a=Ae.current.shift();u({kind:"note",tone:"info",text:`Skipped ${a.path}.`})}else{let a=Ae.current.length;return Ae.current=[],u({kind:"note",tone:"info",text:`Pull cancelled (${a} article(s) left untouched).`}),!0}return cn(),!0},[e,s,cn,u]),is=Y(l=>{let i=no.current;if(!i)return!1;if(no.current=null,se(null),Qe.current++,l.trim()!==i.repoName)return u({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:a,failed:g}=Pr(e,i.targets);u({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 d of g)u({kind:"note",tone:"error",text:` \u2717 ${d.path}: ${d.error}`});return i.hadDevhints&&(u({kind:"note",tone:"warn",text:Pn().join(`
272
272
  `)}),ft(Ro())),u({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
273
273
  ${La}`}),B(["/init"]),Xt(!1),!0},[e,u,ft]),as=Y(async l=>{let i=l.slice(1).trim().split(/\s+/),a=(i[0]??"").toLowerCase(),g=i.slice(1);switch(Xt(!0),a){case"help":u({kind:"note",tone:"info",text:kn().join(`
274
- `)});return;case"exit":case"quit":me.current?.close(),r();return;case"clear":de(),nt.current=[],Xt(!1),se(null),Qe.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=ce(e,s)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),te(!0);try{let m=await op(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},v=>u({kind:"note",tone:"info",text:v})),y=rp(d.name,m);if(sp(y),await vo(y,d.name,v=>u({kind:"note",tone:"info",text:v})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${mn(y)}`}),await rs(s),Rt.current){let v=Rt.current;Rt.current=null;let D=Se(e,s);D.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${v}.`}),B([v])):(u({kind:"note",tone:"warn",text:`${D.reason} (then ${v}.)`}),B(["/login"]),Rt.current=v)}else tn.current&&(se(tn.current),tn.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{te(!1),re(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=ce(e,s).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}ot.current=!0,de(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=ur(g.join(" ")),m=Pe.current.uuid;if(!m){u({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let y=Pe.current.firstPrompt??"";_a(y,e).then(v=>{v?(se(`/rename ${v}`),u({kind:"note",tone:"info",text:`Suggestion: "${v}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}gp(m,d),rt(d),Gt(`${Er} d360-writer \xB7 ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=g[0],m=Q(e);if(!d){let y=Object.entries(m?.profiles??{});if(y.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let v=y.map(([oe,K])=>({name:oe,env:K.connection?.environment??"custom",prod:K.production===!0,who:go(oe)})),D=s??m?.defaultProfile,j=Math.max(0,v.findIndex(oe=>oe.name===D));st({cursor:j,current:j,rows:v});return}if(d==="add"){let y=dr(e,g[1],g[2]);if(y){u({kind:"note",tone:"error",text:y});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),wo(g[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}wo(d,!0);return}case"doctor":await qt(g,{cwd:e});return;case"mcp":await Sn(g);return;case"init":{if(Q(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let d=$p().map(m=>({name:m,apiUrl:vp(m).apiUrl}));it({cursor:0,rows:d});return}case"resume":{let d=g.join(" ").trim(),m=hp(e).filter(D=>D.uuid!==Pe.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ve({query:"",cursor:0,sessions:m});return}let y=mp(e,d);if(!y){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}de(y.uuid),Pe.current={uuid:y.uuid,firstPrompt:y.firstPrompt,titleFired:!0},rt(y.name),Ur(y.uuid),nt.current=[];let v=Ar(e,y.uuid);for(let D of v)u(D);u({kind:"note",tone:"ok",text:v.length?`Resumed "${y.name}" \u2014 restored ${v.length} message(s); continue where you left off.`:`Resumed "${y.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=g.join(" ").trim(),m;try{m=await It(e,s)}catch(v){u({kind:"note",tone:"error",text:`Could not list workspaces: ${v.message}`});return}if(!d){let v=m.workspaces.map(j=>({id:j.id,name:j.name??j.id,type:j.workspace_type}));if(v.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let D=Math.max(0,v.findIndex(j=>j.id===m.current));at({cursor:D,current:D,rows:v,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let y=xo(m.workspaces,d);if(!y){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}an(m.profile,m.projectId,y);return}case"project":{let d=g.join(" ").trim(),m;try{m=await gt(e,s)}catch(v){u({kind:"note",tone:"error",text:`Could not list projects: ${v.message} (signed in? try /login)`});return}if(!d){let v=m.projects.map(j=>({id:j.id,name:j.name??j.id,sub:j.sub_domain}));if(v.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let D=v.findIndex(j=>j.id===m.current);lt({cursor:Math.max(0,D),current:D,rows:v,profile:m.profile,environment:m.environment});return}let y=hs(m.projects,d);if(!y){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map(v=>v.name??v.id).join(", ")}`});return}os(m.profile,y);return}case"logout":{let d;try{d=ce(e,s).name}catch(y){u({kind:"note",tone:"error",text:y.message});return}let m=cp(d);up(e,d),de(),re(y=>y+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),B(["/login"]);return}case"publish":{if(!co(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await jn(e,s,g[1].replace(/\\/g,"/"));if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await sn(m);return}if(g[0]&&g[0]!=="--all"){await ho(g[0]);return}let d=g[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Mr({cwd:e,profileName:s}),y=Ft(m.entries),v=Rn(m.entries);if(v>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${v} article${v===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.`}),y.length===0){u({kind:"note",tone:"ok",text:v>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let D=m.counts["unknown-base"]??0;D>0&&u({kind:"note",tone:"info",text:`(${D} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(d){await sn(y.map(D=>D.path));return}ct({cursor:0,rows:si(y)})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let d=g.join(" ").trim();if(!d){let y=[];try{y=Object.keys(Lr(e,ce(e,s).name)?.articles??{})}catch{}if(y.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Be({query:"",cursor:0,paths:y});return}let m=tp(d)?d:Kt(e,d);if(Yt(m)){try{u({kind:"preview",name:zt(m),text:Wa(Or(m,"utf8"))})}catch(y){u({kind:"note",tone:"error",text:`Could not read ${m}: ${y.message}`})}return}if(Lp.test(d)){try{let y=ce(e,s),v={profile:y.name,connection:y.connection},D=y.project.projectId??ap(v),j=await lp(v,D,d);u({kind:"preview",name:j.title??d,text:j.content??"*(article has no content)*"})}catch(y){u({kind:"note",tone:"error",text:`Could not fetch article: ${y.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=g[0]?.trim();if(!d){let D=_n(Hr(e));He({cursor:D,current:D});return}let{lines:m,changed:y,effective:v}=Ht(e,d);for(let D of m)u({kind:"note",tone:D.startsWith("\u26A0")?"warn":D.startsWith("\u2713")?"ok":"info",text:D});y&&(Qr(D=>D+1),me.current?.setModel(v));return}case"convert":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:m}=Bo(g),y=Tp(e,s);if(y.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let v=Go(y,d);if(v.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${y.length} are tracked overall.)`});return}let D=Wr(v),j=3,oe=`/convert${d?` --scope ${d}`:""} --run`,K=Qn(e,"light");if(!m){let x=Oa({files:Vo(e,v),op:"convert",model:K.model}),A=d?`Scope: ${d} (${v.length} of ${y.length} tracked)
274
+ `)});return;case"exit":case"quit":me.current?.close(),r();return;case"clear":de(),nt.current=[],Xt(!1),se(null),Qe.current++,u({kind:"note",tone:"info",text:"Conversation reset (the previous session is still resumable via /resume)."});return;case"login":{let d;try{d=ce(e,s)}catch(m){u({kind:"note",tone:"error",text:m.message});return}u({kind:"note",tone:"info",text:`Profile "${d.name}" \u2192 ${d.connection.name} (${d.connection.apiUrl})${d.production?" \u26A0 PRODUCTION":""}`}),te(!0);try{let m=await rp(d.connection,{promptForRedirect:()=>Promise.reject(new Error("Manual login is CLI-only. Run: d360-writer login --manual"))},v=>u({kind:"note",tone:"info",text:v})),y=sp(d.name,m);if(ip(y),await vo(y,d.name,v=>u({kind:"note",tone:"info",text:v})),u({kind:"note",tone:"ok",text:`\u2713 Logged in to "${d.name}" as ${mn(y)}`}),await rs(s),Rt.current){let v=Rt.current;Rt.current=null;let D=Se(e,s);D.ok?(u({kind:"note",tone:"ok",text:`\u2713 Signed into the right project \u2014 press 1 to run ${v}.`}),B([v])):(u({kind:"note",tone:"warn",text:`${D.reason} (then ${v}.)`}),B(["/login"]),Rt.current=v)}else tn.current&&(se(tn.current),tn.current=null,u({kind:"note",tone:"info",text:"Press tab to re-send your last prompt."}))}catch(m){u({kind:"note",tone:"error",text:`Login failed: ${m.message}`})}finally{te(!1),re(m=>m+1)}return}case"allow-prod":{let d=!1;try{d=ce(e,s).production}catch{}if(!d){u({kind:"note",tone:"info",text:"Current profile is not production \u2014 writes are already allowed."});return}ot.current=!0,de(),u({kind:"note",tone:"warn",text:"\u26A0 Production writes authorized for this session."});return}case"rename":{let d=ur(g.join(" ")),m=Pe.current.uuid;if(!m){u({kind:"note",tone:"error",text:"Send a message first \u2014 sessions save once the agent replies."});return}if(!d){u({kind:"note",tone:"info",text:"Thinking of a name\u2026"});let y=Pe.current.firstPrompt??"";_a(y,e).then(v=>{v?(se(`/rename ${v}`),u({kind:"note",tone:"info",text:`Suggestion: "${v}" \u2014 press tab to accept, or type /rename <your name>.`})):u({kind:"note",tone:"info",text:"Usage: /rename <name>"})}).catch(()=>u({kind:"note",tone:"info",text:"Usage: /rename <name>"}));return}wp(m,d),rt(d),Gt(`${Er} d360-writer \xB7 ${d}`),u({kind:"note",tone:"ok",text:`Session renamed to "${d}".`});return}case"profile":{let d=g[0],m=Q(e);if(!d){let y=Object.entries(m?.profiles??{});if(y.length===0){u({kind:"note",tone:"info",text:"No profiles. Run /init first."});return}let v=y.map(([ne,K])=>({name:ne,env:K.connection?.environment??"custom",prod:K.production===!0,who:go(ne)})),D=s??m?.defaultProfile,j=Math.max(0,v.findIndex(ne=>ne.name===D));st({cursor:j,current:j,rows:v});return}if(d==="add"){let y=dr(e,g[1],g[2]);if(y){u({kind:"note",tone:"error",text:y});return}u({kind:"note",tone:"ok",text:`\u2713 Profile "${g[1]}" created (environment: ${g[2]??g[1]}).`}),wo(g[1],!1);return}if(!m?.profiles?.[d]){u({kind:"note",tone:"error",text:`Unknown profile "${d}". Create it: /profile add ${d} <environment>`});return}wo(d,!0);return}case"doctor":await qt(g,{cwd:e});return;case"mcp":await Sn(g);return;case"init":{if(Q(e)){u({kind:"note",tone:"info",text:"This repo is already set up \u2014 edit .d360-writer.json directly (or d360-writer init for the CLI wizard)."});return}let d=vp().map(m=>({name:m,apiUrl:Cp(m).apiUrl}));it({cursor:0,rows:d});return}case"resume":{let d=g.join(" ").trim(),m=gp(e).filter(D=>D.uuid!==Pe.current.uuid);if(!d){if(!m.length){u({kind:"note",tone:"info",text:"No saved sessions for this repo yet."});return}Ve({query:"",cursor:0,sessions:m});return}let y=hp(e,d);if(!y){u({kind:"note",tone:"error",text:`No session matches "${d}".`});return}de(y.uuid),Pe.current={uuid:y.uuid,firstPrompt:y.firstPrompt,titleFired:!0},rt(y.name),Ur(y.uuid),nt.current=[];let v=Ar(e,y.uuid);for(let D of v)u(D);u({kind:"note",tone:"ok",text:v.length?`Resumed "${y.name}" \u2014 restored ${v.length} message(s); continue where you left off.`:`Resumed "${y.name}" (agent memory reconnected; no saved transcript to replay).`});return}case"workspace":{let d=g.join(" ").trim(),m;try{m=await It(e,s)}catch(v){u({kind:"note",tone:"error",text:`Could not list workspaces: ${v.message}`});return}if(!d){let v=m.workspaces.map(j=>({id:j.id,name:j.name??j.id,type:j.workspace_type}));if(v.length===0){u({kind:"note",tone:"info",text:"No workspaces in this project."});return}let D=Math.max(0,v.findIndex(j=>j.id===m.current));at({cursor:D,current:D,rows:v,profile:m.profile,projectId:m.projectId,projectName:m.projectName,environment:m.environment});return}let y=xo(m.workspaces,d);if(!y){u({kind:"note",tone:"error",text:`No workspace matches "${d}".`});return}an(m.profile,m.projectId,y);return}case"project":{let d=g.join(" ").trim(),m;try{m=await gt(e,s)}catch(v){u({kind:"note",tone:"error",text:`Could not list projects: ${v.message} (signed in? try /login)`});return}if(!d){let v=m.projects.map(j=>({id:j.id,name:j.name??j.id,sub:j.sub_domain}));if(v.length===0){u({kind:"note",tone:"info",text:"No projects found for this identity."});return}let D=v.findIndex(j=>j.id===m.current);lt({cursor:Math.max(0,D),current:D,rows:v,profile:m.profile,environment:m.environment});return}let y=hs(m.projects,d);if(!y){u({kind:"note",tone:"error",text:`No project matches "${d}". Available: ${m.projects.map(v=>v.name??v.id).join(", ")}`});return}os(m.profile,y);return}case"logout":{let d;try{d=ce(e,s).name}catch(y){u({kind:"note",tone:"error",text:y.message});return}let m=up(d);dp(e,d),de(),re(y=>y+1),u({kind:"note",tone:m?"ok":"info",text:m?`\u2713 Signed out of "${d}" and cleared its project/workspace selection.`:`Profile "${d}" was not signed in. Cleared any project/workspace selection.`}),u({kind:"note",tone:"info",text:"Run /login to sign in and pick a project."}),B(["/login"]);return}case"publish":{if(!co(l.trim()))return;if(g[0]==="--related"&&g[1]){let m=await jn(e,s,g[1].replace(/\\/g,"/"));if(m.length===0){u({kind:"note",tone:"ok",text:"\u2713 All related articles are already published."});return}await sn(m);return}if(g[0]&&g[0]!=="--all"){await ho(g[0]);return}let d=g[0]==="--all";u({kind:"note",tone:"info",text:"Checking what needs publishing\u2026"});try{let m=await Mr({cwd:e,profileName:s}),y=Ft(m.entries),v=Rn(m.entries);if(v>0&&u({kind:"note",tone:"warn",text:`\u26A0 ${v} article${v===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.`}),y.length===0){u({kind:"note",tone:"ok",text:v>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates."});let D=m.counts["unknown-base"]??0;D>0&&u({kind:"note",tone:"info",text:`(${D} article(s) have no sync base yet \u2014 publish those by path if needed.)`});return}if(d){await sn(y.map(D=>D.path));return}ct({cursor:0,rows:si(y)})}catch(m){u({kind:"note",tone:"error",text:`Could not compute sync status: ${m.message}`}),u({kind:"note",tone:"info",text:"Publish a specific article: /publish <article-path>"})}return}case"preview":{let d=g.join(" ").trim();if(!d){let y=[];try{y=Object.keys(Lr(e,ce(e,s).name)?.articles??{})}catch{}if(y.length===0){u({kind:"note",tone:"info",text:"No tracked articles to pick from yet. Usage: /preview <path-to.md | article-id>"});return}Be({query:"",cursor:0,paths:y});return}let m=np(d)?d:Kt(e,d);if(Yt(m)){try{u({kind:"preview",name:zt(m),text:Wa(Or(m,"utf8"))})}catch(y){u({kind:"note",tone:"error",text:`Could not read ${m}: ${y.message}`})}return}if(Mp.test(d)){try{let y=ce(e,s),v={profile:y.name,connection:y.connection},D=y.project.projectId??lp(v),j=await cp(v,D,d);u({kind:"preview",name:j.title??d,text:j.content??"*(article has no content)*"})}catch(y){u({kind:"note",tone:"error",text:`Could not fetch article: ${y.message}`})}return}u({kind:"note",tone:"error",text:`"${d}" is neither a file (relative to ${e}) nor an article id.`});return}case"model":{let d=g[0]?.trim();if(!d){let D=_n(Hr(e));He({cursor:D,current:D});return}let{lines:m,changed:y,effective:v}=Ht(e,d);for(let D of m)u({kind:"note",tone:D.startsWith("\u26A0")?"warn":D.startsWith("\u2713")?"ok":"info",text:D});y&&(Qr(D=>D+1),me.current?.setModel(v));return}case"convert":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{scope:d,run:m}=Bo(g),y=Sp(e,s);if(y.length===0){u({kind:"note",tone:"error",text:"No tracked articles in d360-category-map.json. Publish some first (/publish), then /convert."});return}let v=Go(y,d);if(v.length===0){u({kind:"note",tone:"error",text:`No tracked articles under "${d}". (${y.length} are tracked overall.)`});return}let D=Wr(v),j=3,ne=`/convert${d?` --scope ${d}`:""} --run`,K=Qn(e,"light");if(!m){let x=Oa({files:Vo(e,v),op:"convert",model:K.model}),A=d?`Scope: ${d} (${v.length} of ${y.length} tracked)
275
275
  `:"",M=`
276
276
  Model: ${K.model}${K.forced?" (forced)":" \u2014 mechanical work; /model to override"}`;u({kind:"note",tone:"info",text:A+zo(D,x,j).join(`
277
- `)+M}),B([oe]);return}We.current=Date.now(),Ze(0),O(!0);let _=new AbortController;we.current=_,J({verb:"Converting",total:D.length,done:0,active:[],rows:Vt(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${v.length} articles across ${D.length} partitions (\u2264${j} agents at once) on ${K.model}\u2026 (esc to stop)`});try{for await(let x of Jn({cwd:e,partitions:D,promptFor:Yo,concurrency:j,profileName:s,allowProdWrites:ot.current,model:K.model,signal:_.signal}))if(x.type==="partition_status")x.status==="running"?J(A=>A&&{...A,active:[...A.active,x.label],rows:Re(A.rows,x.label,"active"),lastAt:Date.now()}):J(A=>A&&{...A,active:A.active.filter(M=>M!==x.label),done:A.done+1,rows:Re(A.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")J(A=>{if(!A)return A;let M={...A,lastAt:Date.now()};return x.event.type==="tool"?M.tools=A.tools+1:x.event.type==="text"&&(M.chars=A.chars+x.event.delta.length),M});else if(x.type==="run_done"){pt(L=>L+x.totalCostUsd),dt(L=>L+x.results.reduce((G,ae)=>G+ae.outputTokens,0));let A=x.aborted?"Stopped. ":"",M=t.kind==="api"?"api":"subscription";u({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:A+Ko(x.results,D,M).join(`
278
- `)})}}catch(x){u({kind:"note",tone:"error",text:`Convert run failed: ${x.message}`})}finally{we.current=null,J(null),O(!1),re(x=>x+1)}return}case"write":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Sp(e);if(d.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:y,run:v}=Jo(g),{docsDir:D,targets:j,reason:oe}=nr(e,d,{scope:m,path:y});if(j.length===0){u({kind:"note",tone:"warn",text:oe??"Nothing to write."});return}let K=Wr(j),_=5,x=Qn(e,"standard");if(!v&&!!!y){let L=Oa({files:Qo(e,d,j),op:"write",model:x.model}),G=m?`Scope: ${m} (${j.length} pending)
277
+ `)+M}),B([ne]);return}We.current=Date.now(),Ze(0),O(!0);let _=new AbortController;we.current=_,J({verb:"Converting",total:D.length,done:0,active:[],rows:Vt(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Converting ${v.length} articles across ${D.length} partitions (\u2264${j} agents at once) on ${K.model}\u2026 (esc to stop)`});try{for await(let x of Jn({cwd:e,partitions:D,promptFor:Yo,concurrency:j,profileName:s,allowProdWrites:ot.current,model:K.model,signal:_.signal}))if(x.type==="partition_status")x.status==="running"?J(A=>A&&{...A,active:[...A.active,x.label],rows:Re(A.rows,x.label,"active"),lastAt:Date.now()}):J(A=>A&&{...A,active:A.active.filter(M=>M!==x.label),done:A.done+1,rows:Re(A.rows,x.label,x.status==="done"?"done":"failed"),lastAt:Date.now()});else if(x.type==="partition_event")J(A=>{if(!A)return A;let M={...A,lastAt:Date.now()};return x.event.type==="tool"?M.tools=A.tools+1:x.event.type==="text"&&(M.chars=A.chars+x.event.delta.length),M});else if(x.type==="run_done"){pt(L=>L+x.totalCostUsd),dt(L=>L+x.results.reduce((G,ae)=>G+ae.outputTokens,0));let A=x.aborted?"Stopped. ":"",M=t.kind==="api"?"api":"subscription";u({kind:"note",tone:x.aborted?"warn":x.ok?"ok":"warn",text:A+Ko(x.results,D,M).join(`
278
+ `)})}}catch(x){u({kind:"note",tone:"error",text:`Convert run failed: ${x.message}`})}finally{we.current=null,J(null),O(!1),re(x=>x+1)}return}case"write":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=Rp(e);if(d.length===0){u({kind:"note",tone:"error",text:"No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first \u2014 try: analyze this repo and propose a docs structure."});return}let{scope:m,path:y,run:v}=Jo(g),{docsDir:D,targets:j,reason:ne}=nr(e,d,{scope:m,path:y});if(j.length===0){u({kind:"note",tone:"warn",text:ne??"Nothing to write."});return}let K=Wr(j),_=5,x=Qn(e,"standard");if(!v&&!!!y){let L=Oa({files:Qo(e,d,j),op:"write",model:x.model}),G=m?`Scope: ${m} (${j.length} pending)
279
279
  `:"",ae=`
280
280
  Model: ${x.model}${x.forced?" (forced)":" \u2014 authoring; /model to override"}`;u({kind:"note",tone:"info",text:G+er(K,L,_).join(`
281
281
  `)+ae}),B([`/write${m?` --scope ${m}`:" --all"} --run`]);return}We.current=Date.now(),Ze(0),O(!0);let M=new AbortController;we.current=M,J({verb:"Writing",total:K.length,done:0,active:[],rows:Vt(K),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Writing ${j.length} article${j.length===1?"":"s"} across ${K.length} partition${K.length===1?"":"s"} (\u2264${_} agents at once) on ${x.model}${x.forced?" (forced)":""}\u2026 (esc to stop)`});try{for await(let L of Jn({cwd:e,partitions:K,promptFor:G=>Zo(G,D),concurrency:_,profileName:s,allowProdWrites:ot.current,model:x.model,signal:M.signal}))if(L.type==="partition_status")L.status==="running"?J(G=>G&&{...G,active:[...G.active,L.label],rows:Re(G.rows,L.label,"active"),lastAt:Date.now()}):J(G=>G&&{...G,active:G.active.filter(ae=>ae!==L.label),done:G.done+1,rows:Re(G.rows,L.label,L.status==="done"?"done":"failed"),lastAt:Date.now()});else if(L.type==="partition_event")J(G=>{if(!G)return G;let ae={...G,lastAt:Date.now()};return L.event.type==="tool"?ae.tools=G.tools+1:L.event.type==="text"&&(ae.chars=G.chars+L.event.delta.length),ae});else if(L.type==="run_done"){pt(ko=>ko+L.totalCostUsd),dt(ko=>ko+L.results.reduce((ol,rl)=>ol+rl.outputTokens,0));let G=L.aborted?"Stopped. ":"",ae=t.kind==="api"?"api":"subscription";u({kind:"note",tone:L.aborted?"warn":L.ok?"ok":"warn",text:G+tr(L.results,K,ae).join(`
282
282
  `)}),!L.aborted&&L.ok&&B(["/publish --all","/screenshot --all"])}}catch(L){u({kind:"note",tone:"error",text:`Write run failed: ${L.message}`})}finally{we.current=null,J(null),O(!1),re(L=>L+1)}return}case"draft":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{features:d,looseDocs:m}=or(e);if(d.length===0&&m===0){u({kind:"note",tone:"info",text:sr});return}let y=g.join(" ").trim();if(!y&&d.length>1){u({kind:"note",tone:"info",text:`Multiple features in .d360-writer/input/ \u2014 draft which one?
283
283
  ${d.map(j=>` \u2022 ${j.name} (${j.docCount} doc${j.docCount===1?"":"s"})`).join(`
284
284
  `)}`}),B(d.map(j=>`/draft ${j.name}`));return}let v="",D;if(y){let j=rr(d,y);j?v=j:D=y}else v=d[0]?.name??"";await pe(Nn(v,D),{display:y?`/draft ${y}`:"/draft",quietUser:!0});return}case"sync":{if(!co(l.trim()))return;let d=(g[0]??"status").toLowerCase();try{if(d==="status"){u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"});let m=await Mr({cwd:e,profileName:s});u({kind:"note",tone:"info",text:In(m).join(`
285
- `)});return}if(d==="pull"){let m=g[1];if(!m){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let y;if(m==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),y=(await Mr({cwd:e,profileName:s})).entries.filter(j=>j.status==="remote-ahead"&&j.path).map(j=>j.path),y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else y=[m.replace(/\\/g,"/")];let v=[];for(let D of y)v.push(await bp({cwd:e,profileName:s,relPath:D}));Ae.current=v,cn();return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${d} \u2014 use /sync or /sync pull <path>|--all.`})}catch(m){u({kind:"note",tone:"error",text:`Sync failed: ${m.message}`})}return}case"scope":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=xp(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}ut({cursor:0,rows:d.map(m=>({...m,checked:m.recommended}))});return}case"audit":case"capture-setup":{let m=await(a==="audit"?An:Bt)(g,void 0);if(m.kind==="forward-to-agent"&&m.prompt&&await pe(m.prompt,{display:m.display,quietUser:!0}),a==="capture-setup"){let y=wr(e);y&&u({kind:"note",tone:"info",text:y.join(`
285
+ `)});return}if(d==="pull"){let m=g[1];if(!m){u({kind:"note",tone:"error",text:"Usage: /sync pull <article-path> | --all"});return}let y;if(m==="--all"){if(u({kind:"note",tone:"info",text:"Checking Document360 for drift\u2026"}),y=(await Mr({cwd:e,profileName:s})).entries.filter(j=>j.status==="remote-ahead"&&j.path).map(j=>j.path),y.length===0){u({kind:"note",tone:"ok",text:"\u2713 Nothing is remote-ahead \u2014 no pulls needed. (Conflicts are never bulk-pulled; pull them one by one.)"});return}}else y=[m.replace(/\\/g,"/")];let v=[];for(let D of y)v.push(await xp({cwd:e,profileName:s,relPath:D}));Ae.current=v,cn();return}u({kind:"note",tone:"error",text:`Unknown subcommand: /sync ${d} \u2014 use /sync or /sync pull <path>|--all.`})}catch(m){u({kind:"note",tone:"error",text:`Sync failed: ${m.message}`})}return}case"scope":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let d=$p(e);if(d.length===0){u({kind:"note",tone:"info",text:'No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.'});return}ut({cursor:0,rows:d.map(m=>({...m,checked:m.recommended}))});return}case"audit":case"capture-setup":{let m=await(a==="audit"?An:Bt)(g,void 0);if(m.kind==="forward-to-agent"&&m.prompt&&await pe(m.prompt,{display:m.display,quietUser:!0}),a==="capture-setup"){let y=wr(e);y&&u({kind:"note",tone:"info",text:y.join(`
286
286
  `)})}return}case"devhints":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:kt(yt(e)).join(`
287
287
  `)}),ft(ze()),Dt.current=_e(e).status==="current";return}case"inbox":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(yr(e)===0){u({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 pe(kr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:d,what:m}=ar(g);if(!m&&ir(e)===0){u({kind:"note",tone:"info",text:cr});return}let y=`/document${m?` ${m}`:""}${d?" --publish":""}`;await pe(lr(m,d),{display:y,quietUser:!0});return}case"catch-up":{if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!co(l.trim()))return;let{publish:d}=br(g),m=vt($t(e));u({kind:"note",tone:"info",text:m?`Catching up on ${m} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026"}),await pe(xr({publish:d}),{display:`/catch-up${d?" --publish":""}`,quietUser:!0});return}case"update":{ao.current=!0,u({kind:"note",tone:"info",text:`Updating ${Je}\u2026`}),(await Mn()).ok?(u({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),B(m=>m.includes("/exit")?m:[...m,"/exit"])):u({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Ln}`});return}case"screenshot":{let d=mr(g);if(d.mode==="list"){if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}u({kind:"note",tone:"info",text:gr(hr(e,d.scope),d.scope).join(`
288
- `)});return}if(d.mode==="single"){let _=await Un(g);_.kind==="forward-to-agent"&&_.prompt&&await pe(_.prompt,{display:_.display,quietUser:!0});return}if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=d.mode==="scope"?d.scope:void 0,y=Pp(e,{scope:m}).map(_=>_.id);if(y.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let v=6,D=Cp(y,3),j=Qn(e,"standard");We.current=Date.now(),Ze(0),O(!0);let oe=new AbortController;we.current=oe,J({verb:"Authoring",unit:"spec",total:D.length,done:0,active:[],rows:Vt(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${y.length} screenshot spec${y.length===1?"":"s"} across ${D.length} partition${D.length===1?"":"s"} (\u2264${v} agents at once) on ${j.model}${j.forced?" (forced)":""}\u2026 (esc to stop)`});let K=!1;try{for await(let _ of Jn({cwd:e,partitions:D,promptFor:Ki,concurrency:v,profileName:s,allowProdWrites:ot.current,model:j.model,signal:oe.signal}))if(_.type==="partition_status")_.status==="running"?J(x=>x&&{...x,active:[...x.active,_.label],rows:Re(x.rows,_.label,"active"),lastAt:Date.now()}):J(x=>x&&{...x,active:x.active.filter(A=>A!==_.label),done:x.done+1,rows:Re(x.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_event")J(x=>{if(!x)return x;let A={...x,lastAt:Date.now()};return _.event.type==="tool"?A.tools=x.tools+1:_.event.type==="text"&&(A.chars=x.chars+_.event.delta.length),A});else if(_.type==="run_done"){pt(L=>L+_.totalCostUsd),dt(L=>L+_.results.reduce((G,ae)=>G+ae.outputTokens,0));let x=_.results.filter(L=>L.ok).length,A=_.aborted?"Stopped. ":"";K=!_.aborted&&d.setup;let M=_.aborted?"":K?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:_.aborted?"warn":_.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${x}/${_.results.length} batches ok.${M}`})}}catch(_){u({kind:"note",tone:"error",text:`Spec authoring failed: ${_.message}`})}finally{we.current=null,J(null),O(!1),re(_=>_+1)}if(K){let _=await Bt();_.kind==="forward-to-agent"&&_.prompt&&await pe(_.prompt,{display:_.display,quietUser:!0});let x=wr(e);x&&u({kind:"note",tone:"info",text:x.join(`
288
+ `)});return}if(d.mode==="single"){let _=await Un(g);_.kind==="forward-to-agent"&&_.prompt&&await pe(_.prompt,{display:_.display,quietUser:!0});return}if(!Q(e)){u({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let m=d.mode==="scope"?d.scope:void 0,y=Tp(e,{scope:m}).map(_=>_.id);if(y.length===0){u({kind:"note",tone:"info",text:m?`No screenshot placeholders under ${m}.`:"No screenshot placeholders found in the docs."});return}let v=6,D=Pp(y,3),j=Qn(e,"standard");We.current=Date.now(),Ze(0),O(!0);let ne=new AbortController;we.current=ne,J({verb:"Authoring",unit:"spec",total:D.length,done:0,active:[],rows:Vt(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),u({kind:"note",tone:"info",text:`Authoring ${y.length} screenshot spec${y.length===1?"":"s"} across ${D.length} partition${D.length===1?"":"s"} (\u2264${v} agents at once) on ${j.model}${j.forced?" (forced)":""}\u2026 (esc to stop)`});let K=!1;try{for await(let _ of Jn({cwd:e,partitions:D,promptFor:Ki,concurrency:v,profileName:s,allowProdWrites:ot.current,model:j.model,signal:ne.signal}))if(_.type==="partition_status")_.status==="running"?J(x=>x&&{...x,active:[...x.active,_.label],rows:Re(x.rows,_.label,"active"),lastAt:Date.now()}):J(x=>x&&{...x,active:x.active.filter(A=>A!==_.label),done:x.done+1,rows:Re(x.rows,_.label,_.status==="done"?"done":"failed"),lastAt:Date.now()});else if(_.type==="partition_event")J(x=>{if(!x)return x;let A={...x,lastAt:Date.now()};return _.event.type==="tool"?A.tools=x.tools+1:_.event.type==="text"&&(A.chars=x.chars+_.event.delta.length),A});else if(_.type==="run_done"){pt(L=>L+_.totalCostUsd),dt(L=>L+_.results.reduce((G,ae)=>G+ae.outputTokens,0));let x=_.results.filter(L=>L.ok).length,A=_.aborted?"Stopped. ":"";K=!_.aborted&&d.setup;let M=_.aborted?"":K?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";u({kind:"note",tone:_.aborted?"warn":_.ok?"ok":"warn",text:`${A}Authored specs \u2014 ${x}/${_.results.length} batches ok.${M}`})}}catch(_){u({kind:"note",tone:"error",text:`Spec authoring failed: ${_.message}`})}finally{we.current=null,J(null),O(!1),re(_=>_+1)}if(K){let _=await Bt();_.kind==="forward-to-agent"&&_.prompt&&await pe(_.prompt,{display:_.display,quietUser:!0});let x=wr(e);x&&u({kind:"note",tone:"info",text:x.join(`
289
289
  `)})}return}case"reset":{let d=Cr(e);if(d.length===0){u({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}no.current={repoName:zt(e),targets:d,hadDevhints:Yt(Ua(e))},u({kind:"note",tone:"warn",text:Tr(e,d).join(`
290
- `)}),se(zt(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,cn,u,de,pe,sn,ho,rs]),un=Y(l=>{let i=(l??R).trim();if(k(""),Jt(null),et(0),i.startsWith("/")&&(se(null),Qe.current++,Zt(null),B(g=>Ca(g,i))),!i||is(i)||ss(i))return;to.current.push(i);let a=Ra(i,Gr.current);i.startsWith("/")?(u({kind:"user",text:i}),as(a)):pe(a,{display:i})},[R,is,ss,as,pe]),ls=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Pa(l);if(Ta(i)){let a=Sa(++Qa.current,i);Gr.current.set(a,i),C(a)}else C(i);return}C(l)},[C]),mt=Math.max(10,Ye-6),cs=_r(()=>Kn(b.text,mt),[b.text,mt]),yo=Y(l=>w(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),dn=Y(l=>w(i=>({...i,pos:ja(Kn(i.text,mt),i.pos,l)})),[mt]),At=Y(l=>w(i=>({...i,pos:Aa(Kn(i.text,mt),i.pos,l)})),[mt]),tl=["\x1B[H","\x1B[1~","\x1BOH"],nl=["\x1B[F","\x1B[4~","\x1BOF"],us=Y((l,i)=>i.leftArrow?(yo(-1),!0):i.rightArrow?(yo(1),!0):l&&tl.includes(l)?(At("start"),!0):l&&nl.includes(l)?(At("end"),!0):i.ctrl&&l==="a"?(At("start"),!0):i.ctrl&&l==="e"?(At("end"),!0):!1,[yo,At]);return Zd((l,i)=>{if(i.ctrl&&l==="c"){me.current?.close(),r();return}if(!q){if(N){if(i.escape){if(we.current){we.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),we.current.abort());return}St.current||(St.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),me.current?.interrupt());return}if(i.return){let a=R.trim();if(!a)return;Ge.current.push(a),oo([...Ge.current]),k("");return}if(us(l,i))return;if(i.upArrow){dn(-1);return}if(i.downArrow){dn(1);return}if(i.backspace||i.delete){P();return}l&&!i.ctrl&&!i.meta&&ls(l);return}if(Fe){if(i.upArrow){He(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){He(a=>a&&{...a,cursor:Math.min($e.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.length){He(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=$e[Fe.cursor];He(null);let{lines:g,changed:d,effective:m}=Ht(e,a.value??"default");for(let y of g)u({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});d&&(Qr(y=>y+1),me.current?.setModel(m));return}if(l==="s"){let a=$e[Fe.cursor];He(null),me.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){He(null);return}return}if(Te){if(i.upArrow){st(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){st(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.rows.length){st(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Te.rows[Te.cursor];st(null),wo(a.name,i.return===!0);return}if(i.escape){st(null);return}return}if(Ee){if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ee.rows.length){it(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ee.rows[Ee.cursor].name;if(it(null),!Bs(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let d=!1;try{let m=Me(a);d=!!m&&!(De(m)&&!m.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`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)`}),B(["/login"]),re(m=>m+1);return}if(i.escape){it(null);return}return}if(ie){if(i.upArrow){at(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){at(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ie.rows.length){at(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ie.rows[ie.cursor],{profile:g,projectId:d}=ie;at(null),an(g,d,a);return}if(i.escape){at(null);return}return}if(he){if(i.upArrow){lt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){lt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=he.rows.length){lt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=he.rows[he.cursor],{profile:g}=he;lt(null),os(g,a);return}if(i.escape){lt(null);return}return}if(ue){if(i.upArrow){ut(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ut(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){ut(a=>a&&{...a,rows:a.rows.map((g,d)=>d===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=ue.rows.filter(g=>g.checked).map(g=>g.path);if(ut(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Fo(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)u({kind:"note",tone:"info",text:` ${g}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){ut(null);return}return}if(qe){if(i.upArrow){ct(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ct(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=qe.rows.length){ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=qe.rows[qe.cursor];ct(null),a.kind==="article"?ho(a.paths[0]):sn(a.paths);return}if(i.escape){ct(null);return}return}if(ge){if(i.escape){Be(null);return}if(i.upArrow){Be(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Be(a=>a&&{...a,cursor:Math.min(Math.max(0,on.length-1),a.cursor+1)});return}if(i.return){let a=on[ge.cursor];if(a){Be(null);try{u({kind:"preview",name:zt(a),text:Wa(Or(Kt(e,a),"utf8"))})}catch(g){u({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){Be(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Be(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(ye){if(i.escape){Ve(null);return}if(i.upArrow){Ve(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ve(a=>a&&{...a,cursor:Math.min(Math.max(0,rn.length-1),a.cursor+1)});return}if(i.return){let a=rn[ye.cursor];if(a){Ve(null),de(a.uuid),Pe.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},rt(a.name),Ur(a.uuid),nt.current=[];let g=Ar(e,a.uuid);for(let d of g)u(d);u({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){Ve(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ve(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!R&&ke){k(ke),se(null),Qe.current++;return}if(!R&&Pt.length>0&&l&&/^[1-9]$/.test(l)){let a=Pt[Number(l)-1];if(a){k(a);return}}if(!R&&(uo||so)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=uo!=null;ga(uo??so).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?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."}),d&&a&&po(null)});return}if(!us(l,i)){if(ts){if(i.upArrow){et(a=>Math.max(0,a-1));return}if(i.downArrow){et(a=>Math.min(jt.length-1,a+1));return}if(i.tab){k("/"+(jt[Tt]?.name??"")+" "),et(0);return}if(i.return){let a=jt[Tt];if(a){let g=R.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ss(a.usage)&&!g){k("/"+a.name+" "),et(0);return}un("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(R!==""&&tt===null){dn(-1);return}let a=to.current;if(!a.length)return;let g=tt===null?a.length-1:Math.max(0,tt-1);Jt(g),k(a[g]??"");return}if(i.downArrow){if(R!==""&&tt===null){dn(1);return}let a=to.current;if(tt===null)return;let g=tt+1;g>=a.length?(Jt(null),k("")):(Jt(g),k(a[g]??""));return}}if(i.return){un();return}if(i.backspace||i.delete){P();return}if(i.escape){k(""),et(0),se(null),B([]),Zt(null);return}l&&!i.ctrl&&!i.meta&&ls(l)}}}),ve(()=>{if(N||q)return;let l=Ge.current.shift();l!==void 0&&(oo([...Ge.current]),un(l))},[N,q,un]),H(Z,{flexDirection:"column",width:Ye,children:[mo!==null&&H(Z,{marginTop:1,flexDirection:"column",children:[mo.truncated&&S(T,{dimColor:!0,children:"\u2026"}),S(T,{children:mo.text})]}),N&&(Kr?S(Fp,{p:Kr}):S(Mp,{startTime:We.current,chars:Ja})),S(Z,{borderStyle:"round",borderColor:es.prod?"yellow":V,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:R?cs.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===Xn(cs,b.pos),d=Math.min(b.pos,l.end)-l.start;return H(T,{children:[S(T,{color:V,children:i===0?"> ":" "}),g?H(Fr,{children:[a.slice(0,d),S(Zn,{ch:a[d]??" "}),a.slice(d+1)]}):a||" "]},`${i}-${l.start}`)}):H(T,{children:[S(T,{color:V,children:"> "}),ke&&!N?H(Fr,{children:[S(Zn,{ch:ke[0],dim:!0}),S(T,{color:"gray",children:ke.slice(1)}),S(T,{dimColor:!0,children:" (tab)"})]}):fo.isSetup||!Xa?H(Fr,{children:[S(Zn,{ch:fo.text[0],dim:!0}),S(T,{color:"gray",children:fo.text.slice(1)})]}):S(Zn,{ch:" "})]})}),zr.length>0&&S(Z,{flexDirection:"column",paddingX:1,children:zr.map((l,i)=>S(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Fe?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Select model"}),S(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),$e.map((l,i)=>H(T,{color:i===Fe.cursor?V:void 0,children:[i===Fe.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Fe.current?" \u2714":""}`.padEnd(16),S(T,{color:"gray",children:l.desc})]},l.label)),S(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Te?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Switch connection profile"}),Te.rows.map((l,i)=>H(T,{color:i===Te.cursor?V:void 0,children:[i===Te.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Te.current?" \u2714":""}`.padEnd(20),S(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?S(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),S(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ee?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Pick your Document360 environment"}),Ee.rows.map((l,i)=>H(T,{color:i===Ee.cursor?V:void 0,children:[i===Ee.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),S(T,{color:"gray",children:l.apiUrl})]},l.name)),S(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ie?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Switch workspace"}),S(T,{dimColor:!0,children:`environment ${ie.environment} \xB7 project ${ie.projectName??`${ie.projectId.slice(0,8)}\u2026`}`}),ie.rows.map((l,i)=>H(T,{color:i===ie.cursor?V:void 0,children:[i===ie.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ie.current?" \u2714":""}`.padEnd(30),S(T,{color:"gray",children:l.type??""})]},l.id)),S(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):he?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Choose project"}),S(T,{dimColor:!0,children:`environment ${he.environment}`}),he.rows.map((l,i)=>H(T,{color:i===he.cursor?V:void 0,children:[i===he.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===he.current?" \u2714":""}`.padEnd(30),S(T,{color:"gray",children:l.sub??""})]},l.id)),S(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ue?(()=>{let i=Math.min(Math.max(0,ue.cursor-Math.floor(7)),Math.max(0,ue.rows.length-14)),a=ue.rows.slice(i,i+14),g=ue.rows.filter(d=>d.checked).length;return H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:`Which folders back the user docs? (${g} selected of ${ue.rows.length})`}),i>0?S(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((d,m)=>{let y=i+m;return H(T,{color:y===ue.cursor?V:void 0,children:[y===ue.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ye-34)),S(T,{color:"gray",children:En(d)})]},d.path)}),i+14<ue.rows.length?S(T,{dimColor:!0,children:` \u2193 ${ue.rows.length-i-14} more`}):null,S(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():qe?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),qe.rows.map((l,i)=>{let a=i===qe.cursor,g=l.indent?" ":" ",d=`${i+1}.`.padEnd(3);return H(T,{color:a?V:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${d} ${l.label}`.padEnd(Math.min(56,Ye-24)),l.note?S(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),S(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ge?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:`Preview article${ge.query?` \u2014 filter: ${ge.query}`:" (type to filter)"}`}),on.length===0?S(T,{color:"gray",children:"no articles match"}):on.map((l,i)=>H(T,{color:i===ge.cursor?V:void 0,children:[i===ge.cursor?"\u276F ":" ",l]},l)),S(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),rn.length===0?S(T,{color:"gray",children:"no sessions match"}):rn.map((l,i)=>H(T,{color:i===ye.cursor?V:void 0,children:[i===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),S(T,{color:i===ye.cursor?V:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ye-40))})]},l.uuid)),S(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ts?S(Z,{flexDirection:"column",children:jt.map((l,i)=>H(T,{color:i===Tt?V:void 0,children:[i===Tt?"\u276F ":" ",l.usage.padEnd(22)," ",S(T,{color:i===Tt?V:"gray",children:l.name==="model"&&ro?`${l.desc} (currently ${ro})`:l.desc})]},l.name))}):!R&&Pt.length>0?H(Z,{flexDirection:"column",paddingX:1,children:[Yr?S(T,{color:V,children:Yr}):null,Pt.map((l,i)=>H(T,{children:[S(T,{color:V,children:i+1})," ",l.slice(0,Math.max(20,Ye-5))]},l)),S(T,{dimColor:!0,children:`press 1-${Pt.length} to fill the command \xB7 esc dismiss`})]}):S(Z,{paddingX:1,children:H(T,{color:"gray",children:[es.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ro??"model n/a"}${t.kind==="api"?Jr>0?` \xB7 ${le(Jr)}`:"":Xr>0?` \xB7 ${Ue(Xr)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Gp}from"react/jsx-runtime";async function Ya(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Bp(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=qp(Gp(Va,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
291
- `),process.exit(0)}var Kp=Yp(import.meta.url),za=Kp("../package.json"),je=new Vp;function qr(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}je.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=>{qr(e),await hn({profile:e.profile,manual:e.manual})});je.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qr(e),await $s({profile:e.profile})});je.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qr(e),await xs({profile:e.profile})});var Br=je.command("profile").description("Manage connection profiles for the current repo");Br.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>gn(process.cwd()));Br.command("use <name>").description("Set the default profile for this repo").action(e=>wn(process.cwd(),e));Br.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>yn(process.cwd(),e));var Ka=je.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Ka.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ht(process.cwd(),e.profile));Ka.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await fs(process.cwd(),e,t.profile)});je.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>Cs());je.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(()=>(On(),Fi)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});je.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(za.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(zp.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 Ps(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 ma(e.cwd,e.auth,e.profile):await Ya(e.cwd,e.auth,e.profile,za.version)});je.parseAsync(process.argv).catch(e=>{console.error(""),console.error(`\u2717 ${e.message}`),process.exit(1)});
290
+ `)}),se(zt(e));return}default:u({kind:"note",tone:"error",text:`Unknown command: /${a} \u2014 type /help.`})}},[e,r,s,cn,u,de,pe,sn,ho,rs]),un=Y(l=>{let i=(l??R).trim();if(k(""),Jt(null),et(0),i.startsWith("/")&&(se(null),Qe.current++,Zt(null),B(g=>Ca(g,i))),!i||is(i)||ss(i))return;to.current.push(i);let a=Ra(i,Gr.current);i.startsWith("/")?(u({kind:"user",text:i}),as(a)):pe(a,{display:i})},[R,is,ss,as,pe]),ls=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let i=Pa(l);if(Ta(i)){let a=Sa(++Qa.current,i);Gr.current.set(a,i),C(a)}else C(i);return}C(l)},[C]),mt=Math.max(10,Ye-6),cs=_r(()=>Kn(b.text,mt),[b.text,mt]),yo=Y(l=>w(i=>({...i,pos:Math.max(0,Math.min(i.text.length,i.pos+l))})),[]),dn=Y(l=>w(i=>({...i,pos:ja(Kn(i.text,mt),i.pos,l)})),[mt]),At=Y(l=>w(i=>({...i,pos:Aa(Kn(i.text,mt),i.pos,l)})),[mt]),tl=["\x1B[H","\x1B[1~","\x1BOH"],nl=["\x1B[F","\x1B[4~","\x1BOF"],us=Y((l,i)=>i.leftArrow?(yo(-1),!0):i.rightArrow?(yo(1),!0):l&&tl.includes(l)?(At("start"),!0):l&&nl.includes(l)?(At("end"),!0):i.ctrl&&l==="a"?(At("start"),!0):i.ctrl&&l==="e"?(At("end"),!0):!1,[yo,At]);return Zd((l,i)=>{if(i.ctrl&&l==="c"){me.current?.close(),r();return}if(!q){if(N){if(i.escape){if(we.current){we.current.signal.aborted||(u({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),we.current.abort());return}St.current||(St.current=!0,u({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),me.current?.interrupt());return}if(i.return){let a=R.trim();if(!a)return;Ge.current.push(a),oo([...Ge.current]),k("");return}if(us(l,i))return;if(i.upArrow){dn(-1);return}if(i.downArrow){dn(1);return}if(i.backspace||i.delete){P();return}l&&!i.ctrl&&!i.meta&&ls(l);return}if(Fe){if(i.upArrow){He(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){He(a=>a&&{...a,cursor:Math.min($e.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=$e.length){He(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=$e[Fe.cursor];He(null);let{lines:g,changed:d,effective:m}=Ht(e,a.value??"default");for(let y of g)u({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});d&&(Qr(y=>y+1),me.current?.setModel(m));return}if(l==="s"){let a=$e[Fe.cursor];He(null),me.current?.setModel(a.value??void 0),u({kind:"note",tone:"ok",text:`\u2713 Using ${a.label} for this session only (your saved default is unchanged).`});return}if(i.escape){He(null);return}return}if(Te){if(i.upArrow){st(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){st(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.rows.length){st(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return||l==="s"){let a=Te.rows[Te.cursor];st(null),wo(a.name,i.return===!0);return}if(i.escape){st(null);return}return}if(Ee){if(i.upArrow){it(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){it(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Ee.rows.length){it(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=Ee.rows[Ee.cursor].name;if(it(null),!Bs(e,a).created){u({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}u({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${a}").`});let d=!1;try{let m=Me(a);d=!!m&&!(De(m)&&!m.refreshToken)}catch{d=!1}u({kind:"note",tone:"info",text:d?`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)`}),B(["/login"]),re(m=>m+1);return}if(i.escape){it(null);return}return}if(ie){if(i.upArrow){at(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){at(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ie.rows.length){at(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=ie.rows[ie.cursor],{profile:g,projectId:d}=ie;at(null),an(g,d,a);return}if(i.escape){at(null);return}return}if(he){if(i.upArrow){lt(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){lt(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=he.rows.length){lt(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=he.rows[he.cursor],{profile:g}=he;lt(null),os(g,a);return}if(i.escape){lt(null);return}return}if(ue){if(i.upArrow){ut(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ut(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l===" "){ut(a=>a&&{...a,rows:a.rows.map((g,d)=>d===a.cursor?{...g,checked:!g.checked}:g)});return}if(i.return){let a=ue.rows.filter(g=>g.checked).map(g=>g.path);if(ut(null),a.length===0){u({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}Fo(e,a),u({kind:"note",tone:"ok",text:`\u2713 Scoped to ${a.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of a)u({kind:"note",tone:"info",text:` ${g}`});u({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(i.escape){ut(null);return}return}if(qe){if(i.upArrow){ct(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){ct(a=>a&&{...a,cursor:Math.min(a.rows.length-1,a.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=qe.rows.length){ct(a=>a&&{...a,cursor:Number(l)-1});return}if(i.return){let a=qe.rows[qe.cursor];ct(null),a.kind==="article"?ho(a.paths[0]):sn(a.paths);return}if(i.escape){ct(null);return}return}if(ge){if(i.escape){Be(null);return}if(i.upArrow){Be(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Be(a=>a&&{...a,cursor:Math.min(Math.max(0,on.length-1),a.cursor+1)});return}if(i.return){let a=on[ge.cursor];if(a){Be(null);try{u({kind:"preview",name:zt(a),text:Wa(Or(Kt(e,a),"utf8"))})}catch(g){u({kind:"note",tone:"error",text:`Could not read ${a}: ${g.message}`})}}return}if(i.backspace||i.delete){Be(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Be(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(ye){if(i.escape){Ve(null);return}if(i.upArrow){Ve(a=>a&&{...a,cursor:Math.max(0,a.cursor-1)});return}if(i.downArrow){Ve(a=>a&&{...a,cursor:Math.min(Math.max(0,rn.length-1),a.cursor+1)});return}if(i.return){let a=rn[ye.cursor];if(a){Ve(null),de(a.uuid),Pe.current={uuid:a.uuid,firstPrompt:a.firstPrompt,titleFired:!0},rt(a.name),Ur(a.uuid),nt.current=[];let g=Ar(e,a.uuid);for(let d of g)u(d);u({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){Ve(a=>a&&{...a,query:a.query.slice(0,-1),cursor:0});return}if(l&&!i.ctrl&&!i.meta&&l.length===1){Ve(a=>a&&{...a,query:a.query+l,cursor:0});return}return}if(i.tab&&!R&&ke){k(ke),se(null),Qe.current++;return}if(!R&&Pt.length>0&&l&&/^[1-9]$/.test(l)){let a=Pt[Number(l)-1];if(a){k(a);return}}if(!R&&(uo||so)&&l==="c"&&!i.ctrl&&!i.meta&&!i.return&&!i.tab){let a=uo!=null;ga(uo??so).then(d=>{u({kind:"note",tone:d?"ok":"warn",text:d?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."}),d&&a&&po(null)});return}if(!us(l,i)){if(ts){if(i.upArrow){et(a=>Math.max(0,a-1));return}if(i.downArrow){et(a=>Math.min(jt.length-1,a+1));return}if(i.tab){k("/"+(jt[Tt]?.name??"")+" "),et(0);return}if(i.return){let a=jt[Tt];if(a){let g=R.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ss(a.usage)&&!g){k("/"+a.name+" "),et(0);return}un("/"+a.name+(g?" "+g:""));return}}}else{if(i.upArrow){if(R!==""&&tt===null){dn(-1);return}let a=to.current;if(!a.length)return;let g=tt===null?a.length-1:Math.max(0,tt-1);Jt(g),k(a[g]??"");return}if(i.downArrow){if(R!==""&&tt===null){dn(1);return}let a=to.current;if(tt===null)return;let g=tt+1;g>=a.length?(Jt(null),k("")):(Jt(g),k(a[g]??""));return}}if(i.return){un();return}if(i.backspace||i.delete){P();return}if(i.escape){k(""),et(0),se(null),B([]),Zt(null);return}l&&!i.ctrl&&!i.meta&&ls(l)}}}),ve(()=>{if(N||q)return;let l=Ge.current.shift();l!==void 0&&(oo([...Ge.current]),un(l))},[N,q,un]),H(Z,{flexDirection:"column",width:Ye,children:[mo!==null&&H(Z,{marginTop:1,flexDirection:"column",children:[mo.truncated&&S(T,{dimColor:!0,children:"\u2026"}),S(T,{children:mo.text})]}),N&&(Kr?S(Hp,{p:Kr}):S(Wp,{startTime:We.current,chars:Ja})),S(Z,{borderStyle:"round",borderColor:es.prod?"yellow":V,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:R?cs.map((l,i)=>{let a=b.text.slice(l.start,l.end),g=i===Xn(cs,b.pos),d=Math.min(b.pos,l.end)-l.start;return H(T,{children:[S(T,{color:V,children:i===0?"> ":" "}),g?H(Fr,{children:[a.slice(0,d),S(Zn,{ch:a[d]??" "}),a.slice(d+1)]}):a||" "]},`${i}-${l.start}`)}):H(T,{children:[S(T,{color:V,children:"> "}),ke&&!N?H(Fr,{children:[S(Zn,{ch:ke[0],dim:!0}),S(T,{color:"gray",children:ke.slice(1)}),S(T,{dimColor:!0,children:" (tab)"})]}):fo.isSetup||!Xa?H(Fr,{children:[S(Zn,{ch:fo.text[0],dim:!0}),S(T,{color:"gray",children:fo.text.slice(1)})]}):S(Zn,{ch:" "})]})}),zr.length>0&&S(Z,{flexDirection:"column",paddingX:1,children:zr.map((l,i)=>S(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${i}-${l.slice(0,24)}`))}),Fe?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Select model"}),S(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),$e.map((l,i)=>H(T,{color:i===Fe.cursor?V:void 0,children:[i===Fe.cursor?"\u276F ":" ",`${i+1}. ${l.label}${i===Fe.current?" \u2714":""}`.padEnd(16),S(T,{color:"gray",children:l.desc})]},l.label)),S(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):Te?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Switch connection profile"}),Te.rows.map((l,i)=>H(T,{color:i===Te.cursor?V:void 0,children:[i===Te.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===Te.current?" \u2714":""}`.padEnd(20),S(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?S(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),S(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Ee?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Pick your Document360 environment"}),Ee.rows.map((l,i)=>H(T,{color:i===Ee.cursor?V:void 0,children:[i===Ee.cursor?"\u276F ":" ",`${i+1}. ${l.name}`.padEnd(16),S(T,{color:"gray",children:l.apiUrl})]},l.name)),S(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ie?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Switch workspace"}),S(T,{dimColor:!0,children:`environment ${ie.environment} \xB7 project ${ie.projectName??`${ie.projectId.slice(0,8)}\u2026`}`}),ie.rows.map((l,i)=>H(T,{color:i===ie.cursor?V:void 0,children:[i===ie.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===ie.current?" \u2714":""}`.padEnd(30),S(T,{color:"gray",children:l.type??""})]},l.id)),S(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):he?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Choose project"}),S(T,{dimColor:!0,children:`environment ${he.environment}`}),he.rows.map((l,i)=>H(T,{color:i===he.cursor?V:void 0,children:[i===he.cursor?"\u276F ":" ",`${i+1}. ${l.name}${i===he.current?" \u2714":""}`.padEnd(30),S(T,{color:"gray",children:l.sub??""})]},l.id)),S(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ue?(()=>{let i=Math.min(Math.max(0,ue.cursor-Math.floor(7)),Math.max(0,ue.rows.length-14)),a=ue.rows.slice(i,i+14),g=ue.rows.filter(d=>d.checked).length;return H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:`Which folders back the user docs? (${g} selected of ${ue.rows.length})`}),i>0?S(T,{dimColor:!0,children:` \u2191 ${i} more`}):null,a.map((d,m)=>{let y=i+m;return H(T,{color:y===ue.cursor?V:void 0,children:[y===ue.cursor?"\u276F ":" ",d.checked?"\u25C9 ":"\u25CB ",d.path.padEnd(Math.min(48,Ye-34)),S(T,{color:"gray",children:En(d)})]},d.path)}),i+14<ue.rows.length?S(T,{dimColor:!0,children:` \u2193 ${ue.rows.length-i-14} more`}):null,S(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():qe?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),qe.rows.map((l,i)=>{let a=i===qe.cursor,g=l.indent?" ":" ",d=`${i+1}.`.padEnd(3);return H(T,{color:a?V:void 0,bold:l.kind==="category"&&!a,children:[a?"\u276F ":" ",`${g}${d} ${l.label}`.padEnd(Math.min(56,Ye-24)),l.note?S(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),S(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ge?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:`Preview article${ge.query?` \u2014 filter: ${ge.query}`:" (type to filter)"}`}),on.length===0?S(T,{color:"gray",children:"no articles match"}):on.map((l,i)=>H(T,{color:i===ge.cursor?V:void 0,children:[i===ge.cursor?"\u276F ":" ",l]},l)),S(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):ye?H(Z,{flexDirection:"column",paddingX:1,children:[S(T,{color:V,bold:!0,children:`Resume session${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),rn.length===0?S(T,{color:"gray",children:"no sessions match"}):rn.map((l,i)=>H(T,{color:i===ye.cursor?V:void 0,children:[i===ye.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),S(T,{color:i===ye.cursor?V:"gray",children:l.firstPrompt.slice(0,Math.max(10,Ye-40))})]},l.uuid)),S(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ts?S(Z,{flexDirection:"column",children:jt.map((l,i)=>H(T,{color:i===Tt?V:void 0,children:[i===Tt?"\u276F ":" ",l.usage.padEnd(22)," ",S(T,{color:i===Tt?V:"gray",children:l.name==="model"&&ro?`${l.desc} (currently ${ro})`:l.desc})]},l.name))}):!R&&Pt.length>0?H(Z,{flexDirection:"column",paddingX:1,children:[Yr?S(T,{color:V,children:Yr}):null,Pt.map((l,i)=>H(T,{children:[S(T,{color:V,children:i+1})," ",l.slice(0,Math.max(20,Ye-5))]},l)),S(T,{dimColor:!0,children:`press 1-${Pt.length} to fill the command \xB7 esc dismiss`})]}):S(Z,{paddingX:1,children:H(T,{color:"gray",children:[es.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${ro??"model n/a"}${t.kind==="api"?Jr>0?` \xB7 ${le(Jr)}`:"":Xr>0?` \xB7 ${Ue(Xr)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Vp}from"react/jsx-runtime";async function Ya(e=process.cwd(),t="auto",n,o="0.0.0"){let r=Gp(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${I("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${I("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Bp(Vp(Va,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
291
+ `),process.exit(0)}var Xp=zp(import.meta.url),za=Xp("../package.json"),je=new Yp;function qr(e){e.env&&(console.error("\u2717 --env was replaced by --profile (connection profiles). Use: --profile <name>"),process.exit(2))}je.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=>{qr(e),await hn({profile:e.profile,manual:e.manual})});je.command("logout").description("Remove the stored Document360 session").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qr(e),await $s({profile:e.profile})});je.command("whoami").description("Show the current Document360 identity (refreshes if expired)").option("--profile <name>","Connection profile").option("--env <name>",!1).action(async e=>{qr(e),await xs({profile:e.profile})});var Br=je.command("profile").description("Manage connection profiles for the current repo");Br.command("list",{isDefault:!0}).description("List profiles (\u25CF = default)").action(()=>gn(process.cwd()));Br.command("use <name>").description("Set the default profile for this repo").action(e=>wn(process.cwd(),e));Br.command("show [name]").description("Print the resolved profile (connection + project)").action(e=>yn(process.cwd(),e));var Ka=je.command("workspace").description("Choose the Document360 workspace for this repo (active profile's project)");Ka.command("select",{isDefault:!0}).description("Interactively pick the workspace (lists in non-TTY)").option("--profile <name>","Connection profile").action(e=>ht(process.cwd(),e.profile));Ka.command("use <name>").description("Set the workspace by name (scriptable)").option("--profile <name>","Connection profile").action(async(e,t)=>{process.exitCode=await fs(process.cwd(),e,t.profile)});je.command("logs").description("Show the Document360 API log files (send these to support when reporting a problem)").action(()=>Cs());je.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(()=>(On(),Fi)),n=await t(process.cwd());for(let o of e(n))console.log(o);process.exitCode=n.some(o=>o.level==="fail")?1:0});je.name("d360-writer").description("Standalone documentation agent CLI. Reads your code, writes your docs.").version(za.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(Kp.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 Ps(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 ma(e.cwd,e.auth,e.profile):await Ya(e.cwd,e.auth,e.profile,za.version)});je.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.4.98",
3
+ "version": "0.5.0",
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.52",
37
+ "document360-engine": "^0.2.53",
38
38
  "ink": "^5.2.1",
39
39
  "picocolors": "^1.1.1",
40
40
  "react": "^18.3.1",