document360-writer 0.5.12 → 0.5.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +13 -13
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Il=Object.defineProperty;var Io=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Nl=(e,t)=>{for(var n in t)Il(e,n,{get:t[n],enumerable:!0})};import We from"picocolors";var M,_l,Ol,Ul,Ss,Ft,m,$,U,E,O,oe,
|
|
2
|
+
var Il=Object.defineProperty;var Io=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var Nl=(e,t)=>{for(var n in t)Il(e,n,{get:t[n],enumerable:!0})};import We from"picocolors";var M,_l,Ol,Ul,Ss,Ft,m,$,U,E,O,oe,Te,W=Io(()=>{"use strict";M="#7f56d9",[_l,Ol,Ul]=[127,86,217],Ss=e=>We.isColorSupported?`\x1B[38;2;${_l};${Ol};${Ul}m${e}\x1B[39m`:e,Ft=e=>We.bold(Ss(e)),m=e=>We.dim(e),$=e=>We.red(e),U=e=>We.yellow(e),E=e=>We.green(e),O=Ss,oe=e=>We.gray(e),Te=e=>We.bold(e)});import{existsSync as Dn,writeFileSync as Bt,readFileSync as xc,readdirSync as $c}from"node:fs";import{join as vc}from"node:path";import{devHintsGuidePath as jn,hintsDir as Vs,architectureDir as Xs,messagesDir as Mo,creatorNotesPath as zs,devhintsStatePath as Js,ensureDir as Sn,writeMessage as Cc,listOpenForDev as Pc}from"document360-engine";function Qs(){return`# Dev \u2192 Docs hand-off \u2014 protocol guide
|
|
3
3
|
|
|
4
4
|
<!-- devhints script v${ne} \xB7 maintained by document360-writer (/devhints). -->
|
|
5
5
|
|
|
@@ -179,7 +179,7 @@ Anything only a human knows that would help document this product. For example:
|
|
|
179
179
|
`)}function Gt(e){try{return $c(Xs(e)).some(t=>/\.md$/i.test(t)&&t.toLowerCase()!=="creator-notes.md")}catch{return!1}}function Ee(e){let n=Wo(e)?.completedVersion;return typeof n!="number"?{status:"unset"}:{status:n<ne?"stale":"current",completedVersion:n}}function An(e,t=new Date().toISOString()){let n={guideRefreshed:!1,notifiedBuilder:!1,toVersion:ne};try{if(!Dn(jn(e)))return n;let o=Wo(e),r=o?.emittedVersion??0;n.completedVersion=o?.completedVersion;let s=o?.completedVersion??0;ne>r&&(Sn(Mo(e)),Bt(jn(e),Qs()),ei(e,t),n.guideRefreshed=!0),ne>s&&(Pc(e).some(p=>p.kind==="request"&&p.subject.startsWith(Ks))||(Cc(e,{id:`onb${ne}`,created:t,from:"docs",kind:"request",re:"",sources:[],subject:`${Ks}${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:","",nt()].join(`
|
|
180
180
|
`)}),n.notifiedBuilder=!0))}catch{}return n}function En(e){if(!Dn(jn(e)))return[];let t=Ee(e);return t.status==="current"?[]:[`\u{1F514} Your builder agent ${t.completedVersion?`is on v${t.completedVersion}`:"hasn't completed the hand-off yet"} \u2014 d360-writer's dev\u2194docs protocol is now v${ne}.`,"Please run this prompt in your repository's coding agent (Claude Code / Codex / Cursor) for:",` ${e}`,vt,nt(),vt,"(Also saved in .d360-writer/messages/ \u2014 or run /devhints to re-show. This stops once your builder runs it.)"]}function Fo(){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
181
|
`)}function In(){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):",vt,Fo(),vt]}function Pt(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):",vt,nt(),vt,"","That one run writes the architecture brief, adds the ongoing rule to your agent memory (CLAUDE.md / AGENTS.md)","and commits it so teammates inherit it, answers any open questions the writer left, and asks you for tribal","knowledge \u2014 no manual file edits. It also sets up the two-way channel: the writer can ask you questions","(`/inbox` on its side), and you can ask it to document a session on demand (Part 4 of the guide).","","When it finishes, come back to THIS terminal and run:"," write the docs for this repo"]}var vt,ne,Ks,ot=Io(()=>{"use strict";vt="-".repeat(64),ne=5;Ks="Re-run dev\u2194docs onboarding (protocol v"});var ra={};Nl(ra,{doctorCommand:()=>Zt,renderDoctorChecks:()=>oa,runDoctorChecks:()=>na});import{existsSync as Zi}from"node:fs";import{d360GetAll as nd,getAccessToken as od,isExpired as Sr,loadProfileMap as rd,loadTokens as sd,packageSkillsDir as ea,projectConfigPath as id,readProjectConfig as ad,DEFAULT_DOCS_DIR as ld,resolveActiveProfile as cd,classifyClaudeAuth as ud,CLAUDE_CODE_SETUP_HINT as ta,resolveModelSetting as dd,probeModel as pd,devHintsGuidePath as fd}from"document360-engine";async function na(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=ud();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. ${ta}`}):t.push({level:"fail",label:"Claude: not signed in \u2014 the agent cannot run (no Claude Code credentials on this machine)",fix:ta});let r=dd(e);if(t.push({level:"ok",label:`Model: ${r.model??"Claude Code default"} (${r.source})`}),o.state==="ready"){let w=await pd(e,r.model??void 0);w.ok?t.push({level:"ok",label:`Model reachable \u2014 replied in ${(w.latencyMs/1e3).toFixed(1)}s`}):w.timedOut?t.push({level:"fail",label:"Model unreachable \u2014 no response in 30s (a docs turn will hang, then end with 0 tokens / no output)",fix:`Usually a corporate proxy/firewall or org policy blocking the Claude model API. Check this machine's network access to the Claude endpoint; confirm with: claude -p "say hi"`}):t.push({level:"fail",label:`Model call failed \u2014 ${w.error??"no output"} (a docs turn will end with 0 tokens / no output)`,fix:'Check sign-in, the selected model (/model), and network access to the Claude endpoint; confirm with: claude -p "say hi"'})}let s=ad(e);if(!s)return t.push({level:"fail",label:`No ${id(e)}`,fix:"Run: /init (or d360-writer init)"}),t;t.push({level:"ok",label:`Project config: ${s.projectId}`});let c=(s.docsDir??ld).replace(/\/+$/,"");t.push(s.mode==="engineer"?{level:"warn",label:"Mode: engineer \u2014 agent may modify any source file (dogfooding)",fix:'Remove "mode" from .d360-writer/config.json for the writer-mode boundary'}:{level:"ok",label:`Mode: writer \u2014 edits limited to ${c}/ and .d360-writer/ (docs, capture specs, config); product source is read-only`});let p=s.authoritativeSourceFiles??[];t.push(p.length>0?{level:"ok",label:`Sources: docs grounded in ${p.length} path(s) (${p.slice(0,3).join(", ")}${p.length>3?", \u2026":""})`}:{level:"warn",label:"Sources: not set \u2014 docs are grounded in the whole repo",fix:"Run: /scope to choose which files/folders the docs are written from"});let f;try{f=cd(e),t.push({level:"ok",label:`Profile: ${f.name} (${f.connection.name})${f.production?" \u26A0 PRODUCTION":""}`})}catch(w){return t.push({level:"fail",label:`Profile config: ${w.message.split(".")[0]}`,fix:"Run: /init to scaffold the profiles map"}),t}let b=sd(f.name);b?Sr(b)&&!b.refreshToken?t.push({level:"fail",label:"Document360: session expired (no refresh token)",fix:"/login"}):Sr(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 ${f.name})`}),t.push(f.project.workspaceId?{level:"ok",label:`Workspace: ${f.project.workspaceName??f.project.workspaceId}`}:{level:"warn",label:"No workspace selected",fix:"Run: /workspace"});let k=rd(e,f.name);k?k.projectId&&f.project.projectId&&k.projectId!==f.project.projectId?t.push({level:"fail",label:`Category map projectId (${k.projectId}) \u2260 profile projectId (${f.project.projectId})`,fix:"The map section belongs to a different project \u2014 fix .d360-writer/config.json or the map before publishing"}):t.push({level:"ok",label:`Category map: ${Object.keys(k.articles).length} articles, ${Object.keys(k.categories).length} categories`}):t.push({level:"ok",label:`Category map: none yet for "${f.name}" (created on first /publish)`}),t.push(Zi(ea())?{level:"ok",label:"Skills bundle present"}:{level:"fail",label:`Skills folder missing at ${ea()}`,fix:"Reinstall document360-writer (broken install)"});let A=Ee(e);if((Zi(fd(e))||A.status!=="unset")&&(A.status==="current"?t.push({level:"ok",label:`Dev hand-off: builder up to date (devhints v${ne})`}):A.status==="stale"?t.push({level:"warn",label:`Dev hand-off: builder on devhints v${A.completedVersion}, current is v${ne}`,fix:"Run /devhints and have the repo's coding agent re-run the prompt (adds two-way messages + on-demand docs)"}):t.push({level:"warn",label:"Dev hand-off: guide emitted but the builder hasn't completed it",fix:"Have the repo's coding agent run the /devhints prompt (sets up the two-way channel)"})),b&&(!Sr(b)||b.refreshToken)){let w={profile:f.name,connection:f.connection};try{await od(w);let P=await nd(w,"/v3/projects");t.push({level:"ok",label:`API reachable (${f.connection.apiUrl}) \u2014 ${P.length} project(s) visible`})}catch(P){t.push({level:"fail",label:`API call failed: ${P.message.slice(0,120)}`,fix:"/login if auth-related; otherwise check the apiUrl/network"})}}return t}function oa(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?m(` \u2014 ${r.detail}`):""}`),r.fix&&t.push(` ${m("fix:")} ${O(r.fix)}`)}let n=e.filter(r=>r.level==="fail").length,o=e.filter(r=>r.level==="warn").length;return t.push(""),t.push(n===0?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 Zt(e,t){console.log(m("Running checks\u2026"));for(let n of oa(await na(t.cwd)))console.log(n);return{kind:"continue"}}var qn=Io(()=>{"use strict";ot();W()});import{Command as If}from"commander";import{createRequire as Nf}from"node:module";import{AUTH_MODES as _f}from"document360-engine";import{input as Jl}from"@inquirer/prompts";import{loginPkce as Ql,refreshTokens as Zl,toStoredTokens as _s,clearTokens as ec,decodeJwtClaims as Ns,isExpired as tc,loadTokens as nc,saveTokens as Os,resolveActiveProfile as $n,setProfileProject as oc,readProjectConfig as rc}from"document360-engine";W();import{select as Ll}from"@inquirer/prompts";import{resolveActiveProfile as Ml,setProfileProject as Wl,resolveProjectId as Fl,listWorkspaces as Hl}from"document360-engine";async function Ht(e,t){let n=Ml(e,t),o={profile:n.name,connection:n.connection},r=n.project.projectId??Fl(o);return{workspaces:await Hl(o,r),projectId:r,projectName:n.project.projectName,profile:n.name,environment:n.connection.name,current:n.project.workspaceId}}var Ds=e=>`${e.name??e.id}${e.workspace_type?` \xB7 ${e.workspace_type}`:""}`;function No(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 xn(e,t,n,o,r){Wl(e,t,{projectId:n,workspaceId:o,workspaceName:r})}async function js(e,t,n){let o;try{o=await Ht(e,n)}catch(s){return console.log($(`Could not list workspaces: ${s.message}`)),1}let r=No(o.workspaces,t);return r?(xn(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 $t(e,t){let n;try{n=await Ht(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(m("No workspaces found in this project."));return}if(!process.stdin.isTTY){console.log("");for(let b of o)console.log(` ${b.id===c?O("\u25CF"):" "} ${Ds(b)} ${m(b.id)}`);console.log(m("Run: d360-writer workspace use <name>"));return}let p=await Ll({message:"Select the Document360 workspace for this repo:",choices:o.map(b=>({name:`${Ds(b)}${b.id===c?" (current)":""}`,value:b.id}))}),f=o.find(b=>b.id===p);xn(e,s,r,p,f?.name),console.log(E(`\u2713 Workspace set to "${f?.name??p}" for profile "${s}".`))}W();import{select as ql}from"@inquirer/prompts";import{resolveActiveProfile as Bl,setProfileProject as Gl,listProjects as Yl}from"document360-engine";async function tt(e,t){let n=Bl(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 As=e=>`${e.name??e.id}${e.sub_domain?` \xB7 ${e.sub_domain}`:""}`;function Es(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){Gl(e,t,{projectId:n,projectName:o,workspaceId:void 0,workspaceName:void 0})}async function Is(e,t){let n;try{n=await tt(e,t)}catch(f){console.log($(`Could not list projects: ${f.message}`));return}let{projects:o,profile:r,current:s}=n;if(o.length===0){console.log(m("No projects found for this identity."));return}if(!process.stdin.isTTY){console.log("");for(let f of o)console.log(` ${f.id===s?O("\u25CF"):" "} ${As(f)} ${m(f.id)}`);console.log(m("Run: d360-writer project use <name>"));return}let c=await ql({message:"Select the Document360 project for this repo:",choices:o.map(f=>({name:`${As(f)}${f.id===s?" (current)":""}`,value:f.id}))}),p=o.find(f=>f.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 Vl from"picocolors";function zl(e=process.env){return e.FORCE_HYPERLINK==="0"||!Vl.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 Kl(e,t=e,n){return zl(n)?`\x1B]8;;${e}\x07${t}\x1B]8;;\x07`:t}var Xl=/https?:\/\/[^\s\x1b]+/g;function qt(e,t){return e.replace(Xl,n=>Kl(n,n,t))}function Us(e){return{...Ns(e.idToken)??{},...Ns(e.accessToken)??{}}}function vn(e){let t=Us(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 Cn(e){let t=$n(process.cwd(),e.profile),n=t.connection;console.log(m(`Profile "${t.name}" \u2192 ${n.name} (${n.apiUrl})${t.production?" \u26A0 PRODUCTION":""}`));let o=await Ql(n,{manual:e.manual,promptForRedirect:s=>Jl({message:s})},s=>console.log(qt(s))),r=_s(t.name,o);if(Os(r),await Oo(r,t.name,s=>console.log(m(s))),console.log(""),console.log(E(`\u2713 Logged in to "${t.name}" as ${vn(r)}`)),console.log(m(` access token expires: ${r.expiresAt}`)),console.log(m(` refresh token: ${r.refreshToken?"yes":"NO \u2014 session ends at expiry"}`)),process.stdin.isTTY)try{rc(process.cwd())?.profiles?.[t.name]&&(console.log(""),await $t(process.cwd(),t.name))}catch{}}async function Oo(e,t,n){let r=Us(e).doc360_project_id;if(!(typeof r!="string"||!r))try{if($n(process.cwd(),t).project.projectId)return;let c;try{let{projects:p}=await tt(process.cwd(),t);c=p.find(f=>f.id===r)?.name}catch{}oc(process.cwd(),t,{projectId:r,projectName:c}),n(` Project "${c??r}" written to profile "${t}".`)}catch{}}async function Ls(e){let t=$n(process.cwd(),e.profile),n=t.connection,o=nc(t.name);if(!o){console.log($(`Not logged in to Document360 (profile "${t.name}").`)),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;return}if(console.log(`Profile ${O(t.name)}${t.production?" \u26A0 PRODUCTION":""}: ${vn(o)}`),tc(o))if(o.refreshToken)try{let r=_s(t.name,await Zl(n,o.refreshToken));Os(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(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1}else console.log(U("Session expired (no refresh token).")),console.log(m(`Run: d360-writer login --profile ${t.name}`)),process.exitCode=1;else console.log(m(` expires: ${o.expiresAt}`))}async function Ms(e){let t=$n(process.cwd(),e.profile);ec(t.name)?console.log(E(`\u2713 Logged out of Document360 (profile "${t.name}").`)):console.log(m(`No Document360 session for profile "${t.name}" \u2014 nothing to do.`))}W();import{readProjectConfig as Ws,writeProjectConfig as sc,resolveActiveProfile as ic,loadTokens as ac,isExpired as lc}from"document360-engine";function Pn(e){let t=Ws(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?O("\u25CF "):" ",s=o.production?U(" \u26A0 PRODUCTION"):"",c=o.connection.environment??"(inline)",p=ac(n),f=p?lc(p)&&!p.refreshToken?U("expired"):m("logged in"):m("not logged in");console.log(`${r}${O(n)} \u2192 ${c}${s} [${f}]`)}console.log(""),console.log(m("\u25CF = default. Switch with: d360-writer profile use <name>")),console.log("")}function Tn(e,t){let n=Ws(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,sc(n,e);let o=n.profiles[t].production?U(" \u26A0 PRODUCTION"):"";console.log(E(`\u2713 Default profile is now "${t}"${o}`))}function Rn(e,t){try{let n=ic(e,t);console.log(""),console.log(`Profile ${O(n.name)}${n.production?U(" \u26A0 PRODUCTION"):""}`),console.log(m(` api: ${n.connection.apiUrl}`)),console.log(m(` identity: ${n.connection.authorizationUrl}`)),console.log(m(` clientId: ${n.connection.clientId}`)),console.log(m(` scopes: ${n.connection.scopes.join(" ")}`)),console.log(m(` project: ${n.project.projectId??"(set at login)"}`)),console.log(m(` workspace:${n.project.workspaceId?" "+n.project.workspaceId:" (none)"}`)),console.log("")}catch(n){console.log($(n.message)),process.exitCode=1}}W();import{existsSync as cc,readdirSync as uc,statSync as Fs}from"node:fs";import{join as Hs}from"node:path";import{apiLogDir as dc}from"document360-engine";function qs(){let e=dc();if(console.log(""),console.log(`Document360 API logs: ${O(e)}`),!cc(e)){console.log(m(" No logs yet \u2014 they appear after the first Document360 API call.")),console.log("");return}let t=uc(e),n=t.filter(r=>r.endsWith(".jsonl")).sort().reverse(),o=t.filter(r=>/^crash-\d{4}-\d{2}-\d{2}\.log$/.test(r)).sort().reverse();n.length===0&&o.length===0&&console.log(m(" No logs yet \u2014 they appear after the first Document360 API call."));for(let r of n.slice(0,14)){let s=(Fs(Hs(e,r)).size/1024).toFixed(1);console.log(` ${r} ${m(`${s} KB`)}`)}if(o.length>0){console.log(""),console.log(`Crash logs ${m("(send these if d360-writer crashed or a run died)")}:`);for(let r of o.slice(0,14)){let s=(Fs(Hs(e,r)).size/1024).toFixed(1);console.log(` ${$(r)} ${m(`${s} KB`)}`)}}console.log(""),console.log(m("Failed calls include request/response bodies (tokens redacted, 4 KB cap).")),console.log(m("Set D360_LOG_BODIES=1 to also log bodies for successful calls.")),console.log("")}W();import{createSession as pc,resolveAuth as fc,findByName as mc,slugify as hc,touchSession as gc,upsertSession as wc,resolveActiveProfile as yc}from"document360-engine";async function Bs(e,t,n,o,r,s){let c=fc(n);c.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2)),c.kind==="subscription"&&console.error(m("Using your Claude subscription (no API key set)."));let p=null;try{p=yc(e,r)}catch(w){console.error($(`Document360 profile error: ${w.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(m(" --yes given \u2014 proceeding against production.")));let f;if(o){let w=mc(e,o);w||(console.error($(`No saved session matches "${o}" in this repo.`)),console.error(m("List sessions inside the REPL with /resume.")),process.exit(2)),f=w.uuid,console.error(m(`Resuming "${w.name}"`))}let b=pc({cwd:e,resume:f,profileName:r,allowProdWrites:s===!0}),k=f??null,A=1;for await(let w of b.send(t))switch(w.type){case"session":if(!k){k=w.sessionId;let P=new Date().toISOString();wc({uuid:k,name:hc(t),renamed:!1,titled:!1,cwd:e,firstPrompt:t,createdAt:P,updatedAt:P})}break;case"text":process.stdout.write(w.delta);break;case"tool":console.error(oe(` \u2699 ${w.name}`));break;case"result":A=w.ok?0:1,console.error(m(`(${w.inputTokens}\u2192${w.outputTokens} tokens`+(w.costUsd>0?`, $${w.costUsd<.01?w.costUsd.toFixed(4):w.costUsd.toFixed(2)}`:"")+")")),w.ok||console.error($("agent finished with an error result"));break;case"error":console.error(""),console.error($(`agent error: ${w.message}`)),process.exit(1)}k&&gc(k),process.stdout.write(`
|
|
182
|
-
`),process.exit(A)}import{createInterface as np}from"node:readline/promises";import{createSession as Br,resolveAuth as op,getSession as rp,setTitle as sp,slugify as ip,touchSession as Da,upsertSession as ap,generateTitle as lp,resolveActiveProfile as ja,resolveModelSetting as cp,readProjectConfig as up,decodeJwtClaims as Ra,isExpired as dp,loadTokens as pp}from"document360-engine";var
|
|
182
|
+
`),process.exit(A)}import{createInterface as np}from"node:readline/promises";import{createSession as Br,resolveAuth as op,getSession as rp,setTitle as sp,slugify as ip,touchSession as Da,upsertSession as ap,generateTitle as lp,resolveActiveProfile as ja,resolveModelSetting as cp,readProjectConfig as up,decodeJwtClaims as Ra,isExpired as dp,loadTokens as pp}from"document360-engine";var xe=[{key:"start",label:"Getting Started",rows:[{t:"text",s:"D360-Writer reads your codebase, generates end-user documentation, and publishes it to Document360."},{t:"text",s:"It needs Claude access \u2014 a Claude subscription (default) or an ANTHROPIC_API_KEY."},{t:"gap"},{t:"sub",s:"Quick start"},{t:"step",n:1,s:"Run /init \u2014 pick your environment, sign in, choose your project & workspace. It ends by printing a one-paste hand-off prompt."},{t:"step",n:2,s:"Paste that prompt into your repo's coding agent (Claude Code / Codex / Cursor). Let it finish, then follow its closing line. (Re-show it: /devhints)"},{t:"step",n:3,s:"Run /doctor to confirm every check is green."},{t:"step",n:4,s:'Type "write the docs for this repository" and follow the prompts.'},{t:"gap"},{t:"dim",s:"That's it \u2014 D360-Writer drafts your docs without you writing a line."},{t:"gap"},{t:"sub",s:"Tips"},{t:"text",s:"Just talk to it \u2014 anything not starting with / goes to the agent."},{t:"dim",s:"/ browses commands \xB7 \u2191 recalls history \xB7 esc interrupts a run \xB7 ctrl+c exits"}]},{key:"agentic",label:"Agentic",rows:[{t:"dim",s:"Agentic and Assistant aren't a setting you switch \u2014 just two ways to drive the same tool."},{t:"gap"},{t:"text",s:"D360-Writer works autonomously, like a technical writer dedicated to your project. Your coding agent leaves notes as it ships; you just run the loop."},{t:"gap"},{t:"sub",s:"Every few days"},{t:"cmd",name:"/catch-up --publish",s:"Analyze the latest code changes, update the docs, and publish."},{t:"dim",s:" (or run /catch-up for drafts, then /publish when you are ready)"},{t:"gap"},{t:"sub",s:"Whenever you need"},{t:"cmd",name:"/audit",s:"Preview what changed and what's missing \u2014 writes nothing."},{t:"cmd",name:"/sync",s:"Pull edits made in the Document360 portal; reconcile drift."},{t:"cmd",name:"/inbox",s:"Act on messages from your coding agent."}]},{key:"assistant",label:"Assistant",rows:[{t:"text",s:"D360-Writer is your writing assistant \u2014 it does the writing, you decide what gets written and when."},{t:"text",s:"Best for large or complex monorepos: focus it on one feature, component, or set of source folders."},{t:"gap"},{t:"sub",s:"Just ask"},{t:"good",s:'"Write the documentation for the Multiple JWT feature we shipped in the latest release."'},{t:"gap"},{t:"sub",s:"Or use the pipeline"},{t:"cmd",name:"/scope",s:"Focus D360-Writer on specific source folders (monorepos)."},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from its PRDs in .d360-writer/input/ + the code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview shows the plan + cost first)."},{t:"cmd",name:"/publish",s:"Publish the articles to Document360."}]},{key:"shots",label:"Screenshots",rows:[{t:"text",s:"Documenting a web app? D360-Writer marks where an image helps with a <!-- SCREENSHOT --> placeholder."},{t:"text",s:"The companion CLI d360-capture turns those into real, annotated screenshots by driving your app in a browser."},{t:"gap"},{t:"sub",s:"Flow"},{t:"step",n:1,s:"Write your docs as usual \u2014 placeholders are added where visuals help."},{t:"step",n:2,s:"Run /screenshot --all to author capture specs and refresh the capture checklist (data + test-ids the shots need)."},{t:"step",n:3,s:"Stage what the checklist asks for, then run d360-capture in your app's repo \u2014 it signs in, navigates, captures, annotates."},{t:"step",n:4,s:"Re-run /publish so the images go live on Document360."},{t:"gap"},{t:"sub",s:"Helpers"},{t:"cmd",name:"/screenshot --list",s:"See capture status \u2014 which specs exist and which are done."},{t:"cmd",name:"/capture-setup",s:"Re-show the data-staging + test-id checklist (auto-runs after /screenshot --all)."},{t:"gap"},{t:"dim",s:"d360-capture is a separate Playwright CLI \u2014 run it in the app's repo (needs its URL + a login)."}]},{key:"cmds",label:"Commands",rows:[{t:"dim",s:"Grouped by job. Type any command, or just talk to the agent."},{t:"gap"},{t:"sub",s:"Getting started"},{t:"cmd",name:"/init",s:"Set up Document360 (environment, sign-in, project, hand-off prompt)."},{t:"cmd",name:"/login",s:"Sign in to Document360."},{t:"cmd",name:"/project",s:"Choose the Document360 project."},{t:"cmd",name:"/workspace",s:"Switch the workspace."},{t:"cmd",name:"/scope",s:"Choose which repo folders back the docs (monorepos)."},{t:"cmd",name:"/devhints",s:"Re-show the builder hand-off prompt."},{t:"gap"},{t:"sub",s:"Agentic \u2014 keep docs in sync"},{t:"cmd",name:"/catch-up",s:"Do all pending work \u2192 drafts (--publish goes live)."},{t:"cmd",name:"/publish",s:"Publish to Document360 (--all or a path)."},{t:"cmd",name:"/audit",s:"Preview what changed / what's missing."},{t:"cmd",name:"/sync",s:"Pull portal edits; reconcile drift."},{t:"cmd",name:"/inbox",s:"Act on your coding agent's messages."},{t:"gap"},{t:"sub",s:"Assistant \u2014 directed writing"},{t:"cmd",name:"/draft <feature>",s:"Plan a feature's articles from PRDs + code."},{t:"cmd",name:"/write",s:"Write the planned articles (--preview first)."},{t:"cmd",name:"/preview",s:"Render an article locally."},{t:"gap"},{t:"sub",s:"Screenshots"},{t:"cmd",name:"/screenshot",s:"Author capture specs (--all / --list)."},{t:"gap"},{t:"sub",s:"Setup & health"},{t:"cmd",name:"/model",s:"Set the Claude model."},{t:"cmd",name:"/profile",s:"Switch/create a Document360 connection."},{t:"cmd",name:"/mcp",s:"Connect MCP servers (Notion, Linear, \u2026)."},{t:"cmd",name:"/allow-prod",s:"Authorize writes to a production profile."},{t:"cmd",name:"/doctor",s:"Health check: auth, profile, workspace, API."},{t:"cmd",name:"/update",s:"Update D360-Writer."},{t:"cmd",name:"/reset",s:"Delete all D360-Writer files (confirms first)."},{t:"gap"},{t:"sub",s:"Session"},{t:"cmd",name:"/resume",s:"Resume a saved session."},{t:"cmd",name:"/rename",s:"Name the session."},{t:"cmd",name:"/clear",s:"Reset the conversation (resumable)."},{t:"cmd",name:"/help",s:"Show this help."},{t:"cmd",name:"/exit",s:"Quit."}]}];function kc(e){switch(e.t){case"head":return e.s;case"text":return` ${e.s}`;case"dim":return` ${e.s}`;case"sub":return e.s;case"good":return` ${e.s}`;case"step":return` ${e.n}. ${e.s}`;case"cmd":return` ${e.name.padEnd(20)} ${e.s}`;case"gap":return""}}function Gs(){let e=["document360-writer \u2014 help",""];for(let t of xe){e.push(`\u2500\u2500 ${t.label} \u2500\u2500`,"");for(let n of t.rows)e.push(kc(n));e.push("")}return e.push("Tip: anything not starting with / goes to the agent."),e}async function Uo(){console.log("");for(let e of Gs())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 bc}from"document360-engine";async function Ys(e,t){let n=t.currentUuid(),o=n?bc(n):void 0;return console.log(o?m(`
|
|
183
183
|
(conversation reset \u2014 "${o.name}" is still available via /resume)
|
|
184
184
|
`):m(`
|
|
185
185
|
(conversation reset \u2014 agent will start fresh on the next prompt)
|
|
@@ -187,8 +187,8 @@ Anything only a human knows that would help document this product. For example:
|
|
|
187
187
|
`),"utf8")}async function ci(){let e=process.cwd(),t=oi(e);if(Tt(t)&&!await Rc({message:`${t} already exists. Overwrite?`,default:!1}))return console.log(m("init cancelled.")),{kind:"continue"};let n=ui(e)??ti(e),o=await Yt({message:"Project ID (used to scope sessions, screenshots, etc.):",default:n}),r=await Yt({message:"Capture directory (where document360-capture .spec.ts files live):",default:si}),s=await Yt({message:"Screenshot output directory:",default:ii}),c=await Yt({message:"Default connection profile name:",default:"berlin"}),p=await Yt({message:"Document360 environment for this profile (baked preset):",default:"berlin"}),f={projectId:o,docsDir:ri,captureDir:r,outputDir:s,profiles:{[c]:{connection:{environment:p},production:!1}},defaultProfile:c,authoritativeSourceFiles:di(e)},b=Ac(e);b?.terminologyGlossary&&(f.terminologyGlossary=b.terminologyGlossary),ni(f,e),li(e);let k=Ct(e);console.log(""),console.log(E(`\u2713 Wrote ${t}`)),console.log(""),console.log(`Next: ${O(`d360-writer login --profile ${c}`)} ${m("(sign in; project & workspace auto-selected)")}`),console.log("");for(let A of Pt(k))console.log(A);return console.log(""),console.log(`${m("Then ask:")} ${O('"write the user docs for this repo"')}`),console.log(""),{kind:"continue"}}function ui(e){let t=Nn(e,"package.json");if(!Tt(t))return null;try{return JSON.parse(Sc(t,"utf8")).name??null}catch{return null}}function di(e){let t=[];for(let n of["README.md","ARCHITECTURE.md","CLAUDE.md"])Tt(Nn(e,n))&&t.push(n);for(let n of["src","api","docs"]){let o=Nn(e,n);Tt(o)&&!Ic(o)&&t.push(n)}return t}function Ic(e){try{return Dc(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.name.startsWith(".")).length>6}catch{return!1}}W();import{readMcpConfig as Ho,writeMcpConfig as pi}from"document360-engine";async function _n(e){let t=(e[0]??"").toLowerCase();return t==="list"||!t?(Nc(),{kind:"continue"}):t==="add"?(_c(e.slice(1)),{kind:"continue"}):t==="remove"||t==="rm"?(Oc(e.slice(1)),{kind:"continue"}):(console.log($(`Unknown /mcp subcommand: ${t}`)),console.log(m("Try: /mcp add <name> <stdio|http|sse> <command-or-url>, /mcp list, /mcp remove <name>")),{kind:"continue"})}function Nc(){let e=Ho(),t=Object.keys(e.servers);if(t.length===0){console.log(m(`
|
|
188
188
|
No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
189
189
|
`));return}console.log(""),console.log("Registered MCP servers (~/.document360-writer/mcp.json):");for(let n of t){let o=e.servers[n];if(o.type==="stdio")console.log(` ${O(n)} ${m("(stdio)")} ${o.command} ${(o.args??[]).join(" ")}`);else{let r=Object.keys(o.headers??{}),s=r.length>0?m(` [headers: ${r.join(", ")}]`):"";console.log(` ${O(n)} ${m(`(${o.type})`)} ${o.url}${s}`)}}console.log("")}function _c(e){let[t,n,...o]=e;if(!t||!n||o.length===0){console.log($("Usage: /mcp add <name> <stdio|http|sse> <command-or-url> [args...] [-H key:value ...]"));return}if(n!=="stdio"&&n!=="http"&&n!=="sse"){console.log($(`Unknown transport: ${n}. Use stdio, http, or sse.`));return}let r=Ho(),s;if(n==="stdio")s={type:"stdio",command:o[0],args:o.slice(1)};else{let c={};for(let p=1;p<o.length;p++)if(o[p]==="-H"||o[p]==="--header"){let f=o[++p],b=f?.match(/^([^:=]+)[:=](.+)$/);if(!b){console.log($(`-H expects key:value (no spaces). Got: ${f??"(nothing)"}`));return}c[b[1].trim()]=b[2].trim()}else{console.log($(`Unexpected argument: ${o[p]}. After the URL, only -H key:value is allowed.`));return}s={type:n,url:o[0],headers:Object.keys(c).length>0?c:void 0}}r.servers[t]=s,pi(r),console.log(""),console.log(E(`\u2713 Registered "${t}" (${n})`)),console.log(U(" This server loads on your next prompt. The current agent session reads MCP config at startup.")),console.log(m(" Run /clear if you want the next turn to reload immediately.")),console.log("")}function Oc(e){let t=e[0];if(!t){console.log($("Usage: /mcp remove <name>"));return}let n=Ho();if(!n.servers[t]){console.log($(`No server named "${t}".`));return}delete n.servers[t],pi(n),console.log(E(`\u2713 Removed "${t}".`)),console.log(m(" Run /clear to drop it from the current session immediately."))}W();import{readFileSync as Jc}from"node:fs";import{join as Qc}from"node:path";import{select as Zc}from"@inquirer/prompts";import{computeSyncStatus as Jo,planPartitions as eu,relatedArticlePaths as tu,resolveModelForOperation as nu,runPartitioned as ou,loadProfileMap as ru,resolveActiveProfile as su,resolveCrossLinks as iu}from"document360-engine";import V from"picocolors";import yi from"wrap-ansi";import zo from"string-width";W();import Fe from"picocolors";import qo from"wrap-ansi";import Bo from"string-width";var fi=e=>/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(e),mi=e=>/^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$/.test(e)&&e.includes("-"),hi=e=>e.replace(/^\s*\|/,"").replace(/\|\s*$/,"").split("|").map(t=>t.trim());function Uc(e){let t=e.replace(/\r/g,"").split(`
|
|
190
|
-
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(fi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&mi(t[o+1])){let p=hi(r);o+=2;let f=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)f.push(hi(t[o++]));n.push({kind:"table",header:p,rows:f});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!fi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&mi(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Go(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Fe.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):Fe.italic(t.slice(1,-1)))}var Lc=(e,t)=>e+" ".repeat(Math.max(0,t-Bo(e)));function Mc(e,t,n){let o=e.length,r=e.map((C,R)=>Math.max(Bo(C),...t.map(I=>Bo(I[R]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],f=()=>p.reduce((C,R)=>C+R,0)+c,b=0;for(;f()>s&&b++<1e4;){let C=-1,R=6;for(let I=0;I<o;I++)p[I]>R&&(R=p[I],C=I);if(C===-1)break;p[C]-=1}let k=(C,R,I)=>Fe.gray(C+p.map(H=>"\u2500".repeat(H+2)).join(R)+I),A=Fe.gray("\u2502"),w=(C,R)=>{let I=p.map((
|
|
191
|
-
`)}),H=Math.max(...I.map(
|
|
190
|
+
`),n=[],o=0;for(;o<t.length;){let r=t[o];if(/^\s*```/.test(r)){let p=[];for(o++;o<t.length&&!/^\s*```/.test(t[o]);)p.push(t[o++]);o++,n.push({kind:"code",lines:p});continue}if(fi(r)){n.push({kind:"hr"}),o++;continue}if(r.includes("|")&&o+1<t.length&&mi(t[o+1])){let p=hi(r);o+=2;let f=[];for(;o<t.length&&t[o].includes("|")&&t[o].trim()!=="";)f.push(hi(t[o++]));n.push({kind:"table",header:p,rows:f});continue}let s=r.match(/^(#{1,6})\s+(.*)$/);if(s){n.push({kind:"heading",level:s[1].length,text:s[2]}),o++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(r)){let p=[];for(;o<t.length&&/^\s*([-*]|\d+\.)\s+/.test(t[o]);)p.push(t[o++].replace(/^\s*([-*]|\d+\.)\s+/,""));n.push({kind:"list",items:p});continue}if(r.trim()===""){o++;continue}let c=[];for(;o<t.length&&t[o].trim()!==""&&!/^\s*```/.test(t[o])&&!/^(#{1,6})\s/.test(t[o])&&!/^\s*([-*]|\d+\.)\s+/.test(t[o])&&!fi(t[o])&&!(t[o].includes("|")&&o+1<t.length&&mi(t[o+1]));)c.push(t[o++]);n.push({kind:"para",text:c.join(" ")})}return n}function Go(e){return e.replace(/(\*\*[^*]+\*\*|`[^`]+`|\*[^*]+\*)/g,t=>t.startsWith("**")?Fe.bold(t.slice(2,-2)):t.startsWith("`")?O(t.slice(1,-1)):Fe.italic(t.slice(1,-1)))}var Lc=(e,t)=>e+" ".repeat(Math.max(0,t-Bo(e)));function Mc(e,t,n){let o=e.length,r=e.map((C,R)=>Math.max(Bo(C),...t.map(I=>Bo(I[R]??"")))),s=Math.max(24,n),c=3*o+1,p=[...r],f=()=>p.reduce((C,R)=>C+R,0)+c,b=0;for(;f()>s&&b++<1e4;){let C=-1,R=6;for(let I=0;I<o;I++)p[I]>R&&(R=p[I],C=I);if(C===-1)break;p[C]-=1}let k=(C,R,I)=>Fe.gray(C+p.map(H=>"\u2500".repeat(H+2)).join(R)+I),A=Fe.gray("\u2502"),w=(C,R)=>{let I=p.map((ve,ae)=>{let Ce=C[ae]??"",le=R?Fe.bold(Ce):Go(Ce);return qo(le,ve,{hard:!0}).split(`
|
|
191
|
+
`)}),H=Math.max(...I.map(ve=>ve.length)),se=[];for(let ve=0;ve<H;ve++)se.push(p.map((ae,Ce)=>`${A} ${Lc(I[Ce][ve]??"",ae)} `).join("")+A);return se.join(`
|
|
192
192
|
`)},P=[k("\u250C","\u252C","\u2510"),w(e,!0)];return P.push(t.length===0?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524")),t.forEach((C,R)=>{P.push(w(C,!1)),P.push(R===t.length-1?k("\u2514","\u2534","\u2518"):k("\u251C","\u253C","\u2524"))}),P.join(`
|
|
193
193
|
`)}function Wc(e,t){switch(e.kind){case"heading":return Fe.bold(e.text);case"hr":return Fe.gray("\u2500".repeat(t));case"para":return qo(Go(e.text),t);case"list":return e.items.map(n=>{let[o="",...r]=qo(Go(n),Math.max(10,t-4)).split(`
|
|
194
194
|
`);return" \u2022 "+o+r.map(s=>`
|
|
@@ -217,10 +217,10 @@ No MCP servers registered. Add one with /mcp add <name> <type> <ref>
|
|
|
217
217
|
`)}import{resolveActiveProfile as Vc,loadTokens as zc,isExpired as Kc,decodeJwtClaims as bi}from"document360-engine";function Xc(e){return e.length>12?`${e.slice(0,8)}\u2026`:e}function Ie(e,t){try{let n=Vc(e,t),o=zc(n.name);if(!o)return{ok:!1,reason:`Not signed in to Document360 (profile "${n.name}"). Run /login first.`};if(Kc(o)&&!o.refreshToken)return{ok:!1,reason:`Your Document360 session expired (profile "${n.name}"). Run /login.`};let r=n.project.projectId;if(r){let c={...bi(o.idToken)??{},...bi(o.accessToken)??{}}.doc360_project_id;if(typeof c=="string"&&c&&c!==r)return{ok:!1,reason:`Your Document360 session is signed into a different project than profile "${n.name}" (this profile's project is ${Xc(r)}). Run /login and pick this project.`}}return{ok:!0}}catch{return{ok:!0}}}var Kt=3;function Qo(e){return[`Run the publish-to-d360 skill for the article at: ${e}`,"","Steps you must follow:","1. Read the article markdown \u2014 use the repo-relative path exactly as given above (it resolves against the working directory; do not reconstruct an absolute path).","2. Compute the D360 publish form (strip the YAML frontmatter and the H1 title, strip every <!-- SCREENSHOT ... --> block while keeping the visible [Screenshot: ...] line, normalize cross-article links).","3. Look up the article ID in <repo>/d360-category-map.json. If present, call the document360 MCP update-article tool. If absent, call create-article with local_path set to the repo-relative .md path (the tool records the new ID + sync base in the category map itself \u2014 do not edit the articles map by hand).","4. Report what changed and remind me to publish the draft manually in the Document360 portal."].join(`
|
|
218
218
|
`)}var xi={"local-ahead":"modified locally","untracked-local":"new (never published)",conflict:"\u26A0 conflict \u2014 publishing overwrites the portal edit"};function Xt(e){return e.filter(t=>t.path!==null&&t.status in xi&&!t.link).map(t=>({path:t.path,label:xi[t.status]}))}function On(e){return e.filter(t=>t.link).length}function Zo(e,t){try{let n=ru(e,su(e,t).name);if(!n)return null;let o=0;for(let r of Object.keys(n.articles))try{o+=iu(Jc(Qc(e,r),"utf8"),r,n).unresolved}catch{}return o===0?null:`\u2139 ${o} cross-link${o===1?"":"s"} point to pages not published yet \u2014 they show as plain text for now and turn into live links once those pages are published.`}catch{return null}}function au(e){let t=e.replace(/\\/g,"/").split("/").pop()??e,n=t.replace(/^\d+[-_]/,"").replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):t}function $i(e){let t=[];e.length>1&&t.push({kind:"all",label:`Publish all ${e.length} articles`,paths:e.map(o=>o.path),indent:!1});let n=new Map;for(let o of e){let r=o.path.replace(/\\/g,"/").split("/").slice(0,-1).join("/"),s=n.get(r);s?s.push(o):n.set(r,[o])}for(let o of[...n.keys()].sort()){let r=n.get(o).sort((s,c)=>s.path.localeCompare(c.path));t.push({kind:"category",label:`${au(o)} (${r.length})`,paths:r.map(s=>s.path),indent:!1});for(let s of r){let c=s.path.replace(/\\/g,"/").split("/").pop()??s.path;t.push({kind:"article",label:c,paths:[s.path],indent:!0,note:s.label})}}return t}function Un(e){return[`Run the publish-to-d360 skill for ALL of these ${e.length} articles, one by one:`,"",...e.map(t=>`- ${t}`),"","Use the repo-relative paths exactly as listed (they resolve against the working directory; do not reconstruct absolute paths). Apply the normal per-article publish flow (frontmatter/H1/screenshot-comment strips, link normalization; update when mapped, create with local_path when not). If one article fails, note it and continue. Finish with a summary table (article | created/updated | failures) and remind me drafts need review in the portal."].join(`
|
|
219
219
|
`)}function er(e,t,n){let o=w=>t[w.index]?.paths.length??0,r=e.filter(w=>w.ok),s=e.filter(w=>!w.ok),c=e.reduce((w,P)=>w+o(P),0),p=r.reduce((w,P)=>w+o(P),0),f=n==="api"?`${de(e.reduce((w,P)=>w+P.costUsd,0))} total`:He(e.reduce((w,P)=>w+P.outputTokens,0)),b=`${r.length}/${e.length} partition${e.length===1?"":"s"}`,k=w=>`${w} article${w===1?"":"s"}`,A=[];if(s.length===0)A.push(`Published ${k(c)} (${b}) successfully \xB7 ${f}.`),A.push("All are DRAFTS \u2014 review and publish them in the Document360 portal.");else{A.push(`Published ${p}/${k(c)} (${b}) \xB7 ${f}.`),A.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /publish --all to retry just the rest (published articles are skipped):`);for(let w of s)A.push(` \u2717 ${w.label}${w.error?` \u2014 ${w.error}`:""}`)}return A}async function Xo(e,t){let n=eu(t),{model:o}=nu(e.cwd,"standard");console.log(m(`Publishing ${t.length} article${t.length===1?"":"s"} across ${n.length} partition${n.length===1?"":"s"} (\u2264${Kt} agents at once) on ${o}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let r of ou({cwd:e.cwd,partitions:n,promptFor:s=>Un(s.paths),concurrency:Kt,profileName:e.profileName,allowProdWrites:e.allowProdWrites(),model:o}))if(r.type==="partition_status")r.status==="running"?console.log(m(` \u25B8 ${r.label} \u2014 publishing\u2026`)):r.status==="done"?console.log(E(` \u2713 ${r.label}`)):console.log($(` \u2717 ${r.label}`));else if(r.type==="run_done"){console.log("");let s=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let p of er(r.results,n,s))console.log(r.ok?E(p):U(p));let c=Zo(e.cwd,e.profileName);c&&console.log(m(c))}}catch(r){console.log($(`Publish run failed: ${r.message}`))}return console.log(""),{kind:"continue"}}async function Ln(e,t,n){let o=tu(e,n);if(o.length===0)return[];let r=new Set(Xt((await Jo({cwd:e,profileName:t})).entries).map(s=>s.path));return o.filter(s=>r.has(s))}async function vi(e,t){let n=Ie(t?.cwd??process.cwd(),t?.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=e[0];if(o==="--related"&&e[1]){if(!t)return{kind:"continue"};let r=await Ln(t.cwd,t.profileName,e[1].replace(/\\/g,"/"));return r.length===0?(console.log(E("\u2713 All related articles are already published.")),{kind:"continue"}):await Xo(t,r)}if(o==="--all"){console.log(m("Checking what needs publishing\u2026"));try{let r=await Jo({cwd:t?.cwd??process.cwd()}),s=Xt(r.entries),c=On(r.entries);return c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`)),s.length===0?(console.log(E(c>0?"\u2713 Nothing else is ahead of Document360 to publish.":"\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),{kind:"continue"}):t?await Xo(t,s.map(p=>p.path)):{kind:"forward-to-agent",prompt:Un(s.map(p=>p.path)),display:"/publish --all"}}catch(r){return console.log($(`Could not compute sync status: ${r.message}`)),{kind:"continue"}}}if(!o){console.log(m("Checking what needs publishing\u2026"));let r;try{let s=await Jo({cwd:t?.cwd??process.cwd()});r=Xt(s.entries);let c=On(s.entries);c>0&&console.log(U(`\u26A0 ${c} article(s) already exist on Document360 but aren't linked \u2014 left out (publishing would duplicate them). Run /catch-up or ask me to link them first.`))}catch(s){return console.log($(`Could not compute sync status: ${s.message}`)),console.log(m("Publish a specific article: /publish <article-path>")),{kind:"continue"}}if(r.length===0)return console.log(E("\u2713 Nothing is ahead of Document360 \u2014 no publish candidates.")),console.log(m(" (Articles without a sync base are unverified \u2014 publish those by path if needed.)")),{kind:"continue"};if(!process.stdin.isTTY||!t){for(let s of r)console.log(` ${s.path} ${m(`(${s.label})`)}`);return console.log(m("Run: /publish <article-path>")),{kind:"continue"}}try{o=await t.withPausedInput(()=>Zc({message:"Publish which article?",choices:[...r.length>1?[{name:`All ${r.length} candidates`,value:"--all",description:"one agent run over every candidate"}]:[],...r.map(s=>({name:s.path,value:s.path,description:s.label}))]}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(o==="--all")return await Xo(t,r.map(s=>s.path))}return{kind:"forward-to-agent",prompt:Qo(o),display:`/publish ${o}`}}async function Jt(){return{kind:"forward-to-agent",prompt:["Run the gap-analysis skill against this repo.","","Follow its stages in order:","1. d360_sync_status first \u2014 stop and report if any article is in conflict or remote-ahead (the local copy cannot be trusted until resolved).","2. git diff since the lastAnalyzedCommit marker in d360-category-map.json (or last 30 days if no marker), filtered to the authoritativeSourceFiles paths.","2.5. d360_pending_hints \u2014 the source agent's own notes on what it shipped. Verify each (sources exist, commit is an ancestor of HEAD, source shows the surface) before trusting; fold verified ones into the table, flag the rest.","3. Map changes (diff + hints) to articles via their `sources:` frontmatter; read only implicated articles and changed source files. If articles are missing `sources:`, this is the one-time bootstrap pass \u2014 backfill them.","4. Output the proposal table: | Article (path or proposed title) | Action (create | update | retire | link) | Reason | Evidence | Scope |, then advance lastAnalyzedCommit and stamp consumed hints.","","Do not start writing or updating any article yet \u2014 the proposal table is the deliverable."].join(`
|
|
220
|
-
`),display:"/audit"}}W();import{checkbox as lu}from"@inquirer/prompts";import{inventoryRepo as cu,readProjectConfig as Ci,writeProjectConfig as uu}from"document360-engine";function tr(e,t){let n=Ci(e);n&&(n.authoritativeSourceFiles=t,uu(n,e))}function Mn(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Pi(e,t){let n=t?.cwd??process.cwd();if(!Ci(n))return console.log($("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=cu(n);if(o.length===0)return console.log(m('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${m(Mn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>lu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Mn(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};tr(n,r),console.log(E(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as hu}from"@inquirer/prompts";import{applyPull as ji,computeSyncStatus as Ai,planPull as gu,establishBaselines as wu,D360AuthError as yu}from"document360-engine";W();var Ti=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/sync pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:U,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /sync pull <path>:",paint:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:$,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:$,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:oe,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet:",paint:m,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /sync baseline to set a baseline (or the next publish/pull sets one):",paint:oe,mark:"\xB7"}];function du(e){return e.path?e.path:`${e.title??"(untitled)"} ${oe(`[${e.articleId}]`)}`}function Wn(e){let t=[],n=e.entries.filter(f=>f.link);if(n.length>0){t.push(""),t.push(
|
|
220
|
+
`),display:"/audit"}}W();import{checkbox as lu}from"@inquirer/prompts";import{inventoryRepo as cu,readProjectConfig as Ci,writeProjectConfig as uu}from"document360-engine";function tr(e,t){let n=Ci(e);n&&(n.authoritativeSourceFiles=t,uu(n,e))}function Mn(e){let t=[`${e.fileCount}${e.fileCount>=5e3?"+":""} files`];return e.stacks.length&&t.push(e.stacks.join("+")),t.push(e.reason),t.join(" \xB7 ")}async function Pi(e,t){let n=t?.cwd??process.cwd();if(!Ci(n))return console.log($("No .d360-writer.json here. Run /init first.")),{kind:"continue"};let o=cu(n);if(o.length===0)return console.log(m('No candidate source folders found. Set "authoritativeSourceFiles" in .d360-writer.json manually.')),{kind:"continue"};if(!process.stdin.isTTY||!t){console.log(""),console.log(O("Recommended documentation scope (run /scope in the REPL to choose):"));for(let s of o)console.log(` ${s.recommended?"\u25C9":"\u25CB"} ${s.path} ${m(Mn(s))}`);return console.log(""),{kind:"continue"}}let r;try{r=await t.withPausedInput(()=>lu({message:"Which folders back the user docs? (space toggles, enter confirms)",choices:o.map(s=>({name:`${s.path} (${Mn(s)})`,value:s.path,checked:s.recommended})),pageSize:20}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}if(r.length===0)return console.log(m("Nothing selected \u2014 scope unchanged.")),{kind:"continue"};tr(n,r),console.log(E(`\u2713 Scoped to ${r.length} folder(s) \u2014 written to .d360-writer.json`));for(let s of r)console.log(` ${s}`);return console.log(""),{kind:"continue"}}W();import{confirm as hu}from"@inquirer/prompts";import{applyPull as ji,computeSyncStatus as Ai,planPull as gu,establishBaselines as wu,D360AuthError as yu}from"document360-engine";W();var Ti=[{status:"conflict",header:"Changed in both places \u2014 pick a direction (/sync pull <path> or /publish <path>):",paint:$,mark:"!"},{status:"local-ahead",header:"Changed here \u2014 push with /publish <path>:",paint:U,mark:"M"},{status:"remote-ahead",header:"Changed on Document360 \u2014 pull with /sync pull <path>:",paint:O,mark:"M"},{status:"deleted-local",header:"Removed locally \u2014 still on Document360 (pull to restore, or leave it):",paint:$,mark:"D"},{status:"deleted-remote",header:"Gone from Document360 \u2014 still here (publish to recreate, or delete the file):",paint:$,mark:"D"},{status:"orphaned",header:"Gone from both sides \u2014 these tracking entries point at nothing now:",paint:oe,mark:"X"},{status:"untracked-local",header:"New here \u2014 not on Document360 yet (publish to add them):",paint:m,mark:"?"},{status:"untracked-remote",header:"On Document360 \u2014 not in your local docs yet:",paint:m,mark:"?"},{status:"unknown-base",header:"Tracked, not yet compared \u2014 run /sync baseline to set a baseline (or the next publish/pull sets one):",paint:oe,mark:"\xB7"}];function du(e){return e.path?e.path:`${e.title??"(untitled)"} ${oe(`[${e.articleId}]`)}`}function Wn(e){let t=[],n=e.entries.filter(f=>f.link);if(n.length>0){t.push(""),t.push(Te("Already on Document360, just not linked \u2014 ask me to link these (a republish would duplicate them):"));for(let f of n)t.push(` ${U("~")} ${U(f.path??"")} ${oe(`\u2192 "${f.link.title}"`)}`)}for(let f of Ti){let b=e.entries.filter(k=>k.status===f.status&&!(f.status==="untracked-local"&&k.link));if(b.length!==0){t.push(""),t.push(Te(f.header));for(let k of b)t.push(` ${f.paint(f.mark)} ${f.paint(du(k))}${k.detail?oe(` (${k.detail})`):""}`)}}let o=e.counts["in-sync"]??0,r=e.entries.length;t.push("");let s={"in-sync":"up to date","local-ahead":"changed here","remote-ahead":"changed on Document360",conflict:"changed both places","untracked-local":"new here","untracked-remote":"only on Document360","deleted-local":"removed locally","deleted-remote":"gone from Document360",orphaned:"gone both sides","unknown-base":"not yet compared"},c=n.length,p=r===o?E("\u2713 everything up to date"):[o>0?E(`\u2713 ${o} up to date`):null,c>0?`${c} to link`:null,...Ti.map(f=>{let b=(e.counts[f.status]??0)-(f.status==="untracked-local"?c:0);return b>0?`${b} ${s[f.status]}`:null})].filter(Boolean).join(oe(" \xB7 "));return t.push(p+oe(` \xB7 ${r} tracked+seen \xB7 profile "${e.profile}" \xB7 docs root ${e.docsRoot}/`)),t}import{structuredPatch as pu}from"diff";import Ri from"picocolors";var Si=80,fu="\x1B[48;2;74;28;28m",mu="\x1B[48;2;24;66;24m",Di="\x1B[49m",nr=e=>String(e).padStart(5);function rt(e,t,n){let o=w=>{let P=w.replace(/\r\n/g,`
|
|
221
221
|
`);return P.endsWith(`
|
|
222
222
|
`)||P===""?P:P+`
|
|
223
|
-
`},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=pu("a","b",r,s,"","",{context:3}),f=0,b=0,k=[];p.hunks.forEach((w,P)=>{P>0&&k.push(Ri.gray(" \u2026"));let C=w.oldStart,R=w.newStart;for(let I of w.lines){let H=I[0],se=I.slice(1).slice(0,c);H==="-"?(b++,k.push(`${fu}${nr(C++)} - ${se}${Di}`)):H==="+"?(f++,k.push(`${mu}${nr(R++)} + ${se}${Di}`)):(k.push(Ri.gray(nr(R))+" "+se),C++,R++)}});let A=k.slice(0,Si);return{added:f,removed:b,lines:A,hidden:Math.max(0,k.length-Si)}}async function Ei(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await ku(t.cwd),{kind:"continue"};if(o==="pull")return await xu(t,e.slice(1)),{kind:"continue"};if(o==="baseline")return await bu(t,e.slice(1)),{kind:"continue"};console.log($(`Unknown subcommand: /sync ${o}`)),console.log(m("Usage: /sync drift report (local vs Document360)")),console.log(m(" /sync pull <path> pull portal edits into the local file")),console.log(m(" /sync pull --all pull every remote-ahead article")),console.log(m(" /sync baseline set a sync baseline for tracked-but-not-yet-compared articles"))}catch(r){r instanceof yu?console.log($(r.message)):console.log($(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function ku(e){console.log(m("Checking Document360 for drift\u2026"));let t=await Ai({cwd:e});for(let n of Wn(t))console.log(n);console.log("")}async function bu(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await wu({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0});if(o.baselined.length===0&&o.skipped.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),o.skipped.length>0){console.log(U(`${o.skipped.length} skipped:`));for(let r of o.skipped)console.log(m(` - ${r.path} (${r.reason})`))}}async function xu(e,t){let n=t[0];if(!n){console.log($("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(m("Checking Document360 for drift\u2026")),o=(await Ai({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(E("\u2713 Nothing is remote-ahead \u2014 no pulls needed.")),console.log(m(" (conflicts are never bulk-pulled; pull them one by one: /sync pull <path>)"));return}console.log(`${
|
|
223
|
+
`},r=o(e),s=o(t);if(r===s)return null;let c=Math.max(20,n-10),p=pu("a","b",r,s,"","",{context:3}),f=0,b=0,k=[];p.hunks.forEach((w,P)=>{P>0&&k.push(Ri.gray(" \u2026"));let C=w.oldStart,R=w.newStart;for(let I of w.lines){let H=I[0],se=I.slice(1).slice(0,c);H==="-"?(b++,k.push(`${fu}${nr(C++)} - ${se}${Di}`)):H==="+"?(f++,k.push(`${mu}${nr(R++)} + ${se}${Di}`)):(k.push(Ri.gray(nr(R))+" "+se),C++,R++)}});let A=k.slice(0,Si);return{added:f,removed:b,lines:A,hidden:Math.max(0,k.length-Si)}}async function Ei(e,t){let n=Ie(t.cwd,t.profileName);if(!n.ok)return console.log($(n.reason)),{kind:"continue"};let o=(e[0]??"status").toLowerCase();try{if(o==="status")return await ku(t.cwd),{kind:"continue"};if(o==="pull")return await xu(t,e.slice(1)),{kind:"continue"};if(o==="baseline")return await bu(t,e.slice(1)),{kind:"continue"};console.log($(`Unknown subcommand: /sync ${o}`)),console.log(m("Usage: /sync drift report (local vs Document360)")),console.log(m(" /sync pull <path> pull portal edits into the local file")),console.log(m(" /sync pull --all pull every remote-ahead article")),console.log(m(" /sync baseline set a sync baseline for tracked-but-not-yet-compared articles"))}catch(r){r instanceof yu?console.log($(r.message)):console.log($(`Sync failed: ${r.message}`))}return{kind:"continue"}}async function ku(e){console.log(m("Checking Document360 for drift\u2026"));let t=await Ai({cwd:e});for(let n of Wn(t))console.log(n);console.log("")}async function bu(e,t){let n=t[0]&&t[0]!=="--all"?t[0].replace(/\\/g,"/"):void 0;console.log(m(n?`Setting the sync baseline for ${n}\u2026`:"Setting a sync baseline for tracked-but-not-yet-compared articles\u2026"));let o=await wu({cwd:e.cwd,profileName:e.profileName,relPaths:n?[n]:void 0});if(o.baselined.length===0&&o.skipped.length===0){console.log(E("\u2713 Nothing to baseline \u2014 every tracked article already has a sync baseline."));return}if(o.baselined.length>0&&console.log(E(`\u2713 Baselined ${o.baselined.length} article(s) \u2014 they now read in-sync until either side changes.`)),o.skipped.length>0){console.log(U(`${o.skipped.length} skipped:`));for(let r of o.skipped)console.log(m(` - ${r.path} (${r.reason})`))}}async function xu(e,t){let n=t[0];if(!n){console.log($("Usage: /sync pull <article-path> | --all"));return}let o;if(n==="--all"){if(console.log(m("Checking Document360 for drift\u2026")),o=(await Ai({cwd:e.cwd})).entries.filter(s=>s.status==="remote-ahead"&&s.path).map(s=>s.path),o.length===0){console.log(E("\u2713 Nothing is remote-ahead \u2014 no pulls needed.")),console.log(m(" (conflicts are never bulk-pulled; pull them one by one: /sync pull <path>)"));return}console.log(`${Te(String(o.length))} article(s) are remote-ahead.`)}else o=[n.replace(/\\/g,"/")];for(let r of o){let s=await gu({cwd:e.cwd,relPath:r});console.log(""),console.log(`${O("\u25CF")} ${Te(s.title)} ${oe(`(${s.path})`)}`);for(let b of s.notes)console.log(U(` \u26A0 ${b}`));s.overwritesLocalChanges&&console.log(U(" \u26A0 This OVERWRITES local edits made since the last sync."));let c=rt(s.oldContent,s.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!c){console.log(m(" Local file already matches the remote content \u2014 advancing the sync base only.")),ji({cwd:e.cwd},s);continue}let p=b=>b===1?"":"s";console.log(oe(` \u23BF Added ${c.added} line${p(c.added)}, removed ${c.removed} line${p(c.removed)}`));for(let b of c.lines)console.log(b);if(c.hidden>0&&console.log(m(` \u2026 +${c.hidden} more diff lines`)),!await e.withPausedInput(()=>hu({message:`Write ${s.path}?`,default:!s.overwritesLocalChanges}))){console.log(m(" Skipped."));continue}ji({cwd:e.cwd},s),console.log(E(` \u2713 Pulled ${s.path} (sync base advanced).`))}console.log("")}W();import{statSync as $u}from"node:fs";import{resolve as vu}from"node:path";import{estimateBulkCost as Cu,planPartitions as Pu,readProjectConfig as Tu,resolveModelForOperation as Ru,runPartitioned as Su,trackedArticlePaths as Du}from"document360-engine";var or=3;function rr(e){let t,n=!1;for(let r=0;r<e.length;r++){let s=e[r];s==="--run"||s==="--yes"?n=!0:s==="--scope"?t=e[++r]:s?.startsWith("--scope=")&&(t=s.slice(8))}return{scope:t?.replace(/\\/g,"/").replace(/\/+$/,"")||void 0,run:n}}function sr(e,t){return t?e.filter(n=>{let o=n.replace(/\\/g,"/");return o===t||o.startsWith(`${t}/`)}):e}function ir(e,t){return t.map(n=>{let o=0;try{o=$u(vu(e,n)).size}catch{o=0}return{path:n,bytes:o}})}function ar(e){return`Convert each of these articles to canonical Document360 Flavored Markdown (DFM) and re-publish each as a DRAFT. This is a mechanical syntax conversion, not a rewrite \u2014 be efficient:
|
|
224
224
|
- Read ONLY the article files listed below. Do NOT read source code, other articles, or fetch the live portal \u2014 you already have everything you need.
|
|
225
225
|
- Convert in place: wrap callouts, FAQs, tabs, accordions, and media embeds per the d360-markdown skill. Preserve all wording, headings, and structure; change only GFM\u2192DFM syntax.
|
|
226
226
|
- Publish each as a draft with a single update call. Do NOT re-read, re-verify, or polish after converting, and skip articles already in DFM.
|
|
@@ -236,7 +236,7 @@ Articles:
|
|
|
236
236
|
`+e.paths.map(n=>`- ${n}`).join(`
|
|
237
237
|
`)}function hr(e,t,n){let o=e.reduce((c,p)=>c+p.paths.length,0),[r,s]=t.usd;return[`Write ${o} article${o===1?"":"s"} across ${e.length} partition${e.length===1?"":"s"} (\u2264${n} agents at once):`,...e.map(c=>` \u2022 ${c.label} \u2014 ${c.paths.length} article${c.paths.length===1?"":"s"}`),"",`Estimated cost: ${de(r)}\u2013${de(s)}. ${t.note}`,"","Articles are written as local drafts in the docs tree (nothing is published). Run /write to start."]}function gr(e,t,n){let o=C=>t[C.index]?.paths.length??0,r=e.filter(C=>C.ok),s=e.filter(C=>!C.ok),c=e.reduce((C,R)=>C+o(R),0),p=r.reduce((C,R)=>C+o(R),0),f=e.reduce((C,R)=>C+R.costUsd,0),b=e.reduce((C,R)=>C+R.outputTokens,0),k=n==="api"?`${de(f)} total`:He(b),A=`${r.length}/${e.length} partition${e.length===1?"":"s"} completed`,w=C=>`${C} article${C===1?"":"s"}`,P=[];if(s.length===0)P.push(`Wrote ${w(c)} (${A}) successfully \xB7 ${k}.`),P.push("Next \u2014 push them to Document360:"),P.push("/publish --all"),P.push("Or add screenshots first with /screenshot --all. Drafts are reviewable in the portal after publishing.");else{P.push(`Wrote ${p}/${w(c)} (${A}) \xB7 ${k}.`),P.push(`${s.length} partition${s.length===1?"":"s"} failed \u2014 re-run /write to retry the rest:`);for(let C of s)P.push(` \u2717 ${C.label}${C.error?` \u2014 ${C.error}`:""}`)}return P}function wr(e,t,n){let o=(Oi(e)?.docsDir??Iu).replace(/\/+$/,""),r=t.map(p=>p.path);if(n.path){let p=Lu(n.path,o);return r.includes(p)?{docsDir:o,targets:[p],planCount:r.length}:{docsDir:o,targets:[],planCount:r.length,reason:`"${p}" isn't in the docs plan (.d360-writer/plan.json).`}}let s=Mu(r,n.scope);if(n.scope&&s.length===0)return{docsDir:o,targets:[],planCount:r.length,reason:`No planned articles under "${n.scope}".`};let c=pr(e,o,s);if(c.length===0){let p=n.scope?` under "${n.scope}"`:"";return{docsDir:o,targets:[],planCount:r.length,reason:`All planned articles${p} are already written. Use /write <path> to rewrite one.`}}return{docsDir:o,targets:c,planCount:r.length}}async function Ui(e,t){if(!Oi(t.cwd))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let n=Eu(t.cwd);if(n.length===0)return console.log($("No docs plan found (.d360-writer/plan.json). Analyze the repo and propose a structure first.")),{kind:"continue"};let{scope:o,path:r,preview:s,concurrency:c}=dr(e),{docsDir:p,targets:f,reason:b}=wr(t.cwd,n,{scope:o,path:r});if(f.length===0)return console.log(b?U(b):U("Nothing to write.")),{kind:"continue"};let k=Au(f),A=ur(c),{model:w,forced:P}=Nu(t.cwd,"standard");if(s&&!!!r){let R=ju({files:fr(t.cwd,n,f),op:"write",model:w});o&&console.log(m(`Scope: ${o} (${f.length} pending).`));for(let I of hr(k,R,A))console.log(I);return console.log(m(`Model: ${w}${P?" (forced)":" \u2014 authoring; /model to override"}.`)),console.log(m(`Run /write${o?` --scope ${o}`:""} to start.`)),console.log(""),{kind:"continue"}}console.log(m(`Writing ${f.length} article${f.length===1?"":"s"} across ${k.length} partition${k.length===1?"":"s"} (\u2264${A} agents at once) on ${w}\u2026`)),console.log(m(" (mid-run abort is TUI-only \u2014 Ctrl+C exits the REPL.)"));try{for await(let R of _u({cwd:t.cwd,partitions:k,promptFor:I=>mr(I,p),concurrency:A,profileName:t.profileName,allowProdWrites:t.allowProdWrites(),model:w}))if(R.type==="partition_status")R.status==="running"?console.log(m(` \u25B8 ${R.label} \u2014 writing\u2026`)):R.status==="done"?console.log(E(` \u2713 ${R.label}`)):console.log($(` \u2717 ${R.label}`));else if(R.type==="run_done"){console.log("");let I=process.env.ANTHROPIC_API_KEY?"api":"subscription";for(let H of gr(R.results,k,I))console.log(R.ok?E(H):U(H))}}catch(R){console.log($(`Write run failed: ${R.message}`))}return console.log(""),{kind:"continue"}}W();import{existsSync as Wu,readdirSync as Li,statSync as Mi}from"node:fs";import{join as Wi}from"node:path";import{inputDir as Fu,readProjectConfig as Hu}from"document360-engine";var Fi=/\.(md|markdown|pdf|txt)$/i;function yr(e){let t=Fu(e);if(!Wu(t))return{features:[],looseDocs:0};let n=[],o=0;for(let r of Li(t)){let s=Wi(t,r),c=!1;try{c=Mi(s).isDirectory()}catch{continue}if(c){if(r.startsWith("."))continue;let p=qu(s);p>0&&n.push({name:r,docCount:p})}else Fi.test(r)&&o++}return n.sort((r,s)=>r.name.localeCompare(s.name)),{features:n,looseDocs:o}}function qu(e){let t=0;for(let n of Li(e))try{Mi(Wi(e,n)).isFile()&&Fi.test(n)&&t++}catch{}return t}function kr(e,t){let n=t.trim().toLowerCase();return n?e.find(o=>o.name.toLowerCase()===n)?.name??e.find(o=>o.name.toLowerCase().startsWith(n))?.name??e.find(o=>o.name.toLowerCase().includes(n))?.name??null:null}function Fn(e,t){return["Run the draft-from-prd skill.","",`Target scope: ${e?`the feature documents in .d360-writer/input/${e}/`:t?`the input docs in .d360-writer/input/ relevant to: "${t}"`:"the input docs in .d360-writer/input/"}.`,t&&!e?`Use "${t}" as the feature framing.`:"","","Follow the skill: (1) read those PRDs/specs as the primary source (intent, user-facing surface,","terminology, user stories, prerequisites); (2) locate and read the CODE that implements that surface","to pin exact UI strings/routes/states \u2014 never fabricate; flag anything the PRD claims that you","cannot find in source; (3) propose a tight feature-scoped article set (\u22483\u20135) and pin it to",".d360-writer/plan.json + AGENT-PLAN.md, with each article's `sources` listing BOTH the PRD file(s)","AND the grounding code files; (4) flag overlaps with existing articles (do not merge). Then stop and","offer /write. Do NOT write the articles in this turn."].filter(Boolean).join(`
|
|
238
238
|
`)}var br="No input docs found. Drop this feature's PRDs/specs in .d360-writer/input/<feature>/ (.md or .pdf), then run /draft.";async function Hi(e,t){let n=t?.cwd??process.cwd();if(!Hu(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{features:o,looseDocs:r}=yr(n);if(o.length===0&&r===0)return console.log(m(br)),{kind:"continue"};let s=e.join(" ").trim();if(!s){if(o.length>1){console.log(m("Multiple features in .d360-writer/input/ \u2014 draft which one? Run: /draft <feature>"));for(let f of o)console.log(` ${f.name} ${m(`(${f.docCount} doc${f.docCount===1?"":"s"})`)}`);return{kind:"continue"}}let p=o[0]?.name??"";return{kind:"forward-to-agent",prompt:Fn(p),display:p?`/draft ${p}`:"/draft"}}let c=kr(o,s);return{kind:"forward-to-agent",prompt:Fn(c??"",c?void 0:s),display:`/draft ${s}`}}W();import{listOpenForDocs as Bu,readProjectConfig as Gu}from"document360-engine";function xr(e){try{return Bu(e).filter(t=>t.kind==="request").length}catch{return 0}}function $r(e){let t=e.includes("--publish"),n=e.filter(o=>o!=="--publish").join(" ").trim();return{publish:t,what:n}}function vr(e,t=!1){let n=["Run the document-handoff skill.",""];return e?n.push(`The builder hand-off (what was shipped this session): "${e}".`,"Treat this as the Stage 1 hand-off: ground it in the cited/changed code + the architecture brief,","then decide and APPLY the right doc action \u2014 a new section, a new article, an update to existing","article(s), or a retirement, or a mix. No fixed shape; pick the smallest set that keeps the docs correct."):n.push("No description was given \u2014 call d360_inbox and act on the OPEN `request` messages the builder left:","for each, run the document-handoff flow (ground \u2192 decide \u2192 apply) and mark the request `status: done`","with `resulting_articles` when finished."),n.push("","Draft only \u2014 do not publish. If you would create multiple new articles (a section), call","d360_estimate_cost and present the count + cost band first, then wait for the go-ahead."),t&&n.push("","After the drafts exist and the user confirms any bulk gate, publish the new/updated articles to","Document360 (the publish-to-d360 skill). On a production profile, respect the write-guard."),n.join(`
|
|
239
|
-
`)}var Cr="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function qi(e,t){let n=t?.cwd??process.cwd();if(!Gu(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=$r(e);if(!r&&xr(n)===0)return console.log(m(Cr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:vr(r,o),display:s}}W();import{search as Yu}from"@inquirer/prompts";import{findByName as Vu,getSession as zu,listSessions as Ku,relativeTime as Gi}from"document360-engine";async function Yi(e,t){let n=Ku(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Vu(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),Bi(n),{kind:"continue"})}if(!process.stdin.isTTY)return Bi(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Yu({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${Gi(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=zu(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Bi(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${m(Gi(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Xu}from"document360-engine";function Pr(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function Vi(e,t){let n=Pr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Xu(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(console.log($("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as zi,readProjectConfig as Ju,writeProjectConfig as Qu}from"document360-engine";W();function Tr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Ju(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return zi().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Qu(o,e),null):`Unknown environment "${r}". Known: ${zi().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Ki(e,t){let n=e[0];if(!n)return Pn(t.cwd),{kind:"continue"};if(n==="add"){let o=Tr(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return Tn(t.cwd,n),Rn(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Zu}from"@inquirer/prompts";import{readProjectConfig as ed,readUserConfig as Xi,resolveModelSetting as Rr,writeUserConfig as Ji}from"document360-engine";var Re=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function Hn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Re.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function td(e){switch(e.source){case"project":return".d360-writer.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function Qt(e,t){let n=()=>{let s=Rr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Xi();return s.defaultModel?(delete s.defaultModel,Ji(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Rr(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}Ji({...Xi(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ed(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Qi(e,t){let n=e[0]?.trim();if(!n){let c=Rr(t.cwd);if(!process.stdin.isTTY)return console.log(`${
|
|
239
|
+
`)}var Cr="Nothing to document yet. Say what changed: /document <what you shipped> \u2014 or have the builder drop a request via their /devhints hand-off.";async function qi(e,t){let n=t?.cwd??process.cwd();if(!Gu(n))return console.log($("No d360-writer config here. Run /init first.")),{kind:"continue"};let{publish:o,what:r}=$r(e);if(!r&&xr(n)===0)return console.log(m(Cr)),{kind:"continue"};let s=`/document${r?` ${r}`:""}${o?" --publish":""}`;return{kind:"forward-to-agent",prompt:vr(r,o),display:s}}W();import{search as Yu}from"@inquirer/prompts";import{findByName as Vu,getSession as zu,listSessions as Ku,relativeTime as Gi}from"document360-engine";async function Yi(e,t){let n=Ku(t.cwd).filter(o=>o.uuid!==t.currentUuid());if(n.length===0)return console.log(m("No saved sessions for this repo yet \u2014 sessions auto-save as you work.")),{kind:"continue"};if(e.length>0){let o=e.join(" "),r=Vu(t.cwd,o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:(console.log($(`No session matches "${o}".`)),Bi(n),{kind:"continue"})}if(!process.stdin.isTTY)return Bi(n),console.log(m("Run: /resume <name>")),{kind:"continue"};try{let o=await t.withPausedInput(()=>Yu({message:"Resume session (type to filter, \u2191\u2193 to navigate):",source:async s=>{let c=(s??"").toLowerCase();return n.filter(p=>!c||p.name.toLowerCase().includes(c)||p.firstPrompt.toLowerCase().includes(c)).map(p=>({name:`${p.name} ${Gi(p.updatedAt)}`,value:p.uuid,description:p.firstPrompt.slice(0,100)}))}})),r=zu(o);return r?{kind:"resume",uuid:r.uuid,name:r.name}:{kind:"continue"}}catch{return console.log(""),{kind:"continue"}}}function Bi(e){console.log("");for(let t of e.slice(0,15))console.log(` ${O(t.name)} ${m(Gi(t.updatedAt))}`),console.log(` ${m(t.firstPrompt.slice(0,80))}`);console.log("")}W();import{renameSession as Xu}from"document360-engine";function Pr(e){let t=e.trim();return t.length>=2&&(t[0]==='"'&&t.endsWith('"')||t[0]==="'"&&t.endsWith("'"))?t.slice(1,-1).trim():t}async function Vi(e,t){let n=Pr(e.join(" "));if(!n)return console.log($("Usage: /rename <new name>")),{kind:"continue"};let o=t.currentUuid();return o?(Xu(o,n)?console.log(E(`\u2713 Session renamed to "${n}"`)):console.log($("Could not find the current session record.")),{kind:"continue"}):(console.log($("Nothing to rename yet \u2014 send a message first; sessions auto-save once the agent replies.")),{kind:"continue"})}import{knownEnvironments as zi,readProjectConfig as Ju,writeProjectConfig as Qu}from"document360-engine";W();function Tr(e,t,n){if(!t)return"Usage: /profile add <name> [environment]";let o=Ju(e);if(!o)return"No .d360-writer.json \u2014 run /init first.";if(o.profiles?.[t])return`Profile "${t}" already exists.`;let r=n??t;return zi().includes(r)?(o.profiles={...o.profiles,[t]:{connection:{environment:r},production:!1}},Qu(o,e),null):`Unknown environment "${r}". Known: ${zi().join(", ")} (or add the profile with explicit URLs in .d360-writer.json).`}async function Ki(e,t){let n=e[0];if(!n)return Pn(t.cwd),{kind:"continue"};if(n==="add"){let o=Tr(t.cwd,e[1],e[2]);return o?(console.log($(o)),{kind:"continue"}):(console.log(E(`\u2713 Profile "${e[1]}" created (environment: ${e[2]??e[1]}).`)),console.log(` Switch + sign in: ${O(`/profile ${e[1]}`)} then ${O("/login")}`),{kind:"continue"})}return Tn(t.cwd,n),Rn(t.cwd,n),console.log(m(" Restarting agent for the new profile\u2026")),{kind:"clear"}}W();import{select as Zu}from"@inquirer/prompts";import{readProjectConfig as ed,readUserConfig as Xi,resolveModelSetting as Rr,writeUserConfig as Ji}from"document360-engine";var Re=[{value:null,label:"Auto",desc:"Engine right-sizes per task \u2014 Sonnet for routine work, Opus for analysis (recommended)"},{value:"claude-fable-5",label:"Fable",desc:"Fable 5 \xB7 most capable, for the hardest and longest-running tasks"},{value:"opus",label:"Opus",desc:"Opus 4.8 \xB7 best for everyday complex tasks"},{value:"sonnet",label:"Sonnet",desc:"Sonnet 4.6 \xB7 efficient for routine tasks"},{value:"haiku",label:"Haiku",desc:"Haiku 4.5 \xB7 fastest for quick answers"}];function Hn(e){if(e.model===null||e.source==="claude-settings")return 0;let t=e.model.toLowerCase(),n=Re.findIndex(o=>o.value!==null&&(o.value===t||o.label.toLowerCase()===t||t.includes(o.label.toLowerCase())));return n>=0?n:0}function td(e){switch(e.source){case"project":return".d360-writer.json defaultModel (team setting)";case"user":return"~/.document360-writer/config.json (your /model setting)";case"env":return"ANTHROPIC_MODEL environment variable";case"claude-settings":return"Claude Code's own settings (~/.claude/settings.json)";case"claude-default":return"Claude Code default (no override configured)"}}function Qt(e,t){let n=()=>{let s=Rr(e);return s.source==="project"||s.source==="user"||s.source==="env"?s.model??void 0:void 0};if(t==="default"){let s=Xi();return s.defaultModel?(delete s.defaultModel,Ji(s),{lines:[`\u2713 Personal model override cleared \u2014 now: ${Rr(e).model??"Claude Code default"} (applies from your next message)`],changed:!0,effective:n()}):{lines:["No personal model override set \u2014 nothing to clear."],changed:!1,effective:void 0}}Ji({...Xi(),defaultModel:t});let o=[`\u2713 Personal model set to "${t}" (applies from your next message \u2014 conversation continues)`],r=ed(e)?.defaultModel;return r&&o.push(`\u26A0 .d360-writer.json sets defaultModel "${r}" \u2014 the team setting overrides yours until it is removed.`),{lines:o,changed:!0,effective:n()}}async function Qi(e,t){let n=e[0]?.trim();if(!n){let c=Rr(t.cwd);if(!process.stdin.isTTY)return console.log(`${Te("Model:")} ${O(c.model??"Claude Code default")}`),console.log(m(` source: ${td(c)}`)),console.log(m(" change: /model <haiku|sonnet|opus|full-model-id> \xB7 reset: /model default")),{kind:"continue"};let p=Hn(c),f;try{f=await t.withPausedInput(()=>Zu({message:`Select model (current: ${c.model??"Claude Code default"})`,default:Re[p].value,choices:Re.map((w,P)=>({name:`${w.label}${P===p?" \u2714":""}`,value:w.value,description:w.desc}))}))}catch{return console.log(m("Cancelled.")),{kind:"continue"}}let{lines:b,changed:k,effective:A}=Qt(t.cwd,f??"default");for(let w of b)console.log(w.startsWith("\u26A0")?U(w):w.startsWith("\u2713")?E(w):m(w));return k&&await t.setModel(A),{kind:"continue"}}let{lines:o,changed:r,effective:s}=Qt(t.cwd,n);for(let c of o)console.log(c.startsWith("\u26A0")?U(c):c.startsWith("\u2713")?E(c):m(c));return r&&await t.setModel(s),{kind:"continue"}}qn();async function sa(e,t){return await t.withPausedInput(()=>$t(t.cwd)),{kind:"clear"}}async function ia(e,t){return await t.withPausedInput(()=>Is(t.cwd,t.profileName)),{kind:"clear"}}W();import{resolveActiveProfile as md}from"document360-engine";async function aa(e,t){let n=!1;try{n=md(t.cwd).production}catch{}return n?(console.log(U("\u26A0 Authorizing writes to the PRODUCTION profile for this session.")),{kind:"allow-prod"}):(console.log(m("Current profile is not a production profile \u2014 writes are already allowed.")),{kind:"continue"})}W();var la=async(e,t)=>{try{await t.withPausedInput(()=>Cn({}))}catch(n){console.log($(`Login failed: ${n.message}`))}return{kind:"continue"}};W();import{resolveActiveProfile as hd,clearTokens as gd,clearProfileProject as wd}from"document360-engine";async function ca(e,t){let n;try{n=hd(t.cwd,t.profileName).name}catch(r){return console.log($(r.message)),{kind:"continue"}}let o=gd(n);return wd(t.cwd,n),console.log(o?E(`\u2713 Signed out of "${n}" and cleared its project/workspace selection.`):m(`Profile "${n}" was not signed in. Cleared any project/workspace selection.`)),console.log(m("Run /login to sign in and pick a project.")),{kind:"continue"}}import{existsSync as ua}from"node:fs";import{isAbsolute as yd,join as kd,resolve as bd}from"node:path";import{readProjectConfig as xd,screenshotPlaceholderIds as $d,DEFAULT_CAPTURE_DIR as vd,DEFAULT_OUTPUT_DIR as Cd}from"document360-engine";var da=e=>e.replace(/\\/g,"/").replace(/\/+$/,"");function Dr(e){let t=!e.includes("--no-setup"),n=e.filter(r=>r!=="--no-setup");if(n[0]==="--list")return{mode:"list",scope:n[1]?da(n[1]):void 0};let o=n[0];return!o||o==="--all"?{mode:"all",setup:t}:/[\\/]/.test(o)||o.endsWith(".md")?{mode:"scope",scope:da(o),setup:t}:{mode:"single",id:o}}function jr(e,t){let n=xd(e),o=n?.captureDir??vd,r=n?.outputDir??Cd,s=(c,p)=>yd(c)?kd(c,p):bd(e,c,p);return $d(e,{scope:t}).map(({id:c,file:p})=>{let f=ua(s(r,`${c}.png`))?"captured":ua(s(o,`${c}.spec.ts`))?"spec":"placeholder";return{id:c,file:p,state:f}})}var Pd={placeholder:"\u25CB",spec:"\u25D0",captured:"\u25CF"},Td={placeholder:"placeholder only",spec:"spec written, not captured",captured:"captured"};function Ar(e,t){if(e.length===0)return[t?`No screenshot placeholders under ${t}.`:"No screenshot placeholders found in the docs."];let n=[...new Set(e.map(s=>s.file))].sort(),o=e.filter(s=>s.state==="captured").length,r=[`Screenshots: ${e.length} placeholder${e.length===1?"":"s"} across ${n.length} article${n.length===1?"":"s"} \xB7 ${o} captured${t?` \xB7 scope ${t}`:""}`,""];for(let s of n){r.push(s);for(let c of e.filter(p=>p.file===s))r.push(` ${Pd[c.state]} ${c.id.padEnd(34)} ${Td[c.state]}`)}return r.push("","\u25CB placeholder only \u25D0 spec written \u25CF captured"),r}function pa(e){return["Run the emit-screenshot-spec skill to author the document360-capture spec for EACH of these","SCREENSHOT placeholder ids:",e.paths.map(t=>`- ${t}`).join(`
|
|
240
240
|
`),"","For each: locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir); read the product source for","EXACT routes + stable data-testid selectors (never guess); enter the prepared context via","captureScope(); guard data prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts","(skip-with-TODO if a stable selector is missing). Do NOT run other skills. Report the specs you","wrote and any TODO data-testids."].join(`
|
|
241
241
|
`)}async function Bn(e,t){let n=Dr(e);if(n.mode==="list"){let c=t?.cwd??process.cwd();for(let p of Ar(jr(c,n.scope),n.scope))console.log(p);return{kind:"continue"}}if(n.mode==="single")return{kind:"forward-to-agent",prompt:[`Run the emit-screenshot-spec skill for the SCREENSHOT placeholder with id \`${n.id}\`.`,"Locate its <!-- SCREENSHOT --> block in the docs tree (the configured docsDir), then follow that skill exactly: read the","product source for EXACT routes + stable data-testid selectors (never guess); enter the prepared","context via captureScope(); guard data prerequisites with test.skip(reason); write",`<captureDir>/${n.id}.spec.ts. Report the spec path and any TODO data-testids or data to stage.`].join(`
|
|
242
242
|
`),display:`/screenshot ${n.id}`};let r=[`Run the emit-screenshot-spec skill to (re)generate the document360-capture spec for ${n.mode==="scope"?`every <!-- SCREENSHOT --> placeholder in articles under ${n.scope}`:"every <!-- SCREENSHOT --> placeholder across the docs tree (the configured docsDir)"}.`,"Follow that skill exactly for each: read the SCREENSHOT block; read the product source for EXACT routes","and stable data-testid selectors (never guess); enter the prepared context via captureScope(); guard data",`prerequisites with test.skip(reason); write <captureDir>/<id>.spec.ts.${n.setup?" When done, run capture-setup-checklist to refresh CAPTURE-SETUP.md.":""} Report specs written, TODO data-testids, and data to stage.`].join(`
|
|
@@ -248,10 +248,10 @@ Articles:
|
|
|
248
248
|
`).trimEnd();if(!r)return{lines:["(no output)"],hidden:0};if(n?.startsWith("mcp__document360__")){let c=tp(n.slice(18),o,r);if(c)return{lines:c,hidden:0}}let s=Zd(r)??r.split(`
|
|
249
249
|
`);return{lines:s.slice(0,t).map(c=>he(c,qr)),hidden:Math.max(0,s.length-t)}}function Xn(e,t,n,o="en"){return`${e.replace(/\/$/,"")}/${t}/document/v1/${o}/${n}`}function Jn(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 Qn(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 fp=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function mp(e,t,n,o){if(fp.test(e))try{let r=ja(o),s=typeof t.project_id=="string"&&t.project_id||r.project.projectId,c=Jn(t,n),p=Qn(n);e.endsWith("publish_article")&&p&&console.log(O(` \u2B95 Live: ${p}`)),c&&s&&console.log(O(` \u2B95 Preview: ${Xn(r.connection.portalUrl,s,c,r.project.languageCode??"en")}`))}catch{}}async function Aa(e=process.cwd(),t="auto",n){let o=op(t);o.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(""),console.error(` ${O("export ANTHROPIC_API_KEY=sk-ant-...")} (macOS / Linux)`),console.error(` ${O('$env:ANTHROPIC_API_KEY="sk-ant-..."')} (PowerShell)`),console.error(""),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),console.error(""),process.exit(2)),hp(e,n),o.kind==="subscription"&&(o.stored?console.log(m(" Using your Claude subscription (no API key set).")):console.log(m(" No API key or stored Claude Code login found \u2014 trying your Claude session anyway.")),console.log(""));let r=!1,s=Br({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1},p=np({input:process.stdin,output:process.stdout}),f=[],b=null,k=!1;p.on("line",P=>{if(b){let C=b;b=null,C(P)}else f.push(P)}),p.on("close",()=>{if(k=!0,b){let P=b;b=null,P(null)}});function A(){return f.length>0?Promise.resolve(f.shift()):k?Promise.resolve(null):(process.stdout.write(O("> ")),new Promise(P=>{b=P}))}let w={cwd:e,profileName:n,allowProdWrites:()=>r,restartAgent:()=>{s.close(),s=Br({cwd:e,profileName:n,allowProdWrites:r}),c={uuid:null,firstPrompt:null,titleFired:!1}},currentUuid:()=>c.uuid,setModel:async P=>s.setModel(P),withPausedInput:async P=>{p.pause();try{return await P()}finally{p.resume()}}};try{for(;;){let P=await A();if(P===null)break;let C=P.trim();if(C){if(C.startsWith("/")){let R=va(C);if(!R)continue;let I=$a[R.name];if(!I){console.log($(`Unknown command: /${R.name}`)),console.log(m("Type /help for the list."));continue}let H=await I(R.args,w);if(H.kind==="exit")break;if(H.kind==="clear"){w.restartAgent();continue}if(H.kind==="allow-prod"){r=!0,w.restartAgent(),console.log(E("\u2713 Production writes authorized for this session.")),console.log("");continue}if(H.kind==="resume"){s.close(),s=Br({cwd:e,resume:H.uuid,profileName:n,allowProdWrites:r});let se=rp(H.uuid);c={uuid:H.uuid,firstPrompt:se?.firstPrompt??null,titleFired:!0},Da(H.uuid),console.log(E(`\u2713 Resumed "${H.name}"`)),console.log("");continue}H.kind==="forward-to-agent"&&(c.firstPrompt||(c.firstPrompt=H.display??H.prompt),await Sa(s,H.prompt,o,c,e));continue}c.firstPrompt||(c.firstPrompt=C),await Sa(s,C,o,c,e)}}}finally{s.close(),p.close()}}function hp(e,t){console.log(""),console.log(Ft("document360-writer")),console.log(m(` cwd: ${e}`));let n=cp(e);if(console.log(m(` model: ${n.model??"auto (engine right-sizes per task)"}${n.model?` (${n.source})`:""}`)),console.log(gp(e,t)),!up(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{An(e);for(let o of En(e))console.log(U(` ${o}`))}catch{}try{let o=Dt(St(e));o&&console.log(U(` \u{1F4CB} ${o} from the repo's coding agent \u2014 run /catch-up.`))}catch{}}console.log(m(" Type a prompt, or /help for slash commands. /exit to quit.")),console.log("")}function gp(e,t){try{let n=ja(e,t),o=n.production?U(" \u26A0 PRODUCTION"):"",r=pp(n.name);if(!r)return m(` Document360: profile "${n.name}"${o} \u2014 not logged in (d360-writer login)`);let s={...Ra(r.idToken)??{},...Ra(r.accessToken)??{}},c=s.email??s.preferred_username??"signed in";return dp(r)&&!r.refreshToken?U(` Document360: profile "${n.name}"${o} \u2014 session expired (d360-writer login)`):m(` Document360: ${c} \xB7 profile "${n.name}"${o}`)}catch(n){return m(` Document360: ${n.message.split(".")[0]}`)}}function wp(){console.error(""),console.error(`Sign in with your Claude subscription: run ${O("claude")} once, then retry.`),console.error(` (No Claude Code? ${O("npm install -g @anthropic-ai/claude-code")})`),console.error(`Or set an API key: ${O("https://console.anthropic.com/settings/keys")}`)}function yp(e,t,n){e.uuid=t;let o=new Date().toISOString();ap({uuid:t,name:ip(e.firstPrompt??"session"),renamed:!1,titled:!1,cwd:n,firstPrompt:e.firstPrompt??"",createdAt:o,updatedAt:o})}function kp(e,t){e.titleFired=!0;let n=e.uuid,o=e.firstPrompt;!n||!o||lp(o,t).then(r=>{r&&sp(n,r)}).catch(()=>{})}async function Sa(e,t,n,o,r){let s=new Map;for await(let c of e.send(t))bp(c,o,r,n,s)}function bp(e,t,n,o,r){switch(e.type){case"session":t.uuid||yp(t,e.sessionId,n);break;case"text":process.stdout.write(e.delta);break;case"tool":{let s=zn(e.name,e.input);s&&(process.stdout.write(`
|
|
250
250
|
|
|
251
|
-
`),console.log(`${E("\u25CF")} ${
|
|
252
|
-
`),console.log(m(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Da(t.uuid),t.titleFired||kp(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&wp();break}}import{render as Df}from"ink";import{resolveAuth as jf}from"document360-engine";import{useCallback as Y,useEffect as
|
|
251
|
+
`),console.log(`${E("\u25CF")} ${Te(s.title)}${s.arg!==null?oe(`${s.sep}(${s.arg})`):""}`),r.set(e.id,{name:e.name,input:e.input}));break}case"article_diff":{let s=rt(e.oldContent,e.newContent,Math.max(40,(process.stdout.columns??80)-1));if(!s)break;let c=p=>p===1?"":"s";console.log(oe(` \u23BF Added ${s.added} line${c(s.added)}, removed ${s.removed} line${c(s.removed)}`));for(let p of s.lines)console.log(p);s.hidden>0&&console.log(m(` \u2026 +${s.hidden} more diff lines`));break}case"tool_result":{let s=r.get(e.id);if(!s)break;r.delete(e.id);let c=Kn(e.output,4,e.isError?void 0:s.name,s.input),p=e.isError?$:oe;c.lines.forEach((f,b)=>console.log(p((b===0?" \u23BF ":" ")+f))),c.hidden>0&&console.log(m(` \u2026 +${c.hidden} lines`)),e.isError||mp(s.name,s.input,e.output,n);break}case"result":process.stdout.write(`
|
|
252
|
+
`),console.log(m(` (${e.inputTokens}\u2192${e.outputTokens} tokens`+(e.costUsd>0?`, $${e.costUsd<.01?e.costUsd.toFixed(4):e.costUsd.toFixed(2)}`:"")+")")),console.log(""),t.uuid&&(Da(t.uuid),t.titleFired||kp(t,n));break;case"error":console.error(""),console.error($(`agent error: ${e.message}`)),o.kind==="subscription"&&e.kind==="auth"&&wp();break}}import{render as Df}from"ink";import{resolveAuth as jf}from"document360-engine";import{useCallback as Y,useEffect as $e,useMemo as Xr,useRef as X,useState as F}from"react";import{Box as te,Text as T,useApp as Op,useInput as Up,useStdout as Lp}from"ink";import{existsSync as jt,readFileSync as Jr,readdirSync as os}from"node:fs";import{spawnSync as Mp}from"node:child_process";import{basename as on,isAbsolute as Wp,join as At}from"node:path";import{createSession as sl,classifyClaudeAuth as rs,CLAUDE_CODE_SETUP_HINT as Fp,loginPkce as Hp,toStoredTokens as qp,saveTokens as Bp,getAccessToken as Gp,resolveActiveProfile as pe,resolveProjectId as Yp,getArticle as Vp,decodeJwtClaims as Et,isExpired as _e,loadTokens as Be,clearTokens as zp,clearProfileProject as Kp,setTitle as Xp,slugify as Jp,touchSession as Qr,upsertSession as Qp,generateTitle as il,findByName as Zp,listSessions as ef,renameSession as tf,suggestNextAction as nf,readProjectConfig as ee,writeProjectConfig as al,resolveModelSetting as ss,loadProfileMap as Zr,applyPull as of,computeSyncStatus as es,planPull as rf,establishBaselines as sf,inventoryRepo as af,knownEnvironments as lf,resolveEnvironment as cf,planPartitions as ts,partitionEvenly as uf,screenshotPlaceholderIds as df,trackedArticlePaths as pf,runPartitioned as ao,estimateBulkCost as ll,resolveModelForOperation as lo,readDocsPlan as cl,checkForUpdate as ff,detectInstallKind as mf,isSelfUpdatable as hf,devHintsGuidePath as ul,toolFeedbackPath as gf,reconcileToolFeedback as wf,DEFAULT_DOCS_DIR as uo,setProfileProject as yf}from"document360-engine";ot();import{spawn as Ea}from"node:child_process";function xp(){return process.platform==="win32"?[["clip",[]]]:process.platform==="darwin"?[["pbcopy",[]]]:[["wl-copy",[]],["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]]}function $p(e,t,n){return new Promise(o=>{try{let r=process.platform==="win32"?Ea([e,...t].join(" "),{stdio:["pipe","ignore","ignore"],shell:!0}):Ea(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 Ia(e){for(let[t,n]of xp())if(await $p(t,n,e))return!0;return!1}var vp=/\breply with (the |a )?number\b|\bpick one\b|\bpress the number\b/i;function Gr(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){vp.test(s)&&(t.cueSeen=!0);continue}let c=/^(\s{0,3})[-*•]\s+(.*)$/.exec(s);c?(n[r]=`${c[1]}${++t.num}. ${c[2]}`,o=!0):o&&s.trim()!==""&&/^\S/.test(s)&&(t.closed=!0)}return n.join(`
|
|
254
|
-
`)}import{existsSync as Cp,mkdirSync as Pp,readFileSync as Tp,writeFileSync as Rp}from"node:fs";import{join as Na}from"node:path";import{writerDir as Sp}from"document360-engine";function _a(e){return Na(Sp(e),".sessions")}function Oa(e,t){return Na(_a(e),`${t}.json`)}function Ua(e,t,n){try{Pp(_a(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Rp(Oa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Yr(e,t){try{let n=Oa(e,t);if(!Cp(n))return[];let o=JSON.parse(Tp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Dp=e=>`\x1B]0;${e}\x07`,jp=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function La(e){process.stdout.isTTY&&process.stdout.write(e)}function tn(e){La(Dp(e))}function Zn(e){La(jp(e))}var eo=["\xB7 "," \xB7"],Vr="\u{1F7E3}";qn();var to=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all] [baseline]",desc:"Drift report local vs Document360; pull portal edits; baseline = set a sync base for not-yet-compared articles",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Ma={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/sync":"check Document360 for changes made there","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Wa(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ma[n])return Ma[n];let o=to.find(r=>r.name===t);return o?o.desc:""}function Fa(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return to.filter(n=>n.name.startsWith(t))}function Ha(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as qa,Text as re}from"ink";import{jsx as ie,jsxs as no}from"react/jsx-runtime";function Ap({row:e}){switch(e.t){case"head":return ie(re,{color:M,bold:!0,children:e.s});case"text":return ie(re,{children:e.s});case"dim":return ie(re,{dimColor:!0,children:e.s});case"sub":return ie(re,{bold:!0,dimColor:!0,children:e.s});case"good":return ie(re,{color:"green",children:e.s});case"step":return no(re,{children:[ie(re,{color:M,children:`${e.n}. `}),e.s]});case"cmd":return no(re,{children:[" ",ie(re,{color:M,children:e.name.padEnd(20)}),ie(re,{dimColor:!0,children:e.s})]});case"gap":return ie(re,{children:" "})}}function Ba({tab:e,width:t}){let n=
|
|
254
|
+
`)}import{existsSync as Cp,mkdirSync as Pp,readFileSync as Tp,writeFileSync as Rp}from"node:fs";import{join as Na}from"node:path";import{writerDir as Sp}from"document360-engine";function _a(e){return Na(Sp(e),".sessions")}function Oa(e,t){return Na(_a(e),`${t}.json`)}function Ua(e,t,n){try{Pp(_a(e),{recursive:!0});let o=n.filter(r=>r.kind!=="banner");Rp(Oa(e,t),JSON.stringify({v:1,items:o}),"utf8")}catch{}}function Yr(e,t){try{let n=Oa(e,t);if(!Cp(n))return[];let o=JSON.parse(Tp(n,"utf8"));return Array.isArray(o.items)?o.items:[]}catch{return[]}}var Dp=e=>`\x1B]0;${e}\x07`,jp=e=>`\x1B]9;4;${e};${e===1?100:0}\x07`;function La(e){process.stdout.isTTY&&process.stdout.write(e)}function tn(e){La(Dp(e))}function Zn(e){La(jp(e))}var eo=["\xB7 "," \xB7"],Vr="\u{1F7E3}";qn();var to=[{name:"init",usage:"/init",desc:"Pick an environment, scaffold .d360-writer.json, and set up the builder hand-off (prints the one-paste prompt)",group:"start"},{name:"login",usage:"/login",desc:"Sign in to Document360 (browser)",group:"start"},{name:"project",usage:"/project [name]",desc:"Choose the Document360 project (picker; lists all you can access)",group:"start"},{name:"devhints",usage:"/devhints",desc:"Re-show/refresh the builder hand-off prompt (set up by /init; run anytime to hand your repo agent the latest)",group:"start"},{name:"scope",usage:"/scope",desc:"Choose which repo folders back the docs (monorepos)",group:"start"},{name:"mcp",usage:"/mcp [list|add|remove]",desc:"Connect MCP servers (Notion, Linear, \u2026)",group:"start"},{name:"draft",usage:"/draft [<feature>]",desc:"Draft a feature's articles from its PRDs/specs in .d360-writer/input/ + the code",group:"docs"},{name:"document",usage:"/document [<what>] [--publish]",desc:"Document a shipped change \u2014 the agent picks the action (new section/article/update); bare: act on builder requests",group:"docs"},{name:"write",usage:"/write [--preview|--scope <cat>|<path>] [--concurrency N]",desc:"Write the planned articles in parallel (starts immediately; --preview shows plan + cost first; --concurrency default 3)",group:"docs"},{name:"screenshot",usage:"/screenshot [--list|id|--all|path]",desc:"--list: status; else author capture specs (bulk also refreshes the capture checklist; --no-setup skips)",group:"docs"},{name:"capture-setup",usage:"/capture-setup",desc:"Re-run the data-staging checklist + dev test-id requests (auto-runs after /screenshot --all)",group:"docs"},{name:"preview",usage:"/preview [path|id]",desc:"Render an article (no arg: pick from tracked)",group:"docs"},{name:"publish",usage:"/publish [path|--all]",desc:"Publish to Document360 (no arg: pick; --all: every candidate)",group:"publish"},{name:"audit",usage:"/audit [--auto on|off]",desc:"Gap analysis: code vs docs vs Document360 (what changed); --auto runs it at launch when code changed",group:"publish"},{name:"inbox",usage:"/inbox",desc:"Act on messages from the repo's coding agent (requests to document, answers to your questions)",group:"publish"},{name:"catch-up",usage:"/catch-up [--publish]",desc:"Process ALL pending work (hints + requests + drift) \u2192 write \u2192 push to Document360 (bare = drafts; --publish goes live)",group:"publish"},{name:"sync",usage:"/sync [pull <path>|--all] [baseline]",desc:"Drift report local vs Document360; pull portal edits; baseline = set a sync base for not-yet-compared articles",group:"publish"},{name:"convert",usage:"/convert [--scope <folder>] [--run]",desc:"Convert tracked articles to DFM (one-off legacy migration)",group:"publish"},{name:"profile",usage:"/profile [name|add <name> [env]]",desc:"Switch/create a Document360 connection (picker; s = session)",group:"setup"},{name:"workspace",usage:"/workspace [name]",desc:"Switch the Document360 workspace (picker)",group:"setup"},{name:"model",usage:"/model [name|default]",desc:"Set the Claude model for d360-writer",group:"setup"},{name:"logout",usage:"/logout",desc:"Sign out + clear project/workspace selection (then /login to re-pick)",group:"setup"},{name:"allow-prod",usage:"/allow-prod",desc:"Authorize writes to a production profile",group:"setup"},{name:"doctor",usage:"/doctor",desc:"Health-check: auth, profile, workspace, map, API",group:"setup"},{name:"update",usage:"/update",desc:"Update d360-writer to the latest version (then relaunch)",group:"setup"},{name:"reset",usage:"/reset",desc:"[DANGER] Delete all d360-writer files (docs, config, screenshots); types repo name to confirm",group:"setup"},{name:"resume",usage:"/resume [name]",desc:"Resume a session (no arg lists them)",group:"session"},{name:"rename",usage:"/rename [name]",desc:"Name the session (no arg: suggest one)",group:"session"},{name:"clear",usage:"/clear",desc:"Reset the conversation (resumable)",group:"session"},{name:"help",usage:"/help",desc:"Show this help",group:"session"},{name:"exit",usage:"/exit",desc:"Quit",group:"session"}],Ma={"/catch-up":"write up everything your builder flagged","/audit":"check the code for anything new or missing in the docs","/sync":"check Document360 for changes made there","/publish":"publish your drafts to Document360","/write":"author the planned articles","/draft":"plan articles from PRDs + the code","/login":"sign in to Document360","/workspace":"choose the Document360 workspace","/project":"choose the Document360 project","/scope":"choose which folders back the docs","/init":"set up this repo","/screenshot":"generate screenshots","/doctor":"run a health check"};function Wa(e){let t=e.trim().replace(/^\//,"").split(/\s+/)[0]??"",n=`/${t}`;if(Ma[n])return Ma[n];let o=to.find(r=>r.name===t);return o?o.desc:""}function Fa(e){if(!e.startsWith("/"))return[];let t=e.slice(1).toLowerCase().split(/\s/)[0]??"";return to.filter(n=>n.name.startsWith(t))}function Ha(e){return/<[^>]+>/.test(e.replace(/\[[^\]]*\]/g,""))}W();import{Box as qa,Text as re}from"ink";import{jsx as ie,jsxs as no}from"react/jsx-runtime";function Ap({row:e}){switch(e.t){case"head":return ie(re,{color:M,bold:!0,children:e.s});case"text":return ie(re,{children:e.s});case"dim":return ie(re,{dimColor:!0,children:e.s});case"sub":return ie(re,{bold:!0,dimColor:!0,children:e.s});case"good":return ie(re,{color:"green",children:e.s});case"step":return no(re,{children:[ie(re,{color:M,children:`${e.n}. `}),e.s]});case"cmd":return no(re,{children:[" ",ie(re,{color:M,children:e.name.padEnd(20)}),ie(re,{dimColor:!0,children:e.s})]});case"gap":return ie(re,{children:" "})}}function Ba({tab:e,width:t}){let n=xe[e]??xe[0],o=6+xe.reduce((s,c)=>s+c.label.length+4,0),r="\u2500".repeat(Math.min(o,Math.max(t-1,20)));return no(qa,{flexDirection:"column",paddingX:1,children:[no(re,{children:[ie(re,{color:M,bold:!0,children:"Help "}),xe.map((s,c)=>c===e?ie(re,{color:M,bold:!0,inverse:!0,children:` ${s.label} `},s.key):ie(re,{dimColor:!0,children:` ${s.label} `},s.key))]}),ie(re,{color:M,children:r}),ie(qa,{flexDirection:"column",marginTop:1,children:n.rows.map((s,c)=>ie(Ap,{row:s},c))}),ie(re,{dimColor:!0,children:`
|
|
255
255
|
\u2190/\u2192 or tab switch \xB7 1-5 jump \xB7 esc close`})]})}var Ep=/^(?:\d+[.)]|[-*•])\s+/;function Ga(e,t,n=4){let o=new Set(t.map(s=>s.toLowerCase())),r=[];for(let s of e.split(`
|
|
256
256
|
`)){let c=s.trim().replace(Ep,""),p=c.match(/^`([^`]+)`$/);p&&(c=p[1].trim());let f=c.match(/^\/([a-z?][a-z0-9-]*)(?:\s+(\S.*?))?\s*$/i);if(!f||!o.has(f[1].toLowerCase()))continue;let b=`/${f[1].toLowerCase()}${f[2]?` ${f[2]}`:""}`;if(r.includes(b)||r.push(b),r.length>=n)break}return r}W();function nn(e){return e.map(t=>({label:t.label,items:t.paths.length,status:"pending"}))}function Ne(e,t,n){return e.map(o=>o.label===t?{...o,status:n}:o)}function zr(e){return e.replace(/^[\w.-]+\//,"")}var oo=16,Ya={pending:"\u25CB",active:"\u25A0",done:"\u2714",failed:"\u2717"};function Kr(e){return e.trim().split(/\s+/).slice(1).join(" ")}function Va(e,t){let n=Kr(t);return e.some(r=>r.trim()===t.trim()||!!n&&Kr(r)===n)?e.filter(r=>r.trim()!==t.trim()&&!(n&&Kr(r)===n)):[]}var Ip='\u{1F4ED} No docs yet for this repo. Tell me "write the docs for this repo" and I\u2019ll read the code and draft a structure \u2014 or /audit to see what the docs should cover.';function Np(e,t){switch(e){case"/write":return"finish the planned articles that aren\u2019t written yet";case"/catch-up":return"write up everything your builder flagged";case"/audit":return t?"also scan the code for other changes":"check the code for anything new or missing in the docs";case"/sync":return"check Document360 for changes made there";default:return""}}function ro(e){return e===1?"":"s"}function za(e,t,n){return[e,...t.map((o,r)=>` ${r+1} ${o.padEnd(9)} ${Np(o,n)}`),"Or just tell me what to write or update."].join(`
|
|
257
257
|
`)}function Ka(e){if(!e.ready)return{kind:"idle"};let t=!!e.pendingText;if(!e.hasDocs)return{kind:"noDocs",note:Ip,ghost:"write the docs for this repo",title:t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:null,options:t?["/catch-up","/audit"]:["/audit"]};if(e.pendingWrites>0){let r=t?["/write","/catch-up"]:["/write","/audit"],s=`\u{1F4DD} ${e.pendingWrites} planned article${ro(e.pendingWrites)} not written yet \u2014 pick up where you left off:`;return{kind:"actions",note:za(s,r,t),title:s,options:r}}if(!t&&e.behind>0&&e.autoAudit&&e.allowAutoAudit)return{kind:"autoAudit",note:`\u{1F4CB} ${e.behind} code change${ro(e.behind)} since your last docs check \u2014 running /audit automatically (auto-audit is on)\u2026`};let n=t?["/catch-up","/audit"]:["/audit","/sync"],o=t?`\u{1F4CB} Your builder left ${e.pendingText} for the docs:`:e.behind>0?`\u{1F4CB} ${e.behind} code change${ro(e.behind)} since your last docs check \u2014 /audit to see what needs updating (or /audit --auto on to run it for you):`:`\u{1F4DA} ${e.tracked} article${ro(e.tracked)} tracked for "${e.profileName}". What next?`;return{kind:"actions",note:za(o,n,t),title:o,options:n}}var _p=/\[Pasted text #\d+ \+\d+ lines?\]/g;function Xa(e){return e.replace(/\r\n?/g,`
|
|
@@ -263,11 +263,11 @@ Articles:
|
|
|
263
263
|
`),truncated:c>0||f>0}}}return{text:e,truncated:!1}}function rl(e){let t=!1,n=0,o=0;for(let r of e.split(`
|
|
264
264
|
`)){let s=o+r.length;/^\s*```/.test(r)?t=!t:!t&&r.trim()===""&&s<e.length&&(n=s+1),o=s+1}return n}import{Fragment as ns,jsx as j,jsxs as B}from"react/jsx-runtime";var kf={project:".d360-writer.json",user:"/model",env:"ANTHROPIC_MODEL","claude-settings":"Claude Code settings","claude-default":""},dl=` 1. /init \u2014 pick your Document360 environment & scaffold config
|
|
265
265
|
2. /login \u2014 sign in & pick your Document360 project (workspace auto-selected)
|
|
266
|
-
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function bf(e,t,n,o){let r=rs(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=ss(e),p=ee(e),f=(p?.docsDir??uo).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${f}/ + config`,k={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:kf[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 k;try{let A=pe(e,o);k.profile=A.name,k.apiUrl=A.connection.apiUrl,k.prod=A.production,k.project=A.project.projectName??A.project.projectId??"(chosen at login)";let w=Be(A.name);if(w){let P={...Et(w.idToken)??{},...Et(w.accessToken)??{}},C=P.email??P.preferred_username??"signed in";_e(w)?w.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(w.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function xf(e,t){try{let n=pe(e,t),o=Be(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Et(o.idToken)??{},...Et(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return _e(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var pl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],po=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$f="Ask me to write or update an article\u2026";function co({ch:e,dim:t}){let[n,o]=F(!0);return
|
|
266
|
+
3. I'll hand you a one-paste prompt for your builder \u2014 then just ask me to write the docs`;function bf(e,t,n,o){let r=rs(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=ss(e),p=ee(e),f=(p?.docsDir??uo).replace(/\/+$/,""),b=p?.mode==="engineer"?"engineer \xB7 full source access (dogfooding)":`writer \xB7 edits limited to ${f}/ + config`,k={version:t,claude:s,model:c.model??"Claude Code default model",modelSource:kf[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 k;try{let A=pe(e,o);k.profile=A.name,k.apiUrl=A.connection.apiUrl,k.prod=A.production,k.project=A.project.projectName??A.project.projectId??"(chosen at login)";let w=Be(A.name);if(w){let P={...Et(w.idToken)??{},...Et(w.accessToken)??{}},C=P.email??P.preferred_username??"signed in";_e(w)?w.refreshToken&&(k.who=C,k.loggedOut=!1,k.sessionHint="session expired \u2014 refreshing\u2026"):(k.who=C,k.loggedOut=!1,k.sessionHint=`session valid until ${new Date(w.expiresAt).toLocaleString(void 0,{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"short"})}`)}}catch{}return k}function xf(e,t){try{let n=pe(e,t),o=Be(n.name);if(!o)return{text:`profile "${n.name}" \u2014 not logged in (/login)`,prod:n.production};let r={...Et(o.idToken)??{},...Et(o.accessToken)??{}},s=r.email??r.preferred_username??"signed in";return _e(o)&&!o.refreshToken?{text:`profile "${n.name}" \u2014 session expired (/login)`,prod:n.production}:{text:`${s} \xB7 profile "${n.name}"`,prod:n.production}}catch(n){return{text:n.message.split(".")[0],prod:!1}}}var pl=["Drafting","Composing","Outlining","Researching","Documenting","Structuring","Polishing","Synthesizing","Curating","Distilling","Weaving","Wrangling","Pondering"],po=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$f="Ask me to write or update an article\u2026";function co({ch:e,dim:t}){let[n,o]=F(!0);return $e(()=>{let r=setInterval(()=>o(s=>!s),530);return()=>clearInterval(r)},[]),j(T,{inverse:n,color:t&&!n?"gray":void 0,children:e})}var vf=/^mcp__document360__d360_(create_article|update_article|fork_article|publish_article)$/;function fl(e){let t=e.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/);return t?e.slice(t[0].length):e}var Cf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ml(e){try{return os(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith(".")).length>6}catch{return!1}}function hl(e,t){let n=t??[];return n.length===0?["src","api","services","packages","modules"].some(o=>ml(At(e,o))):n.some(o=>!o.includes("/")&&!o.endsWith(".md")&&ml(At(e,o)))}function Pf({startTime:e,chars:t}){let[n,o]=F(0);$e(()=>{let f=setInterval(()=>o(b=>b+1),120);return()=>clearInterval(f)},[]);let r=po[n%po.length],s=pl[Math.floor(n/16)%pl.length],c=Math.floor((Date.now()-e)/1e3),p=Math.round(t/4);return B(te,{children:[j(T,{color:M,children:` ${r} ${s}\u2026 `}),j(T,{color:"gray",children:`(${zt(c)} \xB7 ~${p} tokens \xB7 esc to interrupt)`})]})}var Tf=12e4;function Rf({p:e}){let[t,n]=F(0);$e(()=>{let I=setInterval(()=>n(H=>H+1),150);return()=>clearInterval(I)},[]);let o=po[t%po.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>=Tf,f=e.verb??"Converting",b=e.unit??"article",k=e.rows.reduce((I,H)=>I+H.items,0),A=f.toLowerCase(),w=e.rows,P=0;if(w.length>oo){let I=w.findIndex(se=>se.status==="active"||se.status==="pending"),H=Math.max(0,Math.min(I-2,w.length-oo));P=w.slice(0,H).filter(se=>se.status==="done").length,w=w.slice(H,H+oo)}let C=Math.min(40,Math.max(...w.map(I=>zr(I.label).length),0)),R=I=>I==="failed"?"red":I==="active"?M:void 0;return B(te,{flexDirection:"column",children:[B(te,{children:[j(T,{color:M,children:` ${o} ${f} ${k} ${b}${k===1?"":"s"} `}),j(T,{color:"gray",children:`\xB7 ${e.done}/${e.total} \xB7 ${e.tools} tool call${e.tools===1?"":"s"} \xB7 ~${c} tokens \xB7 ${zt(r)} \xB7 esc to stop`})]}),P>0&&j(T,{dimColor:!0,children:` \u2714 +${P} done`}),w.map(I=>B(T,{color:R(I.status),dimColor:I.status==="done"||I.status==="pending",children:[` ${Ya[I.status]} ${zr(I.label).padEnd(C)}`,I.status!=="pending"?` (${I.items} ${b}${I.items===1?"":"s"})`:"",I.status==="active"?` \u2190 ${A}\u2026`:""]},I.label)),p&&j(T,{color:"yellow",children:` \u26A0 no activity for ${zt(s)} \u2014 press esc to stop if it's wedged`})]})}var Sf=10800*1e3;function gl({cwd:e,auth:t,profileName:n,version:o}){let{exit:r}=Op(),[s,c]=F(n),[p,f]=F(null),[b,k]=F({text:"",pos:0}),A=b.text,w=Y(l=>{k(a=>{let i=typeof l=="function"?l(a.text):l;return{text:i,pos:i.length}})},[]),P=Y(l=>{k(a=>({text:a.text.slice(0,a.pos)+l+a.text.slice(a.pos),pos:a.pos+l.length}))},[]),C=Y(()=>{k(l=>{if(l.pos===0)return l;let a=l.text.slice(0,l.pos),i=el(a)??a.slice(0,-1);return{text:i+l.text.slice(l.pos),pos:i.length}})},[]),[R,I]=F(!1),[H,se]=F(!1),[ve,ae]=F(0),[Ce,le]=F(null),[Ge,G]=F([]),it=X(0),[vl,rn]=F(!1),[Cl,sn]=F(!1),[Pl,at]=F(0),Ye=X(0),[It,lt]=F(0),[ct,an]=F(null),cs=X(new Map),Tl=X(0),ut=X([]),ge=X(null);ge.current===null&&(ge.current=sl({cwd:e,profileName:s,allowProdWrites:!1}));let Se=X({uuid:null,firstPrompt:null,titleFired:!1}),ln=X(new Map),dt=X(!1),fo=X([]),Ue=X([]),mo=X(null),[us,pt]=F(null),[Ve,ze]=F(null),[De,ft]=F(null),[Le,mt]=F(null),[ue,ht]=F(null),[we,Ke]=F(null),[Xe,gt]=F(null),[ds,Je]=F(null),[ye,Qe]=F(null),[fe,wt]=F(null),[ps,ho]=F([]),Ze=X([]),Nt=X(!1),ke=X(null),[fs,J]=F(null),cn=X(!1),un=X(null),_t=X(null),[be,et]=F(null),[go,Ot]=F(null),[ms,yt]=F(0),[hs,kt]=F(0),[Rl,gs]=F(0),wo=Xr(()=>{try{return ss(e).model??"auto"}catch{return null}},[e,Rl]),{stdout:Pe}=Lp(),[,Sl]=F(0),ws=X(`${Pe.columns??80}x${Pe.rows??24}`),Me=Y(()=>Math.max(20,(Pe.columns??80)-1),[Pe]),d=Y(l=>{ut.current.push(l),console.log(Ko(l,Me()))},[Me]),[yo,ko]=F(null),bt=Y(l=>{ko(l),d({kind:"note",tone:"info",text:"\u2328 Press c to copy the prompt above to your clipboard (then paste it into your coding agent)."})},[d]),bo=X(!1),xo=Y(async()=>{try{if(bo.current||!hf(mf())||ee(e)?.mode==="engineer")return;let l=await ff({pkg:st,currentVersion:o,force:!0});if(!l.updateAvailable||!l.latest)return;bo.current=!0,d({kind:"note",tone:"info",text:`\u2B06 Updating ${st} ${l.current} \u2192 ${l.latest}\u2026 (wait for the \u2713 before you /exit)`}),sn(!0),(await Yn().finally(()=>sn(!1))).ok?(d({kind:"note",tone:"ok",text:`\u2713 Updated to v${l.latest} \u2014 run /exit, then relaunch to apply.`}),G(i=>i.includes("/exit")?i:[...i,"/exit"])):d({kind:"note",tone:"warn",text:`Update available (v${l.latest}) but auto-update failed \u2014 run: ${Gn}`})}catch{}},[e,o,d]),$o=Y(l=>{let a=Ie(e,s);return a.ok?!0:(d({kind:"note",tone:"warn",text:a.reason}),_t.current=l,G(["/login"]),!1)},[e,s,d]),[vo,Co]=F(null),Ut=X(!0),dn=X(0),Lt=X(0);$e(()=>{let l=setInterval(()=>{if(Ut.current){dn.current=0,Lt.current=0;return}if(!R)try{if(!jt(ul(e)))return;if(Ee(e).status==="current"){Ut.current=!0,dn.current=0,Lt.current=0,d({kind:"note",tone:"ok",text:"\u2713 Your builder finished the hand-off \u2014 the architecture brief is in. I can read this repo now and write accurate docs."}),ko(null),le("write the docs for this repo");return}dn.current+=1;let a=dn.current;if((a===4||a%15===0)&&Lt.current<3){Lt.current+=1;let i=Lt.current===3?" (I'll stay quiet now \u2014 type anything to continue.)":"";d({kind:"note",tone:"info",text:Gt(e)?`\u{1F440} Your builder is working on the architecture brief \u2014 I'll continue automatically when it finishes.${i}`:`\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.${i}`})}}catch{}},4e3);return()=>clearInterval(l)},[e,R,d]),$e(()=>{let l=`d360-writer \xB7 ${us??on(e)}`;if(!R){Zn(0),tn(`${Vr} ${l}`);return}Zn(3);let a=0;tn(`${eo[0]} ${l}`);let i=setInterval(()=>{a=(a+1)%eo.length,tn(`${eo[a]} ${l}`)},400);return()=>clearInterval(i)},[R,e,us]),$e(()=>()=>Zn(0),[]);let Po=Y(l=>{try{let a=ee(e);if(!a)return{kind:"idle"};let i=pe(e,s),g=Be(i.name),u=!!g&&(!_e(g)||!!g.refreshToken),h=!hl(e,a.authoritativeSourceFiles),y=rs(t).state==="missing",v=Zr(e,i.name),D=v?Object.keys(v.articles).length:0,_=At(e,(a.docsDir??uo).replace(/\/+$/,"")),K=!1;try{K=jt(_)&&os(_).length>0}catch{}let Q=0;if(v?.lastAnalyzedCommit)try{let S=Mp("git",["rev-list","--count",`${v.lastAnalyzedCommit}..HEAD`],{cwd:e,encoding:"utf8",timeout:3e3});S.status===0&&(Q=parseInt((S.stdout||"").trim(),10)||0)}catch{}let N=0;try{let S=cl(e);if(S.length>0){let L=(a.docsDir??uo).replace(/\/+$/,"");N=pr(e,L,S.map(Z=>Z.path)).length}}catch{}let x={ready:u&&h&&!y,hasDocs:K,tracked:D,pendingText:Dt(St(e)),behind:Q,pendingWrites:N,autoAudit:!!a.autoAudit,profileName:i.name,allowAutoAudit:l};return Ka(x)}catch{return{kind:"idle"}}},[e,s,t]);$e(()=>{d({kind:"banner",info:bf(e,o,t,s)});let l=rs(t).state==="missing";if(l&&d({kind:"note",tone:"warn",text:`\u26A0 Set up Claude first \u2014 d360-writer's agent runs on Claude Code, and it's not signed in on this machine yet.
|
|
267
267
|
${Fp}
|
|
268
268
|
Run /doctor anytime to re-check and see the fix. (You can configure Document360 meanwhile \u2014 the agent just needs Claude before it writes.)`}),!ee(e)){d({kind:"note",tone:"info",text:`Welcome! This repo isn't set up for d360-writer yet \u2014 three steps and you're writing docs:
|
|
269
269
|
${dl}`}),G(l?["/doctor","/init"]:["/init"]);return}l&&G(["/doctor"]);try{let i=pe(e,s),g=Be(i.name);g&&_e(g)&&g.refreshToken?Gp({profile:i.name,connection:i.connection}).then(()=>{d({kind:"note",tone:"ok",text:"\u2713 Document360 session refreshed."}),ae(u=>u+1)}).catch(()=>{d({kind:"note",tone:"warn",text:"Document360 session refresh failed \u2014 do you want to log in now? (press 1)"}),G(["/login"])}):(!g||_e(g))&&(d({kind:"note",tone:"warn",text:`Profile "${i.name}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"]))}catch{}try{let i=ee(e),g=pe(e,s),u=Be(g.name);i&&u&&!_e(u)&&hl(e,i.authoritativeSourceFiles)&&(d({kind:"note",tone:"info",text:"Large repo \u2014 the docs scope isn\u2019t set yet. Run /scope to choose which folders back your docs."}),G(["/scope"]))}catch{}try{if(An(e),Ee(e).status!=="current")if(Gt(e))d({kind:"note",tone:"info",text:`\u{1F514} A newer dev\u2194docs protocol (v${ne}) is available \u2014 your builder can re-run /devhints when convenient. Your docs aren't blocked.`});else{let i=En(e);i.length&&(d({kind:"note",tone:"warn",text:i.join(`
|
|
270
|
-
`)}),bt(nt()),Ut.current=!1)}}catch{}try{let i=wf(e);i.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${i.archived} resolved item${i.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${i.open>0?`; ${i.open} still open`:""}.`})}catch{}let a=Po(!0);a.kind==="autoAudit"?(d({kind:"note",tone:"info",text:a.note}),Jt().then(i=>{i.kind==="forward-to-agent"&&i.prompt&&ce(i.prompt,{display:i.display,quietUser:!0})})):a.kind==="noDocs"?(d({kind:"note",tone:"info",text:a.note}),le(a.ghost),G(a.options),a.title&&Je(a.title)):a.kind==="actions"&&(d({kind:"note",tone:"info",text:a.note}),G(a.options),Je(a.title)),xo()},[])
|
|
270
|
+
`)}),bt(nt()),Ut.current=!1)}}catch{}try{let i=wf(e);i.archived>0&&d({kind:"note",tone:"ok",text:`\u2713 Tidied ${i.archived} resolved item${i.archived===1?"":"s"} from your tool feedback (now fixed in d360-writer) \u2192 moved to .d360-writer/tool-feedback-archived.md${i.open>0?`; ${i.open} still open`:""}.`})}catch{}let a=Po(!0);a.kind==="autoAudit"?(d({kind:"note",tone:"info",text:a.note}),Jt().then(i=>{i.kind==="forward-to-agent"&&i.prompt&&ce(i.prompt,{display:i.display,quietUser:!0})})):a.kind==="noDocs"?(d({kind:"note",tone:"info",text:a.note}),le(a.ghost),G(a.options),a.title&&Je(a.title)):a.kind==="actions"&&(d({kind:"note",tone:"info",text:a.note}),G(a.options),Je(a.title)),xo()},[]),$e(()=>{let l=setInterval(()=>{xo()},Sf);return()=>clearInterval(l)},[xo]),$e(()=>{if(R||Ge.length>0)return;let l=Po(!1);(l.kind==="actions"||l.kind==="noDocs")&&(G(l.options),Je(l.title??null))},[R,Ge,ve,Po]),$e(()=>{let l=null,a=null,i=()=>{l&&clearTimeout(l),l=setTimeout(()=>{l=null;let g=`${Pe.columns??80}x${Pe.rows??24}`;g!==ws.current&&(ws.current=g,Sl(u=>u+1),a&&clearTimeout(a),a=setTimeout(()=>{a=null,console.log("\x1B[?2026h\x1B[H\x1B[2J"+ki(ut.current,Me())+"\x1B[?2026l")},80))},400)};return Pe.on("resize",i),()=>{l&&clearTimeout(l),a&&clearTimeout(a),Pe.off("resize",i)}},[Pe,Me]);let je=Math.max(20,(Pe.columns??80)-1),ys=Xr(()=>xf(e,s),[e,s,ve]),To=(()=>{if(Cl)return{text:"\u23F3 Update in progress \u2014 please don\u2019t close this window\u2026",isSetup:!0};let l=ee(e);if(!l)return{text:"Press 1 to set up this repo, or /help\u2026",isSetup:!0};let a=At(e,(l.docsDir??uo).replace(/\/+$/,"")),i=(()=>{try{return jt(a)&&os(a).length>0}catch{return!1}})();try{let g=pe(e,s),u=Be(g.name);if(!(!!u&&!(_e(u)&&!u.refreshToken)))return{text:`Press 1 to sign in to Document360 (profile "${g.name}")\u2026`,isSetup:!0};if(!g.project.projectId)return{text:"Sign in to Document360 to pick your project\u2026",isSetup:!0};if(!g.project.workspaceId&&!i)return{text:"Press 1 to pick a workspace\u2026",isSetup:!0}}catch{}return i?{text:$f,isSetup:!1}:yo?{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}})(),Mt=Fa(A),ks=Mt.length>0&&!R,Ro=p!==null?ol(p,8,je):null,pn=ye?ye.paths.filter(l=>!ye.query||l.toLowerCase().includes(ye.query.toLowerCase())).slice(0,8):[],fn=be?be.sessions.filter(l=>{let a=be.query.toLowerCase();return!a||l.name.toLowerCase().includes(a)||l.firstPrompt.toLowerCase().includes(a)}).slice(0,8):[],me=Y((l,a)=>{ge.current?.close(),ge.current=sl({cwd:e,resume:l,profileName:a??s,allowProdWrites:dt.current}),l||(Se.current={uuid:null,firstPrompt:null,titleFired:!1},pt(null)),yt(0),kt(0)},[e,s]),bs=Y((l,a,i)=>{if(vf.test(l))try{let g=pe(e,s),u=typeof a.project_id=="string"&&a.project_id||g.project.projectId,h=Jn(a,i),y=[],v=Qn(i);l.endsWith("publish_article")&&v&&y.push(`Live: ${v}`),h&&u&&y.push(`Preview: ${Xn(g.connection.portalUrl,u,h,g.project.languageCode??"en")}`),y.length>0&&d({kind:"link",lines:y})}catch{}},[e,s,d]),ce=Y(async(l,a)=>{rn(!0),le(null),G([]),Je(null),ko(null),Co(null);let i=++it.current;a?.quietUser||d({kind:"user",text:a?.echoDisplay&&a.display?a.display:l});let g=Se.current;g.firstPrompt||(g.firstPrompt=a?.display??l),Ye.current=Date.now(),at(0),I(!0),ln.current.clear();let u="",h=!1,y=!1,v="",D={num:0,closed:!1,cueSeen:!1},_=null,K=()=>{_||(_=setTimeout(()=>{_=null,f(v.length>0?v:null)},60))},Q=()=>{_&&clearTimeout(_),_=null,f(null)},N=()=>{if(v.trim()){let x=Gr(v.trimEnd(),D);d({kind:"assistant",text:x})}v="",Q()};try{for await(let x of ge.current.send(l))if(x.type==="session"){if(!g.uuid){g.uuid=x.sessionId;let S=new Date().toISOString(),L=Jp(g.firstPrompt??"session");Qp({uuid:x.sessionId,name:L,renamed:!1,titled:!1,cwd:e,firstPrompt:g.firstPrompt??"",createdAt:S,updatedAt:S}),pt(L)}}else if(x.type==="text"){v+=x.delta,u+=x.delta;let S=rl(v);if(S>0){let L=v.slice(0,S).trimEnd();L&&d({kind:"assistant",text:Gr(L,D)}),v=v.slice(S)}K(),at(L=>L+x.delta.length)}else if(x.type==="tool"){h=!0;let S=zn(x.name,x.input);S&&(N(),d({kind:"tool",title:S.title,sep:S.sep,arg:S.arg}),ln.current.set(x.id,{name:x.name,input:x.input}))}else if(x.type==="article_diff"){let S=rt(x.oldContent,x.newContent,Me());S&&(N(),d({kind:"diff",added:S.added,removed:S.removed,lines:S.lines,hidden:S.hidden}))}else if(x.type==="tool_result"){x.isError&&/run \/login|not logged in|session expired|rejected the token/i.test(x.output)&&(cn.current=!0);let S=ln.current.get(x.id);if(S){ln.current.delete(x.id),N();let L=Kn(x.output,4,x.isError?void 0:S.name,S.input);d({kind:"tool-result",lines:L.lines,hidden:L.hidden,isError:x.isError}),x.isError||bs(S.name,S.input,x.output)}}else if(x.type==="result"){if(N(),yt(L=>L+x.outputTokens),kt(L=>L+x.costUsd),d({kind:"done",seconds:Math.round((Date.now()-Ye.current)/1e3),tokens:x.outputTokens,costUsd:x.costUsd,ok:x.ok}),!y&&!h&&!u.trim()&&!Nt.current&&d({kind:"note",tone:"warn",text:"The agent produced no output. This usually means the Claude model/runtime did not start \u2014 check sign-in and model with /doctor (on a subscription, make sure Claude Code is logged in on this machine)."}),x.ok&&/🛠|📣 Feedback for the d360-writer developers/.test(u))try{let L=gf(e);if(jt(L)){let Z=Jr(L,"utf8").trim();Z&&(Co(Z),d({kind:"note",tone:"info",text:"\u{1F6E0} Press c to copy this feedback \u2014 send it to the d360-writer team (Teams / Slack / email)."}))}}catch{}let S=x.ok?Ga(u,to.map(L=>L.name)):[];if(S.length>0?G(S):x.ok&&u.trim()&&nf(l,u,e).then(L=>{L&&it.current===i&&le(L)}).catch(()=>{}),g.uuid&&(Qr(g.uuid),!g.titleFired)){g.titleFired=!0;let L=g.uuid,Z=g.firstPrompt;Z&&il(Z,e).then(q=>{q&&(Xp(L,q),pt(q))}).catch(()=>{})}}else x.type==="error"&&(N(),y=!0,x.kind==="auth"&&(cn.current=!0),d({kind:"note",text:`agent error: ${x.message}`,tone:"error"}))}finally{I(!1),Q(),ae(x=>x+1),Se.current.uuid&&Ua(e,Se.current.uuid,ut.current),cn.current&&(cn.current=!1,un.current=a?.display??l,G(["/login"])),Nt.current&&(Nt.current=!1,Ze.current.length>0&&(d({kind:"note",tone:"info",text:`(${Ze.current.length} queued message(s) discarded)`}),Ze.current=[],ho([])),d({kind:"note",tone:"warn",text:"Interrupted. What do you want to do next?"}))}},[e,d,bs,Me]),mn=Y(async l=>{let a=ts(l),i=lo(e,"standard");Ye.current=Date.now(),at(0),I(!0);let g=new AbortController;ke.current=g,J({verb:"Publishing",total:a.length,done:0,active:[],rows:nn(a),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({kind:"note",tone:"info",text:`Publishing ${l.length} article${l.length===1?"":"s"} across ${a.length} partition${a.length===1?"":"s"} (\u2264${Kt} agents at once) on ${i.model}\u2026 (esc to stop)`});try{for await(let u of ao({cwd:e,partitions:a,promptFor:h=>Un(h.paths),concurrency:Kt,profileName:s,allowProdWrites:dt.current,model:i.model,signal:g.signal}))if(u.type==="partition_status")u.status==="running"?J(h=>h&&{...h,active:[...h.active,u.label],rows:Ne(h.rows,u.label,"active"),lastAt:Date.now()}):J(h=>h&&{...h,active:h.active.filter(y=>y!==u.label),done:h.done+1,rows:Ne(h.rows,u.label,u.status==="done"?"done":"failed"),lastAt:Date.now()});else if(u.type==="partition_event")J(h=>{if(!h)return h;let y={...h,lastAt:Date.now()};return u.event.type==="tool"?y.tools=h.tools+1:u.event.type==="text"&&(y.chars=h.chars+u.event.delta.length),y});else if(u.type==="run_done"){kt(D=>D+u.totalCostUsd),yt(D=>D+u.results.reduce((_,K)=>_+K.outputTokens,0));let h=u.aborted?"Stopped. ":"",y=t.kind==="api"?"api":"subscription";d({kind:"note",tone:u.aborted?"warn":u.ok?"ok":"warn",text:h+er(u.results,a,y).join(`
|
|
271
271
|
`)});let v=Zo(e,s);v&&d({kind:"note",tone:"info",text:v})}}catch(u){d({kind:"note",tone:"error",text:`Publish run failed: ${u.message}`})}finally{ke.current=null,J(null),I(!1),ae(u=>u+1)}},[e,s,d,t]),So=Y(async l=>{await ce(Qo(l),{display:`/publish ${l}`,quietUser:!0});try{let a=await Ln(e,s,l.replace(/\\/g,"/"));a.length>0&&(Je(`Related articles not yet published (${a.length}):`),G([`/publish --related ${l}`,...a.map(i=>`/publish ${i}`)]))}catch{}},[e,s,ce]),Do=Y(l=>{let a=Be(l);if(!a||_e(a)&&!a.refreshToken)return null;let i={...Et(a.idToken)??{},...Et(a.accessToken)??{}};return i.email??i.preferred_username??"signed in"},[]),jo=Y((l,a)=>{if(a){let i=ee(e);i&&(i.defaultProfile=l,al(i,e))}c(l),me(void 0,l),d({kind:"note",tone:"ok",text:`\u2713 Switched to profile "${l}"${a?" (saved as default)":" (this session only)"} \u2014 agent restarted.`}),Do(l)||(d({kind:"note",tone:"warn",text:`Profile "${l}" is not signed in \u2014 do you want to log in now? (press 1)`}),G(["/login"])),ae(i=>i+1)},[e,d,me,Do]),hn=Y((l,a,i)=>{xn(e,l,a,i.id,i.name),d({kind:"note",tone:"ok",text:`Switched to workspace "${i.name??i.id}" (agent restarted).`}),me(),Zr(e,l)||(d({kind:"note",tone:"ok",text:"\u2713 Connected. Configuration is done \u2014 one important step remains."}),d({kind:"note",tone:"warn",text:"\u26A0 Before I write the docs, hand the prompt below to your builder (your repo's coding agent). It gives me the architecture brief that makes the docs accurate:"}),d({kind:"note",tone:"info",text:Pt(Ct(e)).join(`
|
|
272
272
|
`)}),bt(nt()),Ut.current=Ee(e).status==="current"||Gt(e),d({kind:"note",tone:"info",text:`No separate builder agent? Then just ask me now: "write the docs for this repo" \u2014 I'll read the code directly.`}))},[e,d,me,bt]),gn=Y(async l=>{let a;try{a=await Ht(e,l)}catch{d({kind:"note",tone:"info",text:"Next: pick a workspace \u2014 run /workspace."}),G(["/workspace"]);return}if(a.workspaces.length===0){d({kind:"note",tone:"warn",text:"This project has no workspaces yet. Create one in Document360, then run /workspace."});return}let i=a.workspaces.filter(u=>(u.workspace_type??"").toLowerCase()!=="apidocumentation"),g=i.length>0?i:a.workspaces;if(g.length===1){let u=g[0],h=a.workspaces.length-g.length;d({kind:"note",tone:"ok",text:`Selected the "${u.name??u.id}" workspace${h>0?" (skipped the API-documentation workspace)":""}.`}),hn(a.profile,a.projectId,u);return}d({kind:"note",tone:"info",text:`Next: pick the workspace your articles publish to (${g.length} available).`}),G(["/workspace"])},[e,d,hn]),wn=Y((l,a)=>{_o(e,l,a.id,a.name),d({kind:"note",tone:"ok",text:`Project set to "${a.name??a.id}" (agent restarted).`}),me(),gn(l)},[e,d,me,gn]),xs=Y(async l=>{let a;try{a=pe(e,l)}catch{return}if(!a.project.workspaceId){if(a.project.projectId){if(!a.project.projectName)try{let{projects:i}=await tt(e,a.name),g=i.find(u=>u.id===a.project.projectId);g?.name&&yf(e,a.name,{projectName:g.name})}catch{}await gn(a.name);return}try{let{projects:i}=await tt(e,a.name);if(i.length===1){let g=i[0];d({kind:"note",tone:"ok",text:`Using your Document360 project "${g.name??g.id}".`}),wn(a.name,{id:g.id,name:g.name});return}if(i.length>1){let g=i.map(u=>({id:u.id,name:u.name??u.id,sub:u.sub_domain}));d({kind:"note",tone:"info",text:"Which Document360 project should these docs publish to?"}),Ke({cursor:0,current:-1,rows:g,profile:a.name,environment:a.connection.name});return}}catch{}d({kind:"note",tone:"info",text:"Next: pick the Document360 project \u2014 run /project."}),G(["/project"])}},[e,d,gn,wn]),yn=Y(()=>{let l=Ue.current[0];if(!l)return;d({kind:"note",tone:"info",text:`\u25CF ${l.title} (${l.path})`});for(let i of l.notes)d({kind:"note",tone:"warn",text:`\u26A0 ${i}`});l.overwritesLocalChanges&&d({kind:"note",tone:"warn",text:"\u26A0 This OVERWRITES local edits made since the last sync."});let a=rt(l.oldContent,l.newContent,Me());d(a?{kind:"diff",added:a.added,removed:a.removed,lines:a.lines,hidden:a.hidden}:{kind:"note",tone:"info",text:"Local file already matches the remote content \u2014 applying only advances the sync base."}),d({kind:"note",tone:"info",text:`Write ${l.path}? (y/n \u2014 anything else cancels)`})},[d,Me]),$s=Y(l=>{if(Ue.current.length===0)return!1;let a=l.trim().toLowerCase();if(a==="y"||a==="yes"){let i=Ue.current.shift();try{of({cwd:e,profileName:s},i),d({kind:"note",tone:"ok",text:`\u2713 Pulled ${i.path} (sync base advanced).`}),Ue.current.length===0&&G(g=>g.length>0?g:["/sync"])}catch(g){d({kind:"note",tone:"error",text:`Pull failed: ${g.message}`})}}else if(a==="n"||a==="no"){let i=Ue.current.shift();d({kind:"note",tone:"info",text:`Skipped ${i.path}.`})}else{let i=Ue.current.length;return Ue.current=[],d({kind:"note",tone:"info",text:`Pull cancelled (${i} article(s) left untouched).`}),!0}return yn(),!0},[e,s,yn,d]),vs=Y(l=>{let a=mo.current;if(!a)return!1;if(mo.current=null,le(null),it.current++,l.trim()!==a.repoName)return d({kind:"note",tone:"warn",text:"Reset cancelled \u2014 nothing deleted."}),!0;let{removed:i,failed:g}=Wr(e,a.targets);d({kind:"note",tone:g.length?"warn":"ok",text:`\u2713 Reset complete \u2014 removed ${i.length} item${i.length===1?"":"s"}. The repo is back to its original state.`});for(let u of g)d({kind:"note",tone:"error",text:` \u2717 ${u.path}: ${u.error}`});return a.hadDevhints&&(d({kind:"note",tone:"warn",text:In().join(`
|
|
273
273
|
`)}),bt(Fo())),d({kind:"note",tone:"info",text:`Clean slate \u2014 set up d360-writer again whenever you're ready:
|
|
@@ -289,7 +289,7 @@ ${v.skipped.map(D=>` - ${D.path} (${D.reason})`).join(`
|
|
|
289
289
|
`)}),bt(nt()),Ut.current=Ee(e).status==="current"||Gt(e);return}case"inbox":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(Ir(e)===0){d({kind:"note",tone:"info",text:"Inbox empty \u2014 no open messages from the builder. (They arrive via the builder's /devhints hand-off.)"});return}await ce(Nr(),{display:"/inbox",quietUser:!0});return}case"document":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let{publish:u,what:h}=$r(g);if(!h&&xr(e)===0){d({kind:"note",tone:"info",text:Cr});return}let y=`/document${h?` ${h}`:""}${u?" --publish":""}`;await ce(vr(h,u),{display:y,quietUser:!0});return}case"catch-up":{if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}if(!$o(l.trim()))return;let{publish:u}=_r(g),h=Dt(St(e));d({kind:"note",tone:"info",text:h?`Catching up on ${h} (+ checking Document360 for drift)\u2026`:"No local queue \u2014 checking for code changes and drift\u2026"}),await ce(Or({publish:u}),{display:`/catch-up${u?" --publish":""}`,quietUser:!0});return}case"update":{bo.current=!0,d({kind:"note",tone:"info",text:`Updating ${st}\u2026 (don\u2019t close this window)`}),sn(!0),(await Yn().finally(()=>sn(!1))).ok?(d({kind:"note",tone:"ok",text:"\u2713 Updated \u2014 run /exit, then relaunch to apply."}),G(h=>h.includes("/exit")?h:[...h,"/exit"])):d({kind:"note",tone:"warn",text:`Update failed \u2014 run manually: ${Gn}`});return}case"screenshot":{let u=Dr(g);if(u.mode==="list"){if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}d({kind:"note",tone:"info",text:Ar(jr(e,u.scope),u.scope).join(`
|
|
290
290
|
`)});return}if(u.mode==="single"){let N=await Bn(g);N.kind==="forward-to-agent"&&N.prompt&&await ce(N.prompt,{display:N.display,quietUser:!0});return}if(!ee(e)){d({kind:"note",tone:"error",text:"No d360-writer config here. Run /init first."});return}let h=u.mode==="scope"?u.scope:void 0,y=df(e,{scope:h}).map(N=>N.id);if(y.length===0){d({kind:"note",tone:"info",text:h?`No screenshot placeholders under ${h}.`:"No screenshot placeholders found in the docs."});return}let v=6,D=uf(y,3),_=lo(e,"standard");Ye.current=Date.now(),at(0),I(!0);let K=new AbortController;ke.current=K,J({verb:"Authoring",unit:"spec",total:D.length,done:0,active:[],rows:nn(D),tools:0,chars:0,lastAt:Date.now(),startedAt:Date.now()}),d({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 ${_.model}${_.forced?" (forced)":""}\u2026 (esc to stop)`});let Q=!1;try{for await(let N of ao({cwd:e,partitions:D,promptFor:pa,concurrency:v,profileName:s,allowProdWrites:dt.current,model:_.model,signal:K.signal}))if(N.type==="partition_status")N.status==="running"?J(x=>x&&{...x,active:[...x.active,N.label],rows:Ne(x.rows,N.label,"active"),lastAt:Date.now()}):J(x=>x&&{...x,active:x.active.filter(S=>S!==N.label),done:x.done+1,rows:Ne(x.rows,N.label,N.status==="done"?"done":"failed"),lastAt:Date.now()});else if(N.type==="partition_event")J(x=>{if(!x)return x;let S={...x,lastAt:Date.now()};return N.event.type==="tool"?S.tools=x.tools+1:N.event.type==="text"&&(S.chars=x.chars+N.event.delta.length),S});else if(N.type==="run_done"){kt(Z=>Z+N.totalCostUsd),yt(Z=>Z+N.results.reduce((q,z)=>q+z.outputTokens,0));let x=N.results.filter(Z=>Z.ok).length,S=N.aborted?"Stopped. ":"";Q=!N.aborted&&u.setup;let L=N.aborted?"":Q?" Refreshing the capture-setup checklist\u2026":" Next: /capture-setup, then d360-capture capture.";d({kind:"note",tone:N.aborted?"warn":N.ok?"ok":"warn",text:`${S}Authored specs \u2014 ${x}/${N.results.length} batches ok.${L}`})}}catch(N){d({kind:"note",tone:"error",text:`Spec authoring failed: ${N.message}`})}finally{ke.current=null,J(null),I(!1),ae(N=>N+1)}if(Q){let N=await en();N.kind==="forward-to-agent"&&N.prompt&&await ce(N.prompt,{display:N.display,quietUser:!0});let x=Er(e);x&&d({kind:"note",tone:"info",text:x.join(`
|
|
291
291
|
`)})}return}case"reset":{let u=Mr(e);if(u.length===0){d({kind:"note",tone:"info",text:"Nothing to reset \u2014 no d360-writer files found in this repo."});return}mo.current={repoName:on(e),targets:u,hadDevhints:jt(ul(e))},d({kind:"note",tone:"warn",text:Fr(e,u).join(`
|
|
292
|
-
`)}),le(on(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,yn,d,me,ce,mn,So,xs]),kn=Y(l=>{let a=(l??A).trim();if(w(""),an(null),lt(0),a.startsWith("/")&&(le(null),it.current++,Je(null),G(g=>Va(g,a))),!a||vs(a)||$s(a))return;fo.current.push(a);let i=Za(a,cs.current);a.startsWith("/")?(d({kind:"user",text:a}),Cs(i)):ce(i,{display:a})},[A,vs,$s,Cs,ce]),Ps=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Xa(l);if(Ja(a)){let i=Qa(++Tl.current,a);cs.current.set(i,a),P(i)}else P(a);return}P(l)},[P]),xt=Math.max(10,je-6),Ts=Xr(()=>so(b.text,xt),[b.text,xt]),Ao=Y(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),bn=Y(l=>k(a=>({...a,pos:tl(so(a.text,xt),a.pos,l)})),[xt]),Wt=Y(l=>k(a=>({...a,pos:nl(so(a.text,xt),a.pos,l)})),[xt]),Dl=["\x1B[H","\x1B[1~","\x1BOH"],jl=["\x1B[F","\x1B[4~","\x1BOF"],Rs=Y((l,a)=>a.leftArrow?(Ao(-1),!0):a.rightArrow?(Ao(1),!0):l&&Dl.includes(l)?(Wt("start"),!0):l&&jl.includes(l)?(Wt("end"),!0):a.ctrl&&l==="a"?(Wt("start"),!0):a.ctrl&&l==="e"?(Wt("end"),!0):!1,[Ao,Wt]);return Up((l,a)=>{if(a.ctrl&&l==="c"){ge.current?.close(),r();return}if(!H){if(R){if(a.escape){if(ke.current){ke.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ke.current.abort());return}Nt.current||(Nt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ge.current?.interrupt());return}if(a.return){let i=A.trim();if(!i)return;Ze.current.push(i),ho([...Ze.current]),w("");return}if(Rs(l,a))return;if(a.upArrow){bn(-1);return}if(a.downArrow){bn(1);return}if(a.backspace||a.delete){C();return}l&&!a.ctrl&&!a.meta&&Ps(l);return}if(Ve){if(a.upArrow){ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ze(i=>i&&{...i,cursor:Math.min(Re.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){ze(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Re[Ve.cursor];ze(null);let{lines:g,changed:u,effective:h}=Qt(e,i.value??"default");for(let y of g)d({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});u&&(gs(y=>y+1),ge.current?.setModel(h));return}if(l==="s"){let i=Re[Ve.cursor];ze(null),ge.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ze(null);return}return}if(De){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){ft(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return||l==="s"){let i=De.rows[De.cursor];ft(null),jo(i.name,a.return===!0);return}if(a.escape){ft(null);return}return}if(go){if(a.escape){Ot(null);return}if(a.leftArrow||a.tab&&a.shift){Ot(i=>i&&{tab:(i.tab-1+Te.length)%Te.length});return}if(a.rightArrow||a.tab){Ot(i=>i&&{tab:(i.tab+1)%Te.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Te.length){Ot({tab:Number(l)-1});return}return}if(Le){if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Le.rows.length){mt(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Le.rows[Le.cursor].name;if(mt(null),!ai(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${i}").`});let u=!1;try{let h=Be(i);u=!!h&&!(_e(h)&&!h.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${i}) and pick your project. (press 1)`}),G(["/login"]),ae(h=>h+1);return}if(a.escape){mt(null);return}return}if(ue){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ue.rows.length){ht(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=ue.rows[ue.cursor],{profile:g,projectId:u}=ue;ht(null),hn(g,u,i);return}if(a.escape){ht(null);return}return}if(we){if(a.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.rows.length){Ke(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=we.rows[we.cursor],{profile:g}=we;Ke(null),wn(g,i);return}if(a.escape){Ke(null);return}return}if(fe){if(a.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l===" "){wt(i=>i&&{...i,rows:i.rows.map((g,u)=>u===i.cursor?{...g,checked:!g.checked}:g)});return}if(a.return){let i=fe.rows.filter(g=>g.checked).map(g=>g.path);if(wt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}tr(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of i)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){wt(null);return}return}if(Xe){if(a.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Xe.rows.length){gt(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Xe.rows[Xe.cursor];gt(null),i.kind==="article"?So(i.paths[0]):mn(i.paths);return}if(a.escape){gt(null);return}return}if(ye){if(a.escape){Qe(null);return}if(a.upArrow){Qe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Qe(i=>i&&{...i,cursor:Math.min(Math.max(0,pn.length-1),i.cursor+1)});return}if(a.return){let i=pn[ye.cursor];if(i){Qe(null);try{d({kind:"preview",name:on(i),text:fl(Jr(At(e,i),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${i}: ${g.message}`})}}return}if(a.backspace||a.delete){Qe(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Qe(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(be){if(a.escape){et(null);return}if(a.upArrow){et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){et(i=>i&&{...i,cursor:Math.min(Math.max(0,fn.length-1),i.cursor+1)});return}if(a.return){let i=fn[be.cursor];if(i){et(null),me(i.uuid),Se.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},pt(i.name),Qr(i.uuid),ut.current=[];let g=Yr(e,i.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${i.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){et(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){et(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(a.tab&&!A&&ve){w(ve),le(null),it.current++;return}if(!A&&Ge.length>0&&l&&/^[1-9]$/.test(l)){let i=Ge[Number(l)-1];if(i){w(i);return}}if(!A&&(vo||yo)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=vo!=null;Ia(vo??yo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\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.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&i&&Co(null)});return}if(!Rs(l,a)){if(ks){if(a.upArrow){lt(i=>Math.max(0,i-1));return}if(a.downArrow){lt(i=>Math.min(Mt.length-1,i+1));return}if(a.tab){w("/"+(Mt[It]?.name??"")+" "),lt(0);return}if(a.return){let i=Mt[It];if(i){let g=A.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ha(i.usage)&&!g){w("/"+i.name+" "),lt(0);return}kn("/"+i.name+(g?" "+g:""));return}}}else{if(a.upArrow){if(A!==""&&ct===null){bn(-1);return}let i=fo.current;if(!i.length)return;let g=ct===null?i.length-1:Math.max(0,ct-1);an(g),w(i[g]??"");return}if(a.downArrow){if(A!==""&&ct===null){bn(1);return}let i=fo.current;if(ct===null)return;let g=ct+1;g>=i.length?(an(null),w("")):(an(g),w(i[g]??""));return}}if(a.return){kn();return}if(a.backspace||a.delete){C();return}if(a.escape){w(""),lt(0),le(null),G([]),Je(null);return}l&&!a.ctrl&&!a.meta&&Ps(l)}}}),xe(()=>{if(R||H)return;let l=Ze.current.shift();l!==void 0&&(ho([...Ze.current]),kn(l))},[R,H,kn]),B(te,{flexDirection:"column",width:je,children:[Ro!==null&&B(te,{marginTop:1,flexDirection:"column",children:[Ro.truncated&&j(T,{dimColor:!0,children:"\u2026"}),j(T,{children:Ro.text})]}),R&&(fs?j(Rf,{p:fs}):j(Pf,{startTime:Ye.current,chars:Pl})),j(te,{borderStyle:"round",borderColor:ys.prod?"yellow":M,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:A?Ts.map((l,a)=>{let i=b.text.slice(l.start,l.end),g=a===io(Ts,b.pos),u=Math.min(b.pos,l.end)-l.start;return B(T,{children:[j(T,{color:M,children:a===0?"> ":" "}),g?B(ns,{children:[i.slice(0,u),j(co,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${l.start}`)}):B(T,{children:[j(T,{color:M,children:"> "}),ve&&!R?B(ns,{children:[j(co,{ch:ve[0],dim:!0}),j(T,{color:"gray",children:ve.slice(1)}),j(T,{dimColor:!0,children:" (tab)"})]}):(To.isSetup||!vl)&&!R?B(ns,{children:[j(co,{ch:To.text[0],dim:!0}),j(T,{color:"gray",children:To.text.slice(1)})]}):j(co,{ch:" "})]})}),ps.length>0&&j(te,{flexDirection:"column",paddingX:1,children:ps.map((l,a)=>j(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),go?j(Ba,{tab:go.tab,width:je}):Ve?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Select model"}),j(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Re.map((l,a)=>B(T,{color:a===Ve.cursor?M:void 0,children:[a===Ve.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===Ve.current?" \u2714":""}`.padEnd(16),j(T,{color:"gray",children:l.desc})]},l.label)),j(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):De?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Switch connection profile"}),De.rows.map((l,a)=>B(T,{color:a===De.cursor?M:void 0,children:[a===De.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===De.current?" \u2714":""}`.padEnd(20),j(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Le?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Pick your Document360 environment"}),Le.rows.map((l,a)=>B(T,{color:a===Le.cursor?M:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),j(T,{color:"gray",children:l.apiUrl})]},l.name)),j(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ue?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Switch workspace"}),j(T,{dimColor:!0,children:`environment ${ue.environment} \xB7 project ${ue.projectName??`${ue.projectId.slice(0,8)}\u2026`}`}),ue.rows.map((l,a)=>B(T,{color:a===ue.cursor?M:void 0,children:[a===ue.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ue.current?" \u2714":""}`.padEnd(30),j(T,{color:"gray",children:l.type??""})]},l.id)),j(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):we?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Choose project"}),j(T,{dimColor:!0,children:`environment ${we.environment}`}),we.rows.map((l,a)=>B(T,{color:a===we.cursor?M:void 0,children:[a===we.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===we.current?" \u2714":""}`.padEnd(30),j(T,{color:"gray",children:l.sub??""})]},l.id)),j(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let a=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),i=fe.rows.slice(a,a+14),g=fe.rows.filter(u=>u.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),a>0?j(T,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,h)=>{let y=a+h;return B(T,{color:y===fe.cursor?M:void 0,children:[y===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,je-34)),j(T,{color:"gray",children:Mn(u)})]},u.path)}),a+14<fe.rows.length?j(T,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,j(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Xe?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Xe.rows.map((l,a)=>{let i=a===Xe.cursor,g=l.indent?" ":" ",u=`${a+1}.`.padEnd(3);return B(T,{color:i?M:void 0,bold:l.kind==="category"&&!i,children:[i?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,je-24)),l.note?j(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ye?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),pn.length===0?j(T,{color:"gray",children:"no articles match"}):pn.map((l,a)=>B(T,{color:a===ye.cursor?M:void 0,children:[a===ye.cursor?"\u276F ":" ",l]},l)),j(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):be?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:`Resume session${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),fn.length===0?j(T,{color:"gray",children:"no sessions match"}):fn.map((l,a)=>B(T,{color:a===be.cursor?M:void 0,children:[a===be.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(T,{color:a===be.cursor?M:"gray",children:l.firstPrompt.slice(0,Math.max(10,je-40))})]},l.uuid)),j(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ks?j(te,{flexDirection:"column",children:Mt.map((l,a)=>B(T,{color:a===It?M:void 0,children:[a===It?"\u276F ":" ",l.usage.padEnd(22)," ",j(T,{color:a===It?M:"gray",children:l.name==="model"&&wo?`${l.desc} (currently ${wo})`:l.desc})]},l.name))}):!R&&!A&&Ge.length>0?B(te,{flexDirection:"column",paddingX:1,children:[ds?j(T,{color:M,children:ds}):null,Ge.map((l,a)=>{let i=l.slice(0,Math.max(20,je-5)),g=je-i.length-7,u=g>=12?Wa(l).slice(0,g):"";return B(T,{children:[j(T,{color:M,children:a+1})," ",i,u?j(T,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),j(T,{dimColor:!0,children:`press 1-${Ge.length} to fill the command \xB7 esc dismiss`})]}):j(te,{paddingX:1,children:B(T,{color:"gray",children:[ys.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${wo??"model n/a"}${t.kind==="api"?hs>0?` \xB7 ${de(hs)}`:"":ms>0?` \xB7 ${He(ms)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Af}from"react/jsx-runtime";async function wl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=jf(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Df(Af(gl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
292
|
+
`)}),le(on(e));return}default:d({kind:"note",tone:"error",text:`Unknown command: /${i} \u2014 type /help.`})}},[e,r,s,yn,d,me,ce,mn,So,xs]),kn=Y(l=>{let a=(l??A).trim();if(w(""),an(null),lt(0),a.startsWith("/")&&(le(null),it.current++,Je(null),G(g=>Va(g,a))),!a||vs(a)||$s(a))return;fo.current.push(a);let i=Za(a,cs.current);a.startsWith("/")?(d({kind:"user",text:a}),Cs(i)):ce(i,{display:a})},[A,vs,$s,Cs,ce]),Ps=Y(l=>{if(l.length>1){if(l.includes("\x1B"))return;let a=Xa(l);if(Ja(a)){let i=Qa(++Tl.current,a);cs.current.set(i,a),P(i)}else P(a);return}P(l)},[P]),xt=Math.max(10,je-6),Ts=Xr(()=>so(b.text,xt),[b.text,xt]),Ao=Y(l=>k(a=>({...a,pos:Math.max(0,Math.min(a.text.length,a.pos+l))})),[]),bn=Y(l=>k(a=>({...a,pos:tl(so(a.text,xt),a.pos,l)})),[xt]),Wt=Y(l=>k(a=>({...a,pos:nl(so(a.text,xt),a.pos,l)})),[xt]),Dl=["\x1B[H","\x1B[1~","\x1BOH"],jl=["\x1B[F","\x1B[4~","\x1BOF"],Rs=Y((l,a)=>a.leftArrow?(Ao(-1),!0):a.rightArrow?(Ao(1),!0):l&&Dl.includes(l)?(Wt("start"),!0):l&&jl.includes(l)?(Wt("end"),!0):a.ctrl&&l==="a"?(Wt("start"),!0):a.ctrl&&l==="e"?(Wt("end"),!0):!1,[Ao,Wt]);return Up((l,a)=>{if(a.ctrl&&l==="c"){ge.current?.close(),r();return}if(!H){if(R){if(a.escape){if(ke.current){ke.current.signal.aborted||(d({kind:"note",tone:"warn",text:"\u238B Stopping the convert run (finishing in-flight articles)\u2026"}),ke.current.abort());return}Nt.current||(Nt.current=!0,d({kind:"note",tone:"warn",text:"\u238B Interrupting\u2026"}),ge.current?.interrupt());return}if(a.return){let i=A.trim();if(!i)return;Ze.current.push(i),ho([...Ze.current]),w("");return}if(Rs(l,a))return;if(a.upArrow){bn(-1);return}if(a.downArrow){bn(1);return}if(a.backspace||a.delete){C();return}l&&!a.ctrl&&!a.meta&&Ps(l);return}if(Ve){if(a.upArrow){ze(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ze(i=>i&&{...i,cursor:Math.min(Re.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Re.length){ze(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Re[Ve.cursor];ze(null);let{lines:g,changed:u,effective:h}=Qt(e,i.value??"default");for(let y of g)d({kind:"note",tone:y.startsWith("\u26A0")?"warn":y.startsWith("\u2713")?"ok":"info",text:y});u&&(gs(y=>y+1),ge.current?.setModel(h));return}if(l==="s"){let i=Re[Ve.cursor];ze(null),ge.current?.setModel(i.value??void 0),d({kind:"note",tone:"ok",text:`\u2713 Using ${i.label} for this session only (your saved default is unchanged).`});return}if(a.escape){ze(null);return}return}if(De){if(a.upArrow){ft(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ft(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=De.rows.length){ft(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return||l==="s"){let i=De.rows[De.cursor];ft(null),jo(i.name,a.return===!0);return}if(a.escape){ft(null);return}return}if(go){if(a.escape){Ot(null);return}if(a.leftArrow||a.tab&&a.shift){Ot(i=>i&&{tab:(i.tab-1+xe.length)%xe.length});return}if(a.rightArrow||a.tab){Ot(i=>i&&{tab:(i.tab+1)%xe.length});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=xe.length){Ot({tab:Number(l)-1});return}return}if(Le){if(a.upArrow){mt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){mt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Le.rows.length){mt(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Le.rows[Le.cursor].name;if(mt(null),!ai(e,i).created){d({kind:"note",tone:"error",text:"Could not scaffold \u2014 .d360-writer.json already exists."});return}d({kind:"note",tone:"ok",text:`\u2713 Wrote .d360-writer.json (environment "${i}").`});let u=!1;try{let h=Be(i);u=!!h&&!(_e(h)&&!h.refreshToken)}catch{u=!1}d({kind:"note",tone:"info",text:u?`Next: sign in to ${i} and pick your project \u2014 you're already signed in here, so it'll be quick. (press 1)`:`Next: sign in to Document360 (${i}) and pick your project. (press 1)`}),G(["/login"]),ae(h=>h+1);return}if(a.escape){mt(null);return}return}if(ue){if(a.upArrow){ht(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){ht(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=ue.rows.length){ht(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=ue.rows[ue.cursor],{profile:g,projectId:u}=ue;ht(null),hn(g,u,i);return}if(a.escape){ht(null);return}return}if(we){if(a.upArrow){Ke(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Ke(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=we.rows.length){Ke(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=we.rows[we.cursor],{profile:g}=we;Ke(null),wn(g,i);return}if(a.escape){Ke(null);return}return}if(fe){if(a.upArrow){wt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){wt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l===" "){wt(i=>i&&{...i,rows:i.rows.map((g,u)=>u===i.cursor?{...g,checked:!g.checked}:g)});return}if(a.return){let i=fe.rows.filter(g=>g.checked).map(g=>g.path);if(wt(null),i.length===0){d({kind:"note",tone:"info",text:"Nothing selected \u2014 scope unchanged."});return}tr(e,i),d({kind:"note",tone:"ok",text:`\u2713 Scoped to ${i.length} folder(s) \u2014 written to .d360-writer.json`});for(let g of i)d({kind:"note",tone:"info",text:` ${g}`});d({kind:"note",tone:"info",text:"Next: ask me to analyze these folders and propose a docs structure."});return}if(a.escape){wt(null);return}return}if(Xe){if(a.upArrow){gt(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){gt(i=>i&&{...i,cursor:Math.min(i.rows.length-1,i.cursor+1)});return}if(l&&/^[1-9]$/.test(l)&&Number(l)<=Xe.rows.length){gt(i=>i&&{...i,cursor:Number(l)-1});return}if(a.return){let i=Xe.rows[Xe.cursor];gt(null),i.kind==="article"?So(i.paths[0]):mn(i.paths);return}if(a.escape){gt(null);return}return}if(ye){if(a.escape){Qe(null);return}if(a.upArrow){Qe(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){Qe(i=>i&&{...i,cursor:Math.min(Math.max(0,pn.length-1),i.cursor+1)});return}if(a.return){let i=pn[ye.cursor];if(i){Qe(null);try{d({kind:"preview",name:on(i),text:fl(Jr(At(e,i),"utf8"))})}catch(g){d({kind:"note",tone:"error",text:`Could not read ${i}: ${g.message}`})}}return}if(a.backspace||a.delete){Qe(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){Qe(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(be){if(a.escape){et(null);return}if(a.upArrow){et(i=>i&&{...i,cursor:Math.max(0,i.cursor-1)});return}if(a.downArrow){et(i=>i&&{...i,cursor:Math.min(Math.max(0,fn.length-1),i.cursor+1)});return}if(a.return){let i=fn[be.cursor];if(i){et(null),me(i.uuid),Se.current={uuid:i.uuid,firstPrompt:i.firstPrompt,titleFired:!0},pt(i.name),Qr(i.uuid),ut.current=[];let g=Yr(e,i.uuid);for(let u of g)d(u);d({kind:"note",tone:"ok",text:g.length?`Resumed "${i.name}" \u2014 restored ${g.length} message(s); continue where you left off.`:`Resumed "${i.name}" (agent memory reconnected; no saved transcript to replay).`})}return}if(a.backspace||a.delete){et(i=>i&&{...i,query:i.query.slice(0,-1),cursor:0});return}if(l&&!a.ctrl&&!a.meta&&l.length===1){et(i=>i&&{...i,query:i.query+l,cursor:0});return}return}if(a.tab&&!A&&Ce){w(Ce),le(null),it.current++;return}if(!A&&Ge.length>0&&l&&/^[1-9]$/.test(l)){let i=Ge[Number(l)-1];if(i){w(i);return}}if(!A&&(vo||yo)&&l==="c"&&!a.ctrl&&!a.meta&&!a.return&&!a.tab){let i=vo!=null;Ia(vo??yo).then(u=>{d({kind:"note",tone:u?"ok":"warn",text:u?i?"\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.":i?"Couldn't reach your clipboard \u2014 select the feedback above and copy it manually.":"Couldn't reach your clipboard \u2014 select the prompt above and copy it manually."}),u&&i&&Co(null)});return}if(!Rs(l,a)){if(ks){if(a.upArrow){lt(i=>Math.max(0,i-1));return}if(a.downArrow){lt(i=>Math.min(Mt.length-1,i+1));return}if(a.tab){w("/"+(Mt[It]?.name??"")+" "),lt(0);return}if(a.return){let i=Mt[It];if(i){let g=A.trim().slice(1).split(/\s+/).slice(1).join(" ");if(Ha(i.usage)&&!g){w("/"+i.name+" "),lt(0);return}kn("/"+i.name+(g?" "+g:""));return}}}else{if(a.upArrow){if(A!==""&&ct===null){bn(-1);return}let i=fo.current;if(!i.length)return;let g=ct===null?i.length-1:Math.max(0,ct-1);an(g),w(i[g]??"");return}if(a.downArrow){if(A!==""&&ct===null){bn(1);return}let i=fo.current;if(ct===null)return;let g=ct+1;g>=i.length?(an(null),w("")):(an(g),w(i[g]??""));return}}if(a.return){kn();return}if(a.backspace||a.delete){C();return}if(a.escape){w(""),lt(0),le(null),G([]),Je(null);return}l&&!a.ctrl&&!a.meta&&Ps(l)}}}),$e(()=>{if(R||H)return;let l=Ze.current.shift();l!==void 0&&(ho([...Ze.current]),kn(l))},[R,H,kn]),B(te,{flexDirection:"column",width:je,children:[Ro!==null&&B(te,{marginTop:1,flexDirection:"column",children:[Ro.truncated&&j(T,{dimColor:!0,children:"\u2026"}),j(T,{children:Ro.text})]}),R&&(fs?j(Rf,{p:fs}):j(Pf,{startTime:Ye.current,chars:Pl})),j(te,{borderStyle:"round",borderColor:ys.prod?"yellow":M,borderTop:!0,borderBottom:!0,borderLeft:!1,borderRight:!1,marginTop:1,flexDirection:"column",children:A?Ts.map((l,a)=>{let i=b.text.slice(l.start,l.end),g=a===io(Ts,b.pos),u=Math.min(b.pos,l.end)-l.start;return B(T,{children:[j(T,{color:M,children:a===0?"> ":" "}),g?B(ns,{children:[i.slice(0,u),j(co,{ch:i[u]??" "}),i.slice(u+1)]}):i||" "]},`${a}-${l.start}`)}):B(T,{children:[j(T,{color:M,children:"> "}),Ce&&!R?B(ns,{children:[j(co,{ch:Ce[0],dim:!0}),j(T,{color:"gray",children:Ce.slice(1)}),j(T,{dimColor:!0,children:" (tab)"})]}):(To.isSetup||!vl)&&!R?B(ns,{children:[j(co,{ch:To.text[0],dim:!0}),j(T,{color:"gray",children:To.text.slice(1)})]}):j(co,{ch:" "})]})}),ps.length>0&&j(te,{flexDirection:"column",paddingX:1,children:ps.map((l,a)=>j(T,{color:"gray",children:`\u29D7 queued: ${l}`},`${a}-${l.slice(0,24)}`))}),go?j(Ba,{tab:go.tab,width:je}):Ve?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Select model"}),j(T,{color:"gray",children:"Your pick becomes your personal default for new sessions (team .d360-writer.json still wins)."}),Re.map((l,a)=>B(T,{color:a===Ve.cursor?M:void 0,children:[a===Ve.cursor?"\u276F ":" ",`${a+1}. ${l.label}${a===Ve.current?" \u2714":""}`.padEnd(16),j(T,{color:"gray",children:l.desc})]},l.label)),j(T,{dimColor:!0,children:"enter set as default \xB7 s this session only \xB7 esc cancel"})]}):De?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Switch connection profile"}),De.rows.map((l,a)=>B(T,{color:a===De.cursor?M:void 0,children:[a===De.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===De.current?" \u2714":""}`.padEnd(20),j(T,{color:"gray",children:`${l.env} \xB7 ${l.who??"not signed in"}`}),l.prod?j(T,{color:"yellow",bold:!0,children:" \u26A0 PRODUCTION"}):null]},l.name)),j(T,{dimColor:!0,children:"enter switch (saved as default) \xB7 s this session only \xB7 esc cancel"})]}):Le?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Pick your Document360 environment"}),Le.rows.map((l,a)=>B(T,{color:a===Le.cursor?M:void 0,children:[a===Le.cursor?"\u276F ":" ",`${a+1}. ${l.name}`.padEnd(16),j(T,{color:"gray",children:l.apiUrl})]},l.name)),j(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):ue?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Switch workspace"}),j(T,{dimColor:!0,children:`environment ${ue.environment} \xB7 project ${ue.projectName??`${ue.projectId.slice(0,8)}\u2026`}`}),ue.rows.map((l,a)=>B(T,{color:a===ue.cursor?M:void 0,children:[a===ue.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===ue.current?" \u2714":""}`.padEnd(30),j(T,{color:"gray",children:l.type??""})]},l.id)),j(T,{dimColor:!0,children:"enter switch \xB7 esc cancel"})]}):we?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Choose project"}),j(T,{dimColor:!0,children:`environment ${we.environment}`}),we.rows.map((l,a)=>B(T,{color:a===we.cursor?M:void 0,children:[a===we.cursor?"\u276F ":" ",`${a+1}. ${l.name}${a===we.current?" \u2714":""}`.padEnd(30),j(T,{color:"gray",children:l.sub??""})]},l.id)),j(T,{dimColor:!0,children:"enter select \xB7 esc cancel"})]}):fe?(()=>{let a=Math.min(Math.max(0,fe.cursor-Math.floor(7)),Math.max(0,fe.rows.length-14)),i=fe.rows.slice(a,a+14),g=fe.rows.filter(u=>u.checked).length;return B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:`Which folders back the user docs? (${g} selected of ${fe.rows.length})`}),a>0?j(T,{dimColor:!0,children:` \u2191 ${a} more`}):null,i.map((u,h)=>{let y=a+h;return B(T,{color:y===fe.cursor?M:void 0,children:[y===fe.cursor?"\u276F ":" ",u.checked?"\u25C9 ":"\u25CB ",u.path.padEnd(Math.min(48,je-34)),j(T,{color:"gray",children:Mn(u)})]},u.path)}),a+14<fe.rows.length?j(T,{dimColor:!0,children:` \u2193 ${fe.rows.length-a-14} more`}):null,j(T,{dimColor:!0,children:"space toggle \xB7 enter save \xB7 esc cancel"})]})})():Xe?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:"Publish to Document360 \u2014 pick a category (whole) or an article:"}),Xe.rows.map((l,a)=>{let i=a===Xe.cursor,g=l.indent?" ":" ",u=`${a+1}.`.padEnd(3);return B(T,{color:i?M:void 0,bold:l.kind==="category"&&!i,children:[i?"\u276F ":" ",`${g}${u} ${l.label}`.padEnd(Math.min(56,je-24)),l.note?j(T,{color:"gray",children:l.note}):null]},`${l.kind}:${l.paths.join(",")}`)}),j(T,{dimColor:!0,children:"\u2191\u2193 move \xB7 1-9 jump \xB7 enter publish (draft) \xB7 esc cancel"})]}):ye?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:`Preview article${ye.query?` \u2014 filter: ${ye.query}`:" (type to filter)"}`}),pn.length===0?j(T,{color:"gray",children:"no articles match"}):pn.map((l,a)=>B(T,{color:a===ye.cursor?M:void 0,children:[a===ye.cursor?"\u276F ":" ",l]},l)),j(T,{dimColor:!0,children:"enter preview \xB7 esc cancel"})]}):be?B(te,{flexDirection:"column",paddingX:1,children:[j(T,{color:M,bold:!0,children:`Resume session${be.query?` \u2014 filter: ${be.query}`:" (type to filter)"}`}),fn.length===0?j(T,{color:"gray",children:"no sessions match"}):fn.map((l,a)=>B(T,{color:a===be.cursor?M:void 0,children:[a===be.cursor?"\u276F ":" ",l.name.slice(0,28).padEnd(30),j(T,{color:a===be.cursor?M:"gray",children:l.firstPrompt.slice(0,Math.max(10,je-40))})]},l.uuid)),j(T,{dimColor:!0,children:"enter resume \xB7 esc cancel"})]}):ks?B(te,{flexDirection:"column",children:[Mt.map((l,a)=>B(T,{color:a===It?M:void 0,children:[a===It?"\u276F ":" ",l.usage.padEnd(22)," ",j(T,{color:a===It?M:"gray",children:l.name==="model"&&wo?`${l.desc} (currently ${wo})`:l.desc})]},l.name)),j(T,{dimColor:!0,children:"\u2191\u2193 choose \xB7 enter run \xB7 tab complete \xB7 esc dismiss"})]}):!R&&!A&&Ge.length>0?B(te,{flexDirection:"column",paddingX:1,children:[ds?j(T,{color:M,children:ds}):null,Ge.map((l,a)=>{let i=l.slice(0,Math.max(20,je-5)),g=je-i.length-7,u=g>=12?Wa(l).slice(0,g):"";return B(T,{children:[j(T,{color:M,children:a+1})," ",i,u?j(T,{dimColor:!0,children:` \u2014 ${u}`}):null]},l)}),j(T,{dimColor:!0,children:`press 1-${Ge.length} to fill the command \xB7 esc dismiss`})]}):j(te,{paddingX:1,children:B(T,{color:"gray",children:[ys.prod?"\u26A0 PRODUCTION \xB7 ":"",`/help \xB7 ${wo??"model n/a"}${t.kind==="api"?hs>0?` \xB7 ${de(hs)}`:"":ms>0?` \xB7 ${He(ms)}`:""} \xB7 \u2191 history \xB7 ctrl+c exit`]})})]})}W();import{jsx as Af}from"react/jsx-runtime";async function wl(e=process.cwd(),t="auto",n,o="0.0.0"){let r=jf(t);r.kind==="none"&&(console.error(""),console.error($("ANTHROPIC_API_KEY is not set (required for --auth api).")),console.error(`Get a key at ${O("https://console.anthropic.com/settings/keys")}`),console.error(`Or use your Claude subscription instead: ${O("d360-writer --auth subscription")}`),process.exit(2));let{waitUntilExit:s}=Df(Af(gl,{cwd:e,auth:r,profileName:n,version:o}));await s(),process.stdout.write(`
|
|
293
293
|
`),process.exit(0)}W();import{writeCrashLog as yl,isBenignTransportError as Ef}from"document360-engine";var kl=!1;function is(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}function bl(e){if(kl)return;kl=!0;let t=(n,o)=>{if(Ef(o)){yl({kind:n,level:"transport",message:is(o),stack:o instanceof Error?o.stack:void 0,detail:e});return}let r=yl({kind:n,level:"fatal",message:is(o),stack:o instanceof Error?o.stack:void 0,detail:e});process.stderr.write(`
|
|
294
294
|
`+$(`\u2717 d360-writer crashed: ${is(o)}`)+`
|
|
295
295
|
`),r&&process.stderr.write(m(` Crash details: ${r}`)+`
|
package/package.json
CHANGED