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