@lovek4d/kickflip 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTEXT.md +151 -115
- package/README.md +23 -14
- package/SKILL.md +37 -37
- package/bin/doctor.mjs +4 -4
- package/bin/install.mjs +3 -3
- package/bin/kickflip.mjs +34 -26
- package/bin/wait-events.mjs +2 -2
- package/board/arch-review.mjs +1 -1
- package/board/auto-review.mjs +2 -0
- package/board/bin/board.mjs +186 -69
- package/board/domain.mjs +8 -5
- package/board/finish.mjs +3 -0
- package/board/headless.mjs +3 -0
- package/board/on-host.mjs +1 -1
- package/board/permissions.mjs +2 -0
- package/board/public/app-arch.js +2 -2
- package/board/public/app-asks.js +57 -38
- package/board/public/app-banner.js +2 -2
- package/board/public/app-cards.js +156 -72
- package/board/public/app-core.js +2 -4
- package/board/public/app-header.js +12 -5
- package/board/public/app-lanes.js +201 -47
- package/board/public/app-needs.js +2 -1
- package/board/public/app-snapshot.js +2 -2
- package/board/public/app-threads.js +11 -14
- package/board/public/app.html +2 -1
- package/board/public/app.js +53 -83
- package/board/public/attach.js +39 -3
- package/board/public/dialogs.js +59 -14
- package/board/public/hub-kit.js +9 -6
- package/board/public/hub.css +5 -18
- package/board/public/linear-key.js +6 -4
- package/board/public/log.html +48 -0
- package/board/public/prompts.js +9 -8
- package/board/public/prototype-kit.js +6 -6
- package/board/public/prototype-switcher.js +13 -5
- package/board/public/prototype.html +1 -0
- package/board/public/router.js +8 -7
- package/board/public/rules-editor.js +3 -4
- package/board/public/shell.js +20 -6
- package/board/public/sidebar.css +21 -1
- package/board/public/sidebar.js +64 -31
- package/board/public/style.css +155 -62
- package/board/public/toasts.js +2 -2
- package/board/public/ui-cards.js +176 -71
- package/board/public/ui-enums.js +5 -4
- package/board/public/ui-header.js +10 -10
- package/board/public/ui-hub.js +4 -4
- package/board/public/ui-markdown.js +1 -1
- package/board/public/ui-order.js +9 -6
- package/board/public/ui-page-header.js +10 -7
- package/board/public/ui-patch.js +53 -0
- package/board/public/ui-phase-bars.js +17 -0
- package/board/public/ui-prompts.js +8 -8
- package/board/public/ui-questions.js +26 -23
- package/board/public/ui-sidebar.js +46 -22
- package/board/public/ui-snapshot.js +20 -9
- package/board/public/ui-threads.js +17 -11
- package/board/public/ui.js +80 -12
- package/board/public/view-frame.js +1 -1
- package/board/public/view-hub-settings.js +25 -18
- package/board/public/view-hub.js +53 -12
- package/board/public/view-notes.js +1 -1
- package/board/public/view-questions.js +101 -50
- package/board/public/view-settings.js +167 -49
- package/board/review.mjs +1 -1
- package/board/server.mjs +18 -12
- package/board/store.mjs +13 -12
- package/board/tickets.mjs +3 -3
- package/board/worktree.mjs +20 -14
- package/docs/hub-session.md +4 -4
- package/hooks-plugin/hooks/codex-share-auto.mjs +1 -1
- package/hooks-plugin/hooks/watcher-stop.mjs +2 -2
- package/hub/board-repo.mjs +1 -1
- package/hub/boards.mjs +4 -4
- package/hub/close-board.mjs +1 -1
- package/hub/github.mjs +4 -4
- package/hub/home.mjs +1 -1
- package/hub/hub.mjs +12 -12
- package/hub/incoming.mjs +2 -0
- package/hub/linear.mjs +2 -2
- package/hub/live.mjs +2 -2
- package/hub/new-board.mjs +2 -2
- package/hub/permission-denied-hook.mjs +2 -0
- package/hub/pr-report.mjs +3 -1
- package/hub/presence.mjs +1 -1
- package/hub/prompts.mjs +1 -1
- package/hub/push.mjs +2 -2
- package/hub/readiness.mjs +2 -2
- package/hub/repos.mjs +3 -3
- package/hub/restart-board.mjs +1 -1
- package/hub/schedule.mjs +1 -1
- package/hub/sessions.mjs +2 -2
- package/hub/sw.js +1 -1
- package/hub/try.mjs +8 -4
- package/hub/usage.mjs +3 -3
- package/hub/views.mjs +1 -1
- package/package.json +5 -1
- package/shared/card-prs.mjs +1 -0
- package/shared/colors.css +5 -4
- package/shared/fake-gh.mjs +59 -8
- package/shared/repos.mjs +1 -1
- package/shared/usage-gate.mjs +1 -1
- package/board/public/view-polling.js +0 -87
package/hub/readiness.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var T=Object.defineProperty;var
|
|
2
|
-
`,{mode:384}),f.renameSync(a,e),n}
|
|
1
|
+
var T=Object.defineProperty;var i=(t,r)=>T(t,"name",{value:r,configurable:!0});import f from"node:fs";import m from"node:os";import y from"node:path";import{execFile as N}from"node:child_process";import{githubLogin as P}from"./pr-report.mjs";import{codexStatusReader as w}from"../shared/codex.mjs";import{linearStatus as R}from"./linear.mjs";import{readSettings as O,subscriptions as C}from"./push.mjs";import{tailscaleState as I,tailscaleInstallHint as L}from"../bin/install.mjs";const x=[["github","GitHub","GitHub polling and PR reports wait on this."],["codex","Codex","Codex implementing and reviewing wait on this; Codex share stays Off."],["linear","Linear",null],["slack","Slack","Reviewer DMs and digests wait on this."],["tailscale","Tailscale","Try builds wait on this."],["notifications","Notifications","Pushes wait on this."]],k=i(t=>y.join(t,".claude","kickflip","integrations.json"),"reportFile");function F(t=m.homedir()){try{return JSON.parse(f.readFileSync(k(t),"utf8")).slack||null}catch{return null}}i(F,"readSlackReport");function Q(t,{home:r=m.homedir(),now:s=new Date,route:d=null,title:o="Board"}={}){const e=k(r),n={ready:t,at:s.toISOString(),route:d,title:o};f.mkdirSync(y.dirname(e),{recursive:!0});const a=`${e}.${process.pid}.tmp`;return f.writeFileSync(a,JSON.stringify({slack:n},null,2)+`
|
|
2
|
+
`,{mode:384}),f.renameSync(a,e),n}i(Q,"reportSlack");const H=i((t,r)=>{const s=Math.floor((r-Date.parse(t))/6e4);return s<1?"just now":s<60?`${s} min ago`:s<1440?`${Math.floor(s/60)} h ago`:`${Math.floor(s/1440)} days ago`},"age"),u=i((t,r,s)=>({settings:t,label:`Hub settings \u203A ${r}`,text:s}),"settingsFix");function $(t,{now:r=Date.now(),platform:s=process.platform}={}){const d=i((o,e)=>{switch(o){case"github":return e?{ready:!0,detail:`gh logged in as ${e}`}:{ready:!1,missing:"gh isn't logged in on the host",fix:{command:"gh auth login"}};case"codex":return e.usable?{ready:!0,detail:"Installed and logged in"}:{ready:!1,missing:e.words,fix:{command:e.fix}};case"linear":return e.set?e.refused?{ready:!1,missing:"Linear refused the key",fix:u("linear","Linear","Paste a new one in")}:{ready:!0,detail:`Key set \xB7 ${e.workspace} workspace`}:{ready:!1,missing:"No Linear key set",fix:u("linear","Linear","Add one in")};case"slack":{const n=e?`${e.title}\u2019s session reported ${e.ready?"a":"no"} Slack connector, ${H(e.at,r)}`:"No board session has reported yet";return e?.ready?{ready:!0,detail:n}:{ready:!1,missing:n,fix:{text:"Add Slack to Claude\u2019s connectors. The next board session to start reports it."}}}case"tailscale":{let n,a;return e.installed?e.signedIn?e.pointsAtHub?e.operatorChecked&&e.operator!==e.username&&(n=`Tailscale operator is ${e.operator||"none"} (expected ${e.username})`,a="sudo tailscale set --operator=$USER"):(n="Tailscale / is not serving the hub",a="kickflip doctor --fix"):(n="Tailscale isn't signed in",a="tailscale up"):(n="Tailscale isn't installed on the host",a=L(s)),n?{ready:!1,missing:n,fix:{command:a}}:{ready:!0,detail:`Serving ${e.dns}${e.operatorChecked?" \xB7 operator "+e.operator:""}`}}case"notifications":return e.on&&e.devices?{ready:!0,detail:`Pushes on \xB7 ${e.devices} device${e.devices===1?"":"s"}`}:{ready:!1,missing:e.on?"No device has turned on notifications":"Pushes are off",fix:u("notifications","Notifications","Turn on notifications in")}}},"row");return x.filter(([o])=>Object.hasOwn(t,o)).map(([o,e,n])=>({id:o,name:e,...d(o,t[o]),waits:n}))}i($,"readinessRows");const j=i(t=>(r,s)=>new Promise(d=>{N(r,s,{env:t,timeout:3e3},(o,e)=>d({status:o?1:0,stdout:e}))}),"asyncRun");function D({home:t=m.homedir(),env:r=process.env,now:s=Date.now,cacheMs:d=6e4,probes:o={}}={}){const e=w({home:t,env:r,now:s,cacheMs:d}),n={github:i(()=>P({env:r}).catch(()=>null),"github"),codex:e,linear:i(()=>R(t),"linear"),slack:i(()=>F(t),"slack"),tailscale:i(()=>I({run:j(r),port:Number(r.KICKFLIP_HUB_PORT||4500)}),"tailscale"),notifications:i(()=>({on:O(t).notifications.on,devices:C(t).length}),"notifications"),...o},a=new Map;async function g(l,c){if(!["github","tailscale"].includes(l))return n[l]({fresh:c});const p=a.get(l);if(!c&&p&&s()-p.at<d)return p.value;const h=Promise.resolve().then(()=>n[l]());return a.set(l,{at:s(),value:h}),h}i(g,"check");const b=i(async({fresh:l=!1}={})=>$(Object.fromEntries(await Promise.all(x.map(async([c])=>[c,await g(c,l)]))),{now:s()}),"rows");async function S(l){const[c]=$({[l]:await g(l,!1)},{now:s()});return c.ready||!c.waits?null:c.waits.replace("this",`${c.name}: ${c.missing.replace(/\.$/,"")}`)}return i(S,"waiting"),{rows:b,waiting:S}}i(D,"readinessReader");const A=w(),V=D({probes:{codex:A}});export{A as readCodex,F as readSlackReport,V as readiness,D as readinessReader,$ as readinessRows,Q as reportSlack};
|
package/hub/repos.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).map(
|
|
3
|
-
`))?`git's github.com login can't see ${e}; run gh auth setup-git`:`run git -C ${r} fetch origin to see the whole error`;return{error:
|
|
1
|
+
var Y=Object.defineProperty;var i=(t,e)=>Y(t,"name",{value:e,configurable:!0});import v from"node:fs";import h from"node:path";import{spawn as Z}from"node:child_process";import{reposDir as A}from"../shared/repos.mjs";import{withFileLock as tt}from"./locks.mjs";import{storedPath as T}from"../bin/install.mjs";const w=i((t,e=400)=>{throw Object.assign(new Error(t),{status:e})},"refuse");function S(t){return(typeof t!="string"||t.length>140||!/^[a-z\d](?:[a-z\d-]{0,37}[a-z\d])?\/[a-z\d_.-]{1,100}$/i.test(t)||[".","..",".git"].includes(t.split("/")[1].toLowerCase()))&&w("Repo must be owner/name on GitHub."),t}i(S,"validateGithub");function E(t){return(typeof t!="string"||!t||t.length>255||t==="@"||t.startsWith("-")||/[\s\x00-\x1f\x7f~^:?*\[\\]/.test(t)||t.includes("..")||t.includes("@{")||t.split("/").some(e=>!e||e.startsWith(".")||e.endsWith(".")||e.endsWith(".lock")))&&w("Choose a valid branch name."),t}i(E,"validateBranch");const C=i((t,e)=>{try{return t(e),!0}catch{return!1}},"valid");function et(t){const e=/^(?:git@github\.com:|https:\/\/github\.com\/|ssh:\/\/git@github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(t.trim());return e?W(e[1]):null}i(et,"githubFromOrigin");const G=/^[a-z\d](?:[a-z\d-]*[a-z\d])?(?:\.[a-z\d](?:[a-z\d-]*[a-z\d])?)+$/i,I=/^[\w~][\w.~-]{0,99}$|^\.[\w~-][\w.~-]{0,98}$/;function O(t){if(typeof t!="string")return null;const e=t.trim().replace(/\/+$/,""),s=/^https:\/\/([^/@\s?#]+?)(?::\d{1,5})?\/([^\s?#]+)$/i.exec(e)||/^ssh:\/\/(?:[^@/:\s]+@)?([^/@:\s?#]+)(?::\d{1,5})?\/([^\s?#]+)$/i.exec(e)||/^[^@/:\s]+@([^/@:\s?#]+):([^\s?#]+)$/.exec(e);if(!s||e.length>400||!G.test(s[1])||/^(?:www\.)?github\.com$/i.test(s[1]))return null;const r=s[2].replace(/^\/+/,"").replace(/\.git$/i,"").split("/");return r.length>10||!r.every(o=>I.test(o)&&o!=="..")?null:{remote:e,host:s[1].toLowerCase(),path:r.join("/")}}i(O,"remoteFromInput");const M="Paste a git link: https://host/path, ssh://host/path or user@host:path.",k=i(t=>O(t)||w(M),"validateRemote"),$=i(t=>typeof t=="string"&&t.includes(":"),"isRemote"),b=i(t=>$(t)?(({host:e,path:s})=>[e,...s.toLowerCase().split("/")])(k(t)):S(t).toLowerCase().split("/"),"repoParts"),B=i(t=>$(t)?(({host:e,path:s})=>`${e}/${s}`)(k(t)):S(t),"repoName"),D=i((t,e)=>{try{return b(t).join("/")===b(e).join("/")}catch{return!1}},"sameRepo");function W(t){if(typeof t!="string")return null;const e=t.trim(),s=/^(?:https?:\/\/(?:www\.)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/\s?#]+\/[^/\s?#]+)(?:\/[^\s]*)?(?:[?#][^\s]*)?$/i.exec(e),r=s?s[1].replace(/\.git$/i,""):e;try{return S(r)}catch{return null}}i(W,"githubFromInput");async function vt(t,{repos:e,manifest:s,sendJSON:r}){try{return r(200,await e.lookup(t.searchParams.get("github")??t.searchParams.get("remote"),s))}catch(o){return r(o.status||502,{error:o.message})}}i(vt,"repoLookupRoute");function z(t,e,{onStderr:s,...r}={}){return new Promise(o=>{const l=Z(t,e,{...r,shell:!1,stdio:["ignore","pipe","pipe"]});let m="",y="";l.stdout.on("data",g=>{m+=g}),l.stderr.on("data",g=>{y+=g,s?.(String(g))}),l.on("error",g=>o({status:1,stdout:m,stderr:g.message})),l.on("close",g=>o({status:g,stdout:m,stderr:y}))})}i(z,"runRepo");async function $t(t,e=z){const s=await e("git",["-C",t,"symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),r=await e("git",["-C",t,"symbolic-ref","--quiet","--short","HEAD"]);for(const o of[s.status===0&&s.stdout.trim().replace(/^origin\//,""),r.status===0&&r.stdout.trim()])if(o&&C(E,o))return o;return""}i($t,"defaultBranch");function x(t,e=A()){const s=b(t),r=h.resolve(e),o=h.resolve(r,...s);o.startsWith(`${r}${h.sep}`)||w("Clone path must stay inside the clone folder.");let l=r;for(const y of["",...s])y&&(l=h.join(l,y)),v.lstatSync(l,{throwIfNoEntry:!1})?.isSymbolicLink()&&w("Clone path must stay inside the clone folder; symlinks are refused.");let m=r;for(;!v.existsSync(m);)m=h.dirname(m);return v.realpathSync(m)!==m&&w("Clone path must stay inside the clone folder; symlinks are refused."),o}i(x,"repoPath");const P=i(t=>v.lstatSync(h.join(t,".git"),{throwIfNoEntry:!1})?.isDirectory()===!0,"hasGit");function St(t,e=A()){let s,r,o;try{s=v.realpathSync(t),r=v.realpathSync(e),o=h.relative(r,s).split(h.sep)}catch{return!1}if(o.length===2&&C(S,o.join("/")))return P(s);if(o.length<2||o.length>11||!G.test(o[0])||!o.slice(1).every(l=>I.test(l)&&l!==".."))return!1;for(let l=2;l<o.length;l++)if(P(h.join(r,...o.slice(0,l))))return!1;return P(s)}i(St,"isClone");function st(t){let e="",s=0,r=0;return o=>{const l=(e+o).split(/[\r\n]/);e=l.pop();for(const m of l){const y=/^(Receiving objects|Resolving deltas):\s+(\d+)%/.exec(m.trim());y&&(y[1]==="Receiving objects"?s=Number(y[2]):r=Number(y[2]),t(Math.floor(s*.9+r*.1)))}}}i(st,"cloneMeter");const nt=/^(?:Cloning into |remote: (?:Enumerating|Counting|Compressing|Total) |Receiving objects:|Resolving deltas:|Updating files:)/;function ot(t,e){return(String(t||"").split(/\n\s*\n/).map(r=>r.split(/[\r\n]+/).map(o=>o.trim()).filter(o=>o&&!nt.test(o))).find(r=>r.length)?.at(-1)||e).replace(/(\w+:\/\/)[^/\s@]+@/g,"$1")}i(ot,"errorLine");const _=i((t,e)=>ot(t.stderr||t.stdout,e),"failure"),rt=i(async(t,e,s,r)=>{const o=await t(e,s,r);return o.status!==0&&w(_(o,`${e} failed`),502),o.stdout},"checked"),R=i(async(t,e)=>JSON.parse(await rt(t,"gh",e)),"ghJSON");async function H(t,e,s){v.lstatSync(h.join(e,".git"),{throwIfNoEntry:!1})?.isDirectory()||w("The clone path must have a real .git metadata directory; symlinks are refused.");const r=await t("git",["-C",e,"rev-parse","--show-toplevel"]);(r.status!==0||h.resolve(r.stdout.trim())!==v.realpathSync(e))&&w("The clone path must be the root of a Git work tree.");const o=await t("git",["-C",e,"remote","get-url","origin"]);o.status===0&&($(s)?D(o.stdout.trim(),s):et(o.stdout)?.toLowerCase()===s.toLowerCase())||w(`The clone path origin must be ${$(s)?B(s):`github.com/${s}`}.`)}i(H,"verifyClone");const F=i((t,e)=>t("git",["-c","credential.helper=",...e],{env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),"publicGit"),it=i(t=>["-c","credential.helper=","-c","credential.https://github.com.helper=!gh auth git-credential",...t],"githubGitArgv"),at=i((t,e,s={})=>t("git",it(e),{...s,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),"githubGit"),ct=i((t=process.env)=>({...t,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:t.GIT_SSH_COMMAND||"ssh -o BatchMode=yes"}),"remoteGitEnv"),L=i((t,e,s={})=>t("git",e,{...s,env:ct()}),"remoteGit"),U=i(t=>$(t)?L:at,"gitFor"),lt=i(t=>$(t)?t:`https://github.com/${t}.git`,"cloneURL"),ut=/not found|authentication failed|could not read username|invalid username or password|permission denied|terminal prompts disabled|\b403\b/i;function ft(t,{github:e="",remote:s="",repo:r}){const o=String(t||"").split(`
|
|
2
|
+
`).map(g=>g.trim()).filter(Boolean),l=(o.find(g=>/^remote:/i.test(g))||o.at(-1)||"git failed without a message").replace(/(\w+:\/\/)[^/\s@]+@/g,"$1"),m=O(s),y=m?`check git can reach ${m.host}: git ls-remote ${m.remote}`:e&&ut.test(o.join(`
|
|
3
|
+
`))?`git's github.com login can't see ${e}; run gh auth setup-git`:`run git -C ${r} fetch origin to see the whole error`;return{error:l,hint:y}}i(ft,"gitReachFault");const N=i((t,e)=>{const{error:s,hint:r}=ft(t.stderr||t.stdout,{remote:e,repo:""});return`${s.replace(/[.\s]*$/,".")} ${r[0].toUpperCase()}${r.slice(1)}.`},"reachError");async function q(t,e,s,r){const o=await U(s)(t,["-C",e,"fetch","--no-tags","origin",`+refs/heads/${r}:refs/remotes/origin/${r}`]);o.status!==0&&w(`Could not fetch branch "${r}" from ${B(s)}: ${_(o,"git fetch failed")}`,502)}i(q,"fetchBranch");function xt({run:t=z,base:e=A(),now:s=Date.now}={}){let r,o;const l=new Map,m=i(n=>({github:n.nameWithOwner,private:n.isPrivate,pushedAt:n.pushedAt||"",defaultBranch:n.defaultBranchRef?.name||"",description:n.description||""}),"repoRow"),y=i((n,u)=>{const a=n.github||n.remote,c=x(a,e),p=Object.entries(u.sites||{}).filter(([,f])=>D(f.github||f.remote,a)&&typeof f.owner?.repo=="string"&&T(h.resolve(f.owner.repo)).toLowerCase()===T(c).toLowerCase()).map(([f,d])=>({route:f,title:d.title||f}));return{...n,clone:c,cloned:v.lstatSync(h.join(c,".git"),{throwIfNoEntry:!1})?.isDirectory()||!1,shared:p}},"decorate");async function g(n,u){const a=await n(t,["ls-remote","--symref",u,"HEAD","refs/heads/*"]);if(a.status!==0)return{failed:a};const c=a.stdout,p=[...new Set([...c.matchAll(/^[\da-f]+\s+refs\/heads\/(.+)$/gm)].map(d=>d[1]).filter(d=>C(E,d)))],f=/^ref:\s+refs\/heads\/(.+)\s+HEAD$/m.exec(c)?.[1];return{defaultBranch:p.includes(f)?f:p[0]||"",branches:p}}i(g,"lsRemote");async function J(n){const u=await g(F,`https://github.com/${n}.git`);return u.failed?null:u}i(J,"remoteBranches");async function K(n){const u=await g(L,n);u.failed&&w(N(u.failed,n),404);const{host:a,path:c}=k(n);return{remote:n,host:a,name:`${a}/${c}`,github:"",pushedAt:"",defaultBranch:u.defaultBranch,description:""}}i(K,"findRemote");async function Q(n){const u=await t("gh",["repo","view",n,"--json","nameWithOwner,isPrivate,description,pushedAt,defaultBranchRef"]);if(u.status===0){const c=JSON.parse(u.stdout);return S(c.nameWithOwner),m(c)}return(await F(t,["ls-remote","--heads",`https://github.com/${n}.git`])).status!==0?null:{github:n,private:!1,pushedAt:"",defaultBranch:"",description:""}}i(Q,"find");async function V(){if((await t("gh",["auth","status"])).status!==0)return{signedIn:!1,repos:[]};const u=await R(t,["api","user"]),a=await R(t,["api","user/orgs","--paginate","--slurp"]),c=[...new Set([u.login,...a.flat().map(d=>d.login)])],p=await Promise.all(c.map(d=>R(t,["repo","list",d,"--limit","100000","--json","nameWithOwner,isPrivate,pushedAt,defaultBranchRef,description"]))),f=new Map;for(const d of p.flat())C(S,d.nameWithOwner)&&f.set(d.nameWithOwner.toLowerCase(),m(d));return{signedIn:!0,login:u.login,owners:c,repos:[...f.values()].sort((d,j)=>(j.pushedAt||"").localeCompare(d.pushedAt||"")||d.github.localeCompare(j.github))}}return i(V,"discover"),{base:h.resolve(e),path:i(n=>x(n,e),"path"),cloned:i(n=>v.lstatSync(h.join(x(n,e),".git"),{throwIfNoEntry:!1})?.isDirectory()||!1,"cloned"),async list(n={},{fresh:u=!1}={}){return(u||!r||s()-r.at>=6e4)&&(o||=V().then(a=>(r={at:s(),value:a},a)).finally(()=>{o=null}),await o),{...r.value,repos:r.value.repos.map(a=>y(a,n))}},async lookup(n,u={}){const a=W(n),c=a?null:O(n);!a&&!c&&w($(n)?M:"Repo must be owner/name on GitHub.");const p=a?a.toLowerCase():b(c.remote).join("/");let f=l.get(p);if(!f||s()-f.at>=6e4){for(const[j,X]of l)s()-X.at>=6e4&&l.delete(j);f={at:s(),pending:a?Q(a):K(c.remote)},l.set(p,f),f.pending.catch(()=>{l.get(p)===f&&l.delete(p)})}const d=await f.pending;return d||w("Not found, or you don't have access.",404),y({...d,listed:!1},u)},async branches(n){if($(n)){k(n);const a=await g(L,n);return a.failed&&w(N(a.failed,n),502),a}const u=S(n);try{const a=await R(t,["api",`repos/${u}`]),c=await R(t,["api",`repos/${u}/branches?per_page=100`,"--paginate","--slurp"]);return{defaultBranch:a.default_branch,branches:c.flat().map(p=>p.name).filter(p=>C(E,p))}}catch(a){const c=await J(u);if(!c)throw a;return c}},async ensure(n,u="main",{progress:a}={}){const c=x(n,e);return E(u),v.mkdirSync(h.dirname(c),{recursive:!0}),tt(h.join(h.resolve(e),".locks",...b(n)),async()=>{if(x(n,e),v.existsSync(c))return await H(t,c,n),await q(t,c,n,u),c;const p=v.mkdtempSync(h.join(h.resolve(e),".clone-"));try{const f=await U(n)(t,["clone","--progress",lt(n),h.join(p,"repo")],a?{onStderr:st(a)}:{});f.status!==0&&w($(n)?N(f,n):_(f,"git clone failed"),502),await H(t,h.join(p,"repo"),n),await q(t,h.join(p,"repo"),n,u),x(n,e),v.renameSync(h.join(p,"repo"),c)}finally{v.rmSync(p,{recursive:!0,force:!0})}return c},{timeout:10*6e4,heartbeat:!0})}}}i(xt,"repoService");export{st as cloneMeter,$t as defaultBranch,ft as gitReachFault,W as githubFromInput,et as githubFromOrigin,it as githubGitArgv,St as isClone,$ as isRemote,O as remoteFromInput,ct as remoteGitEnv,vt as repoLookupRoute,B as repoName,b as repoParts,x as repoPath,xt as repoService,z as runRepo,E as validateBranch,S as validateGithub,k as validateRemote};
|
package/hub/restart-board.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var L=Object.defineProperty;var r=(s,n)=>L(s,"name",{value:n,configurable:!0});import{listBoards as m,readManifest as p,withManifestLock as M,writeManifest as S}from"./boards.mjs";import{routeRecord as h,validRoute as A}from"./routes.mjs";import{sessionOf as B,stopSession as I,withSessionLock as O}from"./sessions.mjs";const o=r((s,n=400)=>{throw Object.assign(new Error(s),{status:n})},"refuse"),R=r(s=>!!(Array.isArray(s?.cmd)&&s.cmd.length&&s.port&&s.owner?.session&&s.owner.repo),"restartable"),_=12e4,j=1e3;async function E(s,{serverUp:n,portUp:b,live:d,stop:u,run:T,now:w=Date.now,sleep:y=r(f=>new Promise(e=>setTimeout(e,f)),"sleep"),onStarting:$}={}){return A(s)||o("Choose a board route."),O(s,async({resume:f})=>{const e=p();m(e).find(t=>t.route===s)||o("That board is not open.",404);const a=h(e.sites,s),c=a.title||s;R(a)||o(`${c} has no server the hub runs or no session to resume.`,409);const l=m(e).filter(t=>t.route!==s&&t.owner?.session===a.owner.session);l.length&&o(`This session is also recorded by ${l.map(t=>`${t.title} (/${t.route})`).join(", ")}; restart refused.`,409),await I(B(e,s),{live:d,stop:u}),await M(async()=>{const t=p(),i=h(t.sites,s);i||o("That board is not open.",404),i.restart_at=Date.now(),await S(t)});const g=await n(s),{session:k}=await f({run:T,live:d});if(!g){$?.(c);const t=w()+_;let i=!1;for(;!(i=await b(a.port))&&w()<t;)await y(j);i||o(`${c}\u2019s session is back, but its server is still starting after 2 minutes. See kickflip logs ${s}.`,504)}return{route:s,title:c,session:k}})}r(E,"restartBoard");export{E as restartBoard,R as restartable};
|
package/hub/schedule.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var S=Object.defineProperty;var i=(t,e)=>S(t,"name",{value:e,configurable:!0});import{FOREVER as c,durationEnd as O,inRange as H}from"./duration.mjs";const w=Object.freeze({quiet:Object.freeze({start:"22:00",end:"08:00",hold:!0}),notifications:Object.freeze({on:!0,weekends_off:!1,snoozed_until:null})}),N="never",f=Object.freeze({present:1,away:5,lowPresent:5,lowAway:15}),A=1e3,Q=f.lowAway,h=/^([01]\d|2[0-3]):([0-5]\d)$/,m=f.away*6e4,d=i(t=>{const[e,n]=t.split(":").map(Number);return e*60+n},"minutes"),a=i((t,e,n=0)=>{const[o,r]=e.split(":").map(Number);return new Date(t.getFullYear(),t.getMonth(),t.getDate()+n,o,r)},"atOn"),y=i((t,e)=>{const n=a(t,e);return n>t?n:a(t,e,1)},"nextAt"),q=i((t,e)=>{const n=a(t,e);return n<=t?n:a(t,e,-1)},"lastAt"),x=i(t=>({quiet:{...t.quiet},notifications:{...t.notifications}}),"copy");function v({present:t,remaining:e=null}){const n=e!==null&&e<A;return t?n?f.lowPresent:f.present:n?f.lowAway:f.away}i(v,"checkEvery");function U({last:t,present:e,remaining:n=null,backAt:o=null}){return o&&o>t?new Date(o):new Date(t.getTime()+v({present:e,remaining:n})*6e4)}i(U,"nextCheckAt");function _(t){const e=t?.on??w.notifications.on,n=t?.weekends_off??w.notifications.weekends_off,o=t?.snoozed_until??null;return typeof e!="boolean"?{error:"Notifications must be on or off."}:typeof n!="boolean"?{error:"Off on weekends must be on or off."}:o!==null&&o!==c&&(typeof o!="string"||Number.isNaN(Date.parse(o)))?{error:"Snooze must end at a date and time, or be forever."}:{notifications:{on:e,weekends_off:n,snoozed_until:o===null||o===c?o:new Date(o).toISOString()}}}i(_,"validateNotifications");function b(t){const{start:e,end:n,hold:o=w.quiet.hold}=t?.quiet||{},{notifications:r,error:u}=_(t?.notifications);return u?{error:u}:typeof e!="string"||!h.test(e)?{error:"Quiet hours' start must be HH:MM (24-hour)."}:typeof n!="string"||!h.test(n)?{error:"Quiet hours' end must be HH:MM (24-hour)."}:e===n?{error:"Quiet hours must start and end at different times."}:typeof o!="boolean"?{error:"Hold pushes must be on or off."}:{settings:{quiet:{start:e,end:n,hold:o},notifications:r}}}i(b,"validate");function T(t){const e=(Array.isArray(t?.windows)?t.windows:[]).map(n=>n?.from).filter(n=>typeof n=="string"&&h.test(n)).sort((n,o)=>d(n)-d(o));return e.length<2?null:{start:e.at(-1),end:e[0],hold:t.hold_overnight!==!1}}i(T,"fromPolling");function W(t){const e=_(t?.notifications).notifications||x(w).notifications;return b({quiet:t?.quiet,notifications:e}).settings||b({quiet:T(t?.polling),notifications:e}).settings||{...x(w),notifications:e}}i(W,"quietOf");function Y(t,e){const n={...t.quiet};return"start"in e&&(n.start=e.start),"end"in e&&(n.end=e.end),"hold"in e&&(n.hold=e.hold==="on"),{quiet:n,notifications:t.notifications}}i(Y,"editQuiet");function $(t,e){const n=t.getHours()*60+t.getMinutes(),[o,r]=[d(e.quiet.start),d(e.quiet.end)];return o<r?n>=o&&n<r:n>=o||n<r}i($,"quietAt");function K(t,e){if(!$(t,e))return null;const n=q(t,e.quiet.start),o=(d(e.quiet.end)-d(e.quiet.start)+1440)%1440,r=new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes()+o/2);return r<=t?r:null}i(K,"quietMiddleOf");function C(t,e){return e.quiet.hold&&$(t,e)&&t-q(t,e.quiet.start)>m}i(C,"holdsPushes");function D(t,e){if(!e.notifications?.weekends_off)return null;let n=a(t,e.quiet.start,-((t.getDay()-5+7)%7));n>t&&(n=a(n,e.quiet.start,-7));const o=a(n,e.quiet.end,3);return t-n>m&&t<o?o:null}i(D,"weekendEnd");function R(t,e){if(e.notifications?.on===!1)return{until:N,why:"off"};if(e.notifications?.snoozed_until===c)return{until:c,why:"snoozed"};const n=e.notifications?.snoozed_until?new Date(e.notifications.snoozed_until):null,o=i(s=>(n>s?["snoozed",n]:null)||D(s,e)&&["weekend",D(s,e)]||C(s,e)&&["overnight",y(s,e.quiet.end)],"at"),r=o(t);if(!r)return null;let u=r[1];for(let s=o(u),p=0;s&&p<8;s=o(u),p++)u=s[1];return{until:u,why:r[0]}}i(R,"hold");function j(t,e){return R(t,e)?.until??null}i(j,"heldUntil");function V(t,e){return j(t,e)??new Date(t.getTime()+f.away*6e4)}i(V,"flushAt");function G(t,e,n){const o=String(e);let r;if(o==="morning")r=y(t,n.quiet.end);else if(o==="tonight")r=y(t,n.quiet.start);else if(o==="monday")r=a(t,n.quiet.end,(8-t.getDay())%7),r<=t&&(r=a(r,n.quiet.end,7));else return O(t,o);return H(t,r)?r:null}i(G,"snoozeEnd");function B(t,e=new Date){if(t.why==="off")return"notifications are off";if(t.until===c)return"snoozed until you end it";const n=k(t.until,e);return t.why==="snoozed"?`snoozed until ${n}`:t.why==="weekend"?`held for the weekend until ${n}`:`held overnight until ${n}`}i(B,"holdLine");function F(t){return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}i(F,"localDay");function J(t,e,n={}){const o=e.quiet.end;return a(t,o)<=t&&n?.[o]!==F(t)?[o]:[]}i(J,"wakesDue");const I=i(t=>/^\/([^/?#]+)(?:[/?#]|$)/.exec(t||"")?.[1]??null,"routeOf");function X(t,e={}){const n=new Map;t.forEach((r,u)=>{r.tag&&n.set(r.tag,u)});const o=new Map;return t.filter((r,u)=>!r.tag||n.get(r.tag)===u).forEach(r=>{const u=I(r.url)??Symbol(r.id);o.set(u,[...o.get(u)||[],r])}),[...o].flatMap(([r,u])=>{if(u.length===1){const[l]=u;return[{title:l.title,body:l.body||"",url:l.url||"/",tag:l.tag||void 0,kind:l.kind,members:[l.id]}]}const s=e[r];if(s&&!s.count)return[];const p=r==="_hub"?"Hub":r,g=u.map(l=>l.title),z=s?`${s.count} need${s.count===1?"s":""} you on ${p}`:`${u.length} updates on ${p}`,E=s?s.summary:[...g.slice(0,2),...g.length>2?[`and ${g.length-2} more`]:[]].join(" \xB7 "),M=u.every(l=>l.kind==="action")?"action":u.find(l=>l.kind!=="action").kind;return[{title:z,body:E,url:`/${r}/`,tag:`summary:${r}`,kind:M,members:u.map(l=>l.id)}]})}i(X,"notifications");const Z=i((t,e=new Date)=>t===c?"once the snooze ends":k(t,e),"sendWords");function k(t,e=new Date){const n=t.getHours(),o=`${n%12||12}:${String(t.getMinutes()).padStart(2,"0")}${n<12?"am":"pm"}`,r=Math.round((a(t,"00:00")-a(e,"00:00"))/864e5);return r===0?o:r===1?`${o} tomorrow`:`${o} ${t.toDateString().slice(0,10)}`}i(k,"clock");export{f as CHECK_MINUTES,w as DEFAULTS,A as LOW_POINTS,N as NEVER,Q as SLOWEST_CHECK_MINUTES,v as checkEvery,k as clock,Y as editQuiet,V as flushAt,T as fromPolling,j as heldUntil,R as hold,B as holdLine,C as holdsPushes,F as localDay,U as nextCheckAt,X as notifications,$ as quietAt,K as quietMiddleOf,W as quietOf,Z as sendWords,G as snoozeEnd,b as validate,J as wakesDue};
|
package/hub/sessions.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
${
|
|
1
|
+
var ne=Object.defineProperty;var a=(e,s)=>ne(e,"name",{value:s,configurable:!0});import _ from"node:fs";import w from"node:path";import O from"node:os";import{spawn as K,spawnSync as oe}from"node:child_process";import{fileURLToPath as ie}from"node:url";import{joinName as re,routeRecord as h,validRoute as ae}from"./routes.mjs";import{withFileLock as ce}from"./locks.mjs";import{RESUME_STATE as D,carryCursor as ue,hubBoard as W,isListening as de,listBoards as L,listenState as le,oldestUnheard as fe,readManifest as S,readJSON as P,saveJSON as J,watchedCounts as pe,watchedLines as me,watcherCursor as he,withManifestLock as we,writeManifest as ge}from"./boards.mjs";import{readUsageGate as be,heldUsageEvent as ke}from"../shared/usage-gate.mjs";import{liveSessions as T,sessionRecords as $e,processStarts as ye,verifiedProcess as Se}from"./live.mjs";import{deliver as Ie}from"./push.mjs";import{WAIT_MS as Te}from"./prompts.mjs";import{nodeBin as H,storedPath as X}from"../bin/install.mjs";import{reposDir as xe}from"../shared/repos.mjs";import{isClone as _e}from"./repos.mjs";import{trustFolder as Oe}from"./trust.mjs";import{contextFull as ve,contextReading as je}from"./usage.mjs";const v=X(w.resolve(w.dirname(ie(import.meta.url)),"..")),Ae=3*6e4,Ee=5*6e4,Ce=15*6e4,q=w.join(O.homedir(),".claude","kickflip","compact-state.json"),De=a((e,s=Date.now())=>!!e.error||s-Date.parse(e.asked_at||e.since)>=Ce,"startFailed");function Le(e){return e.session?{step:"landing",stepAt:e.since}:e.phase==="cloning"?{step:"cloning",stepAt:e.asked_at}:{step:"starting",stepAt:e.phase_at||e.asked_at||e.since}}a(Le,"startStep");function ps(e,s=Date.now(),t=()=>{}){return Object.entries(e.starting||{}).filter(([i])=>!h(e.sites,i)).map(([i,n])=>({route:i,title:n.title||n.label||i,repo:n.repo,...Le(n),...n.phase==="cloning"&&t(i)!==void 0?{percent:t(i)}:{},...n.branch?{branch:n.branch,tickets:n.tickets}:{},askedAt:n.asked_at||n.since,failed:De(n,s),...n.error?{error:n.error}:{}}))}a(ps,"startingBoards");const Pe=Te/1e3+60,Ue=JSON.stringify({worktree:{bgIsolation:"none"},permissions:{deny:["Workflow"]},hooks:{PermissionRequest:[{matcher:"*",hooks:[{type:"command",command:`"${H()}" "${w.join(v,"hub","permission-hook.mjs")}"`,timeout:Pe}]}],PermissionDenied:[{matcher:"Bash",hooks:[{type:"command",command:`"${H()}" "${w.join(v,"hub","permission-denied-hook.mjs")}"`,timeout:15}]}]}});class m extends Error{static{a(this,"SessionError")}constructor(s,t){super(s),this.reason=t}}function Ne(e,s){if(!ae(e))throw new m("Choose a board route.","none");return ce(w.join(O.homedir(),".claude","kickflip","session-locks",e),()=>s({resume:a(t=>Xe(e,t),"resume")}),{staleAfter:12e4,timeout:9e4})}a(Ne,"withSessionLock");function j(){if(process.env.KICKFLIP_CLAUDE)return process.env.KICKFLIP_CLAUDE;const e=w.join(O.homedir(),".local","bin","claude");return _.existsSync(e)?e:"claude"}a(j,"claudeBin");const A=a(e=>e==="CLAUDECODE"||e==="CLAUDE_PID"||e==="CLAUDE_EFFORT"||e.startsWith("CLAUDE_CODE_"),"inherited");function Q(){return process.env.KICKFLIP_TMUX?process.env.KICKFLIP_TMUX:["/opt/homebrew/bin/tmux","/usr/local/bin/tmux","/usr/bin/tmux"].find(e=>_.existsSync(e))||"tmux"}a(Q,"tmuxBin");function U(e){const s=oe(Q(),e,{encoding:"utf8",timeout:1e4,env:Object.fromEntries(Object.entries(process.env).filter(([t])=>!A(t)))});return s.error?.code==="ENOENT"?{status:127,stdout:"",stderr:"tmux isn't installed; kickflip doctor names how to install it"}:{status:s.status??1,stdout:s.stdout||"",stderr:s.stderr||s.error?.message||""}}a(U,"runTmux");const I=a(e=>`kickflip-${e}`,"tmuxName"),N=a((e,s)=>e(["has-session","-t",`=${I(s)}`]).status===0,"hasTmux");async function ms({manifest:e=S(),now:s=new Date,running:t=T(),wakes:i=P(D,{}),tmux:n=U}={}){if(!t)return{compacted:[],failed:[]};const r=Object.assign(Object.create(null),P(q,{})),o=[],l=[];let u=!1;const c=W(e)?.route;for(const p of L(e)){const f=je(p.owner?.session);if(!ve(le(p,{now:s.getTime(),running:t,wakes:i}),f)){h(r,p.route)&&(delete r[p.route],u=!0);continue}if(p.route!==c||h(r,p.route)||!N(n,p.route))continue;const d=`=${I(p.route)}:`,$=n(["send-keys","-t",d,"-l","/compact"]),k=$.status===0?n(["send-keys","-t",d,"Enter"]):$,g=k.status===0?null:(k.stderr||k.stdout).trim().slice(0,300)||`tmux exited ${k.status}`;r[p.route]={session:p.owner.session,percent:f.percent,at:s.toISOString(),...g?{error:g}:{}},u=!0,g?l.push(`${p.route}: could not send /compact to tmux session ${I(p.route)} (${g})`):o.push(p.route)}return u&&J(q,r),{compacted:o,failed:l}}a(ms,"compactFullContexts");function B(e,{cwd:s,timeout:t=6e4}){const i=j(),n=Object.fromEntries(Object.entries(process.env).filter(([r])=>!A(r)));return n.CLAUDE_BG_ISOLATION="none",w.isAbsolute(i)&&(n.PATH=`${w.dirname(i)}:${n.PATH||""}`),new Promise(r=>{let o="",l="",u;try{u=K(i,e,{cwd:s,env:n,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(f){r({status:1,stdout:o,stderr:f.message});return}const c=a(f=>{clearTimeout(p),u.stdout.destroy(),u.stderr.destroy(),r({status:f,stdout:o,stderr:l})},"done"),p=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}c(1)},t);u.stdout.on("data",f=>{o+=f}),u.stderr.on("data",f=>{l+=f}),u.on("error",f=>{l+=f.message,c(1)}),u.on("close",f=>c(f??1)),u.on("exit",f=>setTimeout(()=>c(f??1),300)),u.unref()})}a(B,"runClaude");async function Be(e,{cwd:s,run:t=B,starts:i=ye,signal:n=process.kill}={}){if(e.kind==="bg"){const r=await t(["stop",e.jobId||e.sessionId.slice(0,8)],{cwd:s,timeout:8e3});if(r.status!==0)throw new m(`claude stop failed: ${(r.stderr||r.stdout).trim().slice(0,300)}`,"failed")}else{if(!Se(e,i))throw new m(`Cannot verify session ${e.sessionId}'s process identity; refusing to signal pid ${e.pid}.`,"failed");n(e.pid,"SIGTERM")}}a(Be,"runSessionStop");async function hs(e,{live:s=T,stop:t=Be}={}){if(!e?.session)return;const i=s();if(!i)throw new m(ee(e.session),"unknown");const n=i.get(e.session);if(!n)return;await t(n,{cwd:e.repo||n.cwd||O.homedir()});const r=Date.now()+5e3;for(let o=s();!o||o.get(e.session)?.pid===n.pid;o=s()){if(Date.now()>=r)throw new m(`session ${e.session} did not stop`,"failed");await new Promise(l=>setTimeout(l,100))}}a(hs,"stopSession");function Me(e){const s=`=${I(e)}`;return Re(Q(),process.env.TMUX?["switch-client","-t",s]:["attach-session","-t",s])}a(Me,"attachTmux");function Re(e,s){const t=Object.fromEntries(Object.entries(process.env).filter(([r])=>!A(r)&&r!=="CLAUDE_BG_ISOLATION")),i=a(()=>{},"ignore");process.on("SIGINT",i).on("SIGQUIT",i);const n=a(()=>process.off("SIGINT",i).off("SIGQUIT",i),"settle");return new Promise((r,o)=>{const l=K(e,s,{env:t,stdio:"inherit"});l.on("error",u=>{n(),o(new m(u.message,"failed"))}),l.on("close",u=>{n(),r({status:u??1})})})}a(Re,"runForeground");const M=a(({name:e,model:s})=>["--name",e,"--permission-mode","auto","--settings",Ue,...s?["--model",s]:[]],"common"),Fe=a(e=>`'${e.replaceAll("'","'\\''")}'`,"quote"),E=a((e,s)=>`--name ${Fe(re(e,s))}`,"boardFlag"),Ge=a(({route:e,name:s,model:t,prompt:i})=>["--bg",...M({name:s,model:t}),`/kickflip ${E(e,s)}${i?` ${i}`:""}`],"startArgv"),Ke=a((e,s,t)=>`The hub resumed this session because /${e} had nobody listening. Rejoin the board as session ${s} (kickflip steps 3 and 5): rerun \`node ${w.join(v,"bin","kickflip.mjs")} join ${E(e,t)} --session ${s}\`, relaunch its watcher as a background task, then go on with what its events ask. If your session id (the folder above your scratchpad) isn't ${s}, rejoin with yours and --force.`,"resumePrompt"),We=a(({id:e,route:s,name:t,model:i,background:n})=>["--resume",e,"--bg",...n?[]:M({name:t,model:i}),Ke(s,e,t)],"resumeArgv"),Y=a((e,s)=>`You are the hub session. Read \`${w.join(v,"docs","hub-session.md")}\`, then rejoin /${e} (join ${E(e,s)}) and relaunch its watcher.`,"hubPrompt"),z=a(({route:e,title:s,id:t,model:i})=>[...t?["--resume",t]:[],...M({name:s,model:i}),t?`${Y(e,s)} If your session id (the folder above your scratchpad) isn't ${t}, rejoin with yours and --force.`:`/kickflip ${E(e,s)} --hub
|
|
2
|
+
${Y(e,s)}`],"hubArgv");function V(e,s,{cwd:t,tmux:i}){const n=j(),r=[...new Set(["CLAUDECODE","CLAUDE_BG_ISOLATION",...Object.keys(process.env).filter(A)])].flatMap(l=>["-u",l]),o=i(["new-session","-d","-s",I(e),"-c",t,"/usr/bin/env",...r,...w.isAbsolute(n)?[`PATH=${w.dirname(n)}:${process.env.PATH||""}`]:[],n,...s]);if(o.status!==0)throw new m(`tmux new-session failed (${o.status}): ${(o.stderr||o.stdout).trim().slice(0,300)}`,"failed");return[n,...s]}a(V,"startTmux");async function ws({manifest:e=S(),repo:s,tmux:t=U,attach:i=Me,live:n=T}={}){const r=W(e);if(!r)throw new m("No hub board is flagged; flag one with kickflip set <route> --hub, or run kickflip join --hub in its repo folder","hub");if(!N(t,r.route)){const o=r.owner?.session?r.owner:null;if(o&&!o.repo&&!s)throw new m(`/${r.route}'s session ${o.session} has no folder recorded; pass --repo <its folder>`,"none");F(o,n);const l=o?.repo||w.resolve(s||process.cwd());if(!_.statSync(l,{throwIfNoEntry:!1})?.isDirectory())throw new m(o?.repo?`/${r.route}'s recorded folder ${l} is gone; rejoin from its new folder with --repo`:`no folder at ${l}`,"none");V(r.route,z({route:r.route,title:r.title,id:o?.session,model:o?.model}),{cwd:l,tmux:t})}return i(r.route)}a(ws,"hubSession");function R(e,s){const t=h(e?.sites,s),i=t?.owner?.session?t.owner:h(e?.starting,s);return i?.session?{...i,title:t?.title||s}:null}a(R,"sessionOf");async function Z(e,s=null){const t=e.match(/backgrounded\s*·\s*([0-9a-f]{8})\b/)?.[1]||e.match(/\bclaude attach ([0-9a-f]{8})\b/)?.[1];if(!t)return{session:s,confirmed:!1};if(s?.startsWith(t))return{session:s,confirmed:!0};for(let i=0;i<20;i++){const n=$e().find(r=>r.jobId===t||r.sessionId.startsWith(t));if(n)return{session:n.sessionId,confirmed:!0};await new Promise(r=>setTimeout(r,500))}return{session:s,confirmed:!1}}a(Z,"startedId");async function Je(e,{run:s,cwd:t}){const i=await s(["agents","--json","--all"],{cwd:t});try{return JSON.parse(i.stdout).some(n=>n?.sessionId===e&&n.kind==="background")}catch{return!1}}a(Je,"isBackground");const ee=a(e=>`Couldn't tell whether session ${e} is live: ps gave no answer in time, as happens on a busy Mac. Try again in a moment.`,"unknownLiveness");function F(e,s){if(!e)return;const t=s();if(!t)throw new m(ee(e.session),"unknown");const i=t.get(e.session);if(i)throw new m(`session ${e.session} is live (${i.kind==="bg"?"in the background":"in a terminal"}, pid ${i.pid}); it gets no second process`,"live")}a(F,"refuseLive");async function se(e,{from:s,to:t,mark:i}){await we(async()=>{const n=S(),r=L(n).find(l=>l.route===e);if(r?.owner?.session===s&&(i||t!==s)&&ue(r,{from:s,to:t,mark:i}),t===s)return;const o=h(n.sites,e);if(o?.owner?.session===s)Object.assign(o,{owner:{...o.owner,session:t},updated:new Date().toISOString()});else if(h(n.starting,e)?.session===s)n.starting[e]={...h(n.starting,e),session:t};else return;await ge(n)})}a(se,"moveOwner");async function gs(e,{manifest:s=S(),repo:t,model:i,prompt:n,run:r=B,live:o=T,clones:l=xe()}={}){if(h(s.closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const u=R(s,e);F(u,o);const c=w.resolve(t||u?.repo||process.cwd());if(!_.statSync(c,{throwIfNoEntry:!1})?.isDirectory())throw new m(`no folder at ${c}`,"none");if(_e(c,l))try{Oe(c)}catch(g){throw new m(`Couldn't trust this folder for Claude Code: ${g.message}`,"failed")}const p=h(s?.sites,e)?.title||h(s?.starting,e)?.title||e,f=Ge({route:e,name:p,model:i||u?.model,prompt:n}),d=await r(f,{cwd:c});if(d.status!==0){const g=(d.stderr||"").trim()||(d.stdout||"").trim();throw new m(g?`claude --bg failed (${d.status}): ${g.slice(0,300)}`:`claude exited ${d.status} with no output; check \`claude agents\``,"failed")}const{session:$,confirmed:k}=await Z(d.stdout);if(!$)throw new m(`claude --bg started a session but no session record names it yet; find it with claude agents (${d.stdout.trim().slice(0,300)})`,"failed");return{route:e,session:$,confirmed:k,repo:X(c),model:i||u?.model||null,name:p,argv:[j(),...f],output:d.stdout.trim()}}a(gs,"startSession");function He(e,s={}){return Ne(e,({resume:t})=>t(s))}a(He,"resumeSession");async function Xe(e,{manifest:s=S(),run:t=B,tmux:i=U,live:n=T,mark:r=null}={}){if(h(S().closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const o=R(s,e);if(!o)throw new m(`/${e} has no recorded session`,"none");if(!o.repo)throw new m(`/${e}'s session ${o.session} has no folder recorded; its session records one by rejoining (kickflip join, --repo)`,"none");if(F(o,n),h(s.sites,e)?.hub===!0){if(N(i,e))throw new m(`/${e}'s tmux session ${I(e)} is still open; attach with kickflip hub`,"live");const d=V(e,z({route:e,title:o.title,id:o.session,model:o.model}),{cwd:o.repo,tmux:i});return await se(e,{from:o.session,to:o.session,mark:r}),{route:e,session:o.session,previous:o.session,confirmed:!1,repo:o.repo,argv:d,output:`in tmux session ${I(e)}`}}const l=await Je(o.session,{run:t,cwd:o.repo}),u=We({id:o.session,route:e,name:o.title,model:o.model,background:l}),c=await t(u,{cwd:o.repo});if(c.status!==0)throw new m(`claude --resume failed (${c.status}): ${(c.stderr||c.stdout).trim().slice(0,300)}`,"failed");const{session:p,confirmed:f}=await Z(c.stdout,o.session);return await se(e,{from:o.session,to:p,mark:r}),{route:e,session:p,previous:o.session,confirmed:f,repo:o.repo,argv:[j(),...u],output:c.stdout.trim()}}a(Xe,"resumeRecordedSession");function qe(e,{listening:s,live:t,recorded:i,counts:n,waiting:r,asked:o=!1,now:l}){if(s)return{action:"none",entry:null};const u=new Date(l).toISOString(),c=e?{...e}:{down_since:u};return t?delete c.mark:!c.mark&&n&&(c.mark=n),c.pushed_at?{action:"none",entry:c}:c.resumed_at?c.error||l-Date.parse(c.resumed_at)>=Ee?{action:"push",entry:{...c,pushed_at:u}}:{action:"none",entry:c}:!i||t?{action:"none",entry:c}:!!(e?.mark&&n&&Object.entries(n).some(([f,d])=>d>(h(e.mark,f)??0)))||o||r&&l-Date.parse(c.down_since)>=Ae?{action:"resume",entry:{...c,resumed_at:u}}:{action:"none",entry:c}}a(qe,"resumeStep");async function bs({manifest:e=S(),now:s=new Date,live:t=T,asked:i=new Set,listening:n=a((u,c)=>de(u,{now:s.getTime(),running:c}),"listening"),resume:r=a((u,c)=>He(u,{manifest:e,live:t,mark:c}),"resume"),push:o=Ie,gate:l=be({now:s})}={}){const u=t();if(!u)return{resumed:[],pushed:[],failed:[]};const c=P(D,{}),p=Object.create(null),f={resumed:[],pushed:[],failed:[]};for(const d of L(e)){const $=R(e,d.route),k=!!($&&u.has($.session)),g=n(d,u);let{action:x,entry:b}=qe(h(c,d.route),{listening:g,live:k,recorded:!!$?.repo,now:s.getTime(),asked:i.has(d.route),counts:g?null:pe(d),waiting:!g&&!k&&fe(d)!==null});if(x==="resume"&&l.state==="paused"){const y=h(c,d.route)?.mark||he(d);Object.entries(me(d)).flatMap(([C,te])=>te.slice(h(y,C)||0)).some(C=>!ke(C))||(x="none",delete b.resumed_at)}if(x==="resume")try{await r(d.route,b.mark),f.resumed.push(d.route)}catch(y){y.reason==="unknown"?delete b.resumed_at:b={...b,error:y.message},f.failed.push(`${d.route}: could not resume its session (${y.message})`)}else if(x==="push"){const y=b.error?`The hub couldn't resume it: ${b.error}`:k?"Its session is running but hasn't relaunched its watcher.":`It still isn't listening after the hub resumed it. Try kickflip resume ${d.route}, or claude agents.`;try{await o({title:`${d.title}'s session didn't come back`,body:y,url:`/${d.route}/`,tag:`resume-${d.route}`},{kind:"fault",immediate:!0,at:s}),f.pushed.push(d.route)}catch(G){b={...b,pushed_at:void 0},f.failed.push(`${d.route}: could not push that its session didn't come back (${G.message})`)}}b&&(p[d.route]=b)}return JSON.stringify(p)!==JSON.stringify(c)&&J(D,p),f}a(bs,"checkSessions");export{Ue as BG_SETTINGS,Ee as COMEBACK_WAIT,Pe as PROMPT_HOOK_TIMEOUT_S,Ae as RESUME_AFTER,Ce as STARTING_WAIT,m as SessionError,Me as attachTmux,bs as checkSessions,j as claudeBin,ms as compactFullContexts,z as hubArgv,ws as hubSession,A as inherited,We as resumeArgv,Ke as resumePrompt,He as resumeSession,qe as resumeStep,B as runClaude,Be as runSessionStop,U as runTmux,R as sessionOf,Ge as startArgv,De as startFailed,gs as startSession,ps as startingBoards,hs as stopSession,Q as tmuxBin,I as tmuxName,Ne as withSessionLock};
|
package/hub/sw.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// from push.mjs as {title, body, url, tag, badge}; url is a path on the hub, and badge, when
|
|
3
3
|
// present, is the Home Screen app badge count.
|
|
4
4
|
// It keeps the app shell and its files, network first, so the app opens from the last copy while the host is asleep
|
|
5
|
-
// (docs/adr/
|
|
5
|
+
// (docs/adr/2026-10-29-2005-one-app-for-the-whole-hub.md). Nothing else is cached: API calls, streams, uploads and frames always
|
|
6
6
|
// go to the network.
|
|
7
7
|
// A {forget: 'shell'} message drops the saved shell before the owner's reload and replies on its port.
|
|
8
8
|
const CACHE = 'hub-app';
|
package/hub/try.mjs
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,{mode:384}),
|
|
3
|
-
`)})}o(ut,"failure");function Q(t){return t.ending||(Et(t.child,"SIGTERM"),t.ending=new Promise(e=>{const n=o(()=>{clearTimeout(r),clearInterval(i),e()},"finish"),r=setTimeout(()=>{Et(t.child,"SIGKILL"),n()},4e3),i=setInterval(()=>{try{process.kill(-t.child.pid,0)}catch{n()}},20)})),t.ending}o(Q,"terminate");async function ft(t,e=!1){t.keepPort=e,t.stopped=!0,clearTimeout(t.deadline),clearInterval(t.poll),await Q(t),await t.done}o(ft,"halt");async function K(t,e=!1){await ft(t,e),J(t.board,t.key,{state:void 0,port:void 0,https:void 0,...t.ready?{}:{sha:void 0}}),t.ready||k.delete(A(t.board,t.key))}o(K,"stopRun");async function pt(t,e,n,r={}){if(!n)throw new j("This card has no valid worktree.");const i=xt(n),c=zt(i);if(c)throw new j(c);if(!S.realpathSync(i).startsWith(S.realpathSync(n)+T.sep))throw new j("Build script must be inside the worktree.");const l=await E(n,"rev-parse","HEAD");if(P)throw new j("The hub is stopping. Try again after it restarts.",503);const{state:$}=B(t),R=lt($,e),d={...e==="main"?{}:R,...r,sha:l,script:!0,state:"running",...e==="main"?{}:{at:ct(),head:l}};delete d.port,delete d.https;const O=It(t,e);S.mkdirSync(T.dirname(O),{recursive:!0});const I=S.openSync(O,"w",384);S.fchmodSync(I,384);const p=Rt(i,[e,n],{cwd:n,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,KICKFLIP_BOARD:t.route}});e==="main"?$.main=d:$.cards[e]=d,F(t);const C=A(t,e),a={child:p,board:t,key:e,logFile:O,visited:s(),stopped:!1,port:null,ready:!1};h.set(C,a),k.set(C,l);let _,L;const M=o(D=>{L||=new Error(D),Q(a)},"fail");p.on("error",D=>{_=D}),p.stdout.on("data",D=>S.writeSync(I,D)),p.stderr.on("data",D=>S.writeSync(I,D));const W=vt({input:p.stdout,crlfDelay:1/0});return W.on("line",D=>{const q=/^port (\d{1,5})$/.exec(D);if(!q||a.port||a.stopped)return;const G=Number(q[1]);if(G<1||G>65535){M("Build script printed an invalid port.");return}a.port=G,clearTimeout(a.deadline);const it=s()+6e4;let rt=!1;const gt=o(async()=>{if(!(rt||a.stopped||a.ready||p.exitCode!==null||p.signalCode!==null)){rt=!0;try{if(await u(G)){if(a.stopped||L||p.exitCode!==null||p.signalCode!==null||(a.opening=Dt(a),await a.opening,a.stopped||L||p.exitCode!==null||p.signalCode!==null))return;a.ready=!0,a.visited=s(),$.kind="web",J(t,e,{state:"ready",port:G,https:a.https}),clearInterval(a.poll)}else s()>=it&&M("Nothing answered on the build script\u2019s port within 60 seconds.")}finally{rt=!1}}},"check");a.poll=setInterval(()=>gt().catch(nt=>M(nt.message)),250),gt().catch(nt=>M(nt.message))}),a.deadline=setTimeout(()=>M("No port line within 60 minutes."),60*6e4),p.once("exit",()=>{Q(a)}),a.done=new Promise(D=>p.once("close",(q,G)=>{clearTimeout(a.deadline),clearInterval(a.poll),W.close(),S.closeSync(I),(async()=>{await Q(a),await At(a),a.finished=!0,!a.stopped&&(L||_||q!==0||a.port&&!a.ready?await ut(a,q??1,G,L||_||(a.port&&!a.ready?new Error("Build script exited before its port answered."):null)):a.ready?(e==="main"?(delete $.main.state,delete $.main.port,delete $.main.https):delete $.cards[e],F(t)):($.kind="app",J(t,e,{state:"ready"})))})().catch(it=>w(`build /${t.route} ${e}: ${it.message}`)).finally(()=>{h.get(C)===a&&h.delete(C),D()})})),w(`build /${t.route} ${e}: started; log ${O}`),{status:"started"}}o(pt,"launch");async function ht(t,e,n){const r=A(t,"main");if(v.has(r))throw new j("A build is already running for main.",409);v.add(r);try{h.has(r)&&await K(h.get(r),!0);const i=T.join(bt.homedir(),".claude","kickflip","try",`${t.route}-main`);return S.mkdirSync(T.dirname(i),{recursive:!0}),Ot(i)?await E(i,"checkout","--detach","--force",n.sha):(await E(e,"worktree","prune"),await E(e,"worktree","add","--detach",i,n.sha)),await pt(t,"main",i,n)}catch(i){throw i.status!==503&&(B(t).state.main={...n,state:"failed"},Ct(t,"main",i),F(t)),i}finally{v.delete(r)}}o(ht,"launchMain");async function mt(t,{manifest:e=U()}={}){if(await et(e),Z(e),P)throw new j("The hub is stopping. Try again after it restarts.",503);if(!t||Array.isArray(t)||typeof t!="object"||Object.keys(t).some(d=>!["route","key"].includes(d))||typeof t.route!="string"||typeof t.key!="string")throw new j("Send only the board route and card key.");const{route:n,key:r}=t;if(r!=="main"&&(!/^[\w.-]+\/[\w.-]+$/.test(r)||r.split("/").some(d=>d==="."||d==="..")))throw new j("Card key must be <wave>/<id>.");const i=z(e).find(d=>d.route===n);if(!i)throw new j(`/${n} is not a board.`,404);if(r!=="main"&&!i.waves.some(({slug:d,wave:O})=>O.items.some(I=>`${d}/${I.id}`===r)))throw new j("There is no item with this card key.",404);const c=await b();if(c)throw new j(c,409);const l=A(i,r),$=h.get(l);if(v.has(l)||$&&!$.ready&&!$.finished)throw new j(`A build is already running for ${r==="main"?"main":"this card"}.`,409);if(r==="main"){const d=B(i).state.main;if(d?.state==="running")throw new j("A build is already running for main.",409);if(d?.state!=="failed"||!d.sha)throw new j("Main has no failed build to retry.",409);const{sha:O,branch:I,slug:p,at:C,script:a}=d;return ht(i,st(n,e).repo,{sha:O,branch:I,slug:p,at:C,script:a})}v.add(l);const R=f.delete(l);try{h.has(l)&&await K(h.get(l),!0);const d=await jt(i,r,e);return await pt(i,r,d)}catch(d){throw y.delete(l),R&&d.status!==503&&J(i,r,{state:void 0,sha:void 0}),d}finally{v.delete(l)}}o(mt,"start");function wt(t,e,{manifest:n=U()}={}){const r=z(n).find(c=>c.route===t);if(!r)return null;const i=[...h.values()].find(c=>c.board.dir===r.dir&&c.key.split("/").at(-1).toLowerCase()===e.toLowerCase()&&c.ready&&!c.stopped&&c.child.exitCode===null&&c.child.signalCode===null);return i?{key:i.key,port:i.port}:null}o(wt,"lookup");async function yt({manifest:t=U(),routes:e}={}){if(await et(t),Z(t),P)return x;if(x&&e){if(!N){const n={routes:new Set,manifest:t};n.done=x.catch(()=>{}).then(()=>(N=null,yt({manifest:n.manifest,routes:[...n.routes]}))),N=n}N.manifest=t;for(const n of e)N.routes.add(n);return N.done}return x||(x=(async()=>{const n=z(t),r=V(Ht,{}).prs||{};for(const i of[...h.values()])if(!n.some(c=>c.dir===i.board.dir)||i.key!=="main"&&i.ready&&s()-i.visited>=Xt){await K(i);const{state:c}=B(i.board);i.key==="main"?c.main=null:delete c.cards[i.key],F(i.board)}for(const i of n){if(P)return;if(e&&!e.includes(i.route))continue;const{state:c}=B(i),l=st(i.route,t),$=l.branch||"main",R=l.local?"refs/heads/main":`refs/remotes/origin/${$}`;for(const{slug:d,wave:O}of i.waves)for(const I of O.items){const p=`${d}/${I.id}`;if(!(["done","merged","dropped"].includes(String(I.status).toLowerCase())||["MERGED","CLOSED"].includes(r[`${i.github||O.repo}#${I.pr}`]?.state)))try{const C=A(i,p),a=await jt(i,p,t);if(a){const M=await E(a,"rev-parse","HEAD");let W=0;try{W=Number(await E(a,"rev-list","--count",`${R}..HEAD`))}catch{}Object.assign(c.cards[p]||={},{head:M,ahead:W,script:Ot(xt(a))}),F(i)}else if(!f.has(C))continue;const _=c.cards[p];if((f.has(C)||i.auto_build&&_.script&&_.ahead>0&&(_.sha||k.get(C))!==_.head&&_.state!=="running")&&!v.has(C))try{await mt({route:i.route,key:p},{manifest:t})}catch(M){if([409,503].includes(M.status))continue;throw J(i,p,{sha:_.head}),await ut({board:i,key:p,logFile:Ct(i,p,M)},1),M}}catch(C){w(`try /${i.route} ${p}: ${C.message}`)}}try{if(!l.repo||await b())continue;const d=await E(l.repo,"rev-parse",R);let O=!1;try{await E(l.repo,"cat-file","-e",`${d}:.kickflip/build`),O=!0}catch{}if(!O){const L=h.get(A(i,"main"));L&&await K(L),c.main=null,F(i);continue}const I=c.main;if(I?.state==="running"||I?.sha===d&&(I.state==="failed"||I.state==="ready"&&(c.kind!=="web"||wt(i.route,"main",{manifest:t}))))continue;const p=A(i,"main");if(v.has(p))continue;const C=await E(l.repo,"log","-1","--format=%cI",d);let a=i.github;if(!a)try{a=Tt(await E(l.repo,"remote","get-url","origin"))}catch{}const _={sha:d,branch:$,slug:a||"",at:C,script:O};await ht(i,l.repo,_)}catch(d){w(`try /${i.route} main: ${d.message}`)}}})().finally(()=>{x=null}),x)}o(yt,"tick");async function Nt(){P=!0;const t=Promise.all([...h.values()].map(e=>e.ready?K(e):ft(e)));await Promise.all([t,x])}return o(Nt,"stop"),{start:mt,tick:yt,stop:Nt,lookup:wt,initialize:et}}o(te,"createTryManager");const Pt=1e4,_t=o(async(s,...u)=>(await ot("git",["-C",s,...u],{encoding:"utf8",timeout:Pt,env:Wt()})).stdout,"originGit");async function ye({manifest:s=U(),log:u=console.log,routes:w}={}){const b=w?V(St,{}):{};for(const g of z(s)){if(w&&!w.includes(g.route))continue;const h=st(g.route,s);if(h.local||!h.repo)continue;const v=h.branch||"main",f=new Date().toISOString(),y=Date.now();try{await _t(h.repo,"fetch","--quiet","--no-tags","origin",`+refs/heads/${v}:refs/remotes/origin/${v}`),b[g.route]={at:f,ok:!0}}catch(m){u(`fetch /${g.route} after ${Date.now()-y} ms: ${m.message}`);let k=g.github;if(!k&&!g.remote)try{k=Tt(await E(h.repo,"remote","get-url","origin"))}catch{}b[g.route]={at:f,ok:!1,...Jt(m.killed?`git fetch timed out after ${Pt/1e3} s`:m.stderr,{github:k||"",remote:g.remote,repo:h.repo})};continue}if(g.remote)try{await ee(g,h.repo,v,u)}catch(m){u(`pushed branches /${g.route}: ${m.message}`)}}kt(St,b)}o(ye,"fetchTryBranches");async function ee(s,u,w,b){const g=s.waves.flatMap(({slug:f,wave:y})=>y.items.filter(m=>m.pushed?.branch&&!m.pr&&!["done","merged","dropped"].includes(String(m.status).toLowerCase())).map(m=>({key:`${f}/${m.id}`,branch:m.pushed.branch})));if(!g.length)return;const h=new Map((await _t(u,"ls-remote","--heads","origin")).split(`
|
|
4
|
-
|
|
1
|
+
var qt=Object.defineProperty;var o=(n,f)=>qt(n,"name",{value:f,configurable:!0});import T from"node:fs";import x from"node:path";import Tt from"node:os";import Kt from"node:http";import xt from"node:net";import{execFile as Wt,spawn as Jt}from"node:child_process";import{createInterface as Ot}from"node:readline";import{promisify as zt}from"node:util";import{listBoards as q,readManifest as K,readJSON as rt,saveJSON as It,appendEvent as Ut,GITHUB_STATE as Yt,REPO_FETCH as Ct}from"./boards.mjs";import{boardRepo as Y,githubFromOrigin as Et}from"./board-repo.mjs";import{gitReachFault as jt,remoteFromInput as Qt,remoteGitEnv as Vt}from"./repos.mjs";import{readiness as Xt}from"./readiness.mjs";import{buildScriptError as Zt}from"../board/build-script.mjs";import{appendThread as te,recordedWorktree as ee,setItem as re}from"../board/store.mjs";import{cardPRs as ie,hasPR as se,prKeyOf as ne}from"../shared/card-prs.mjs";class S extends Error{static{o(this,"BuildError")}constructor(f,y=400){super(f),this.status=y}}const dt=zt(Wt),j=o(async(n,...f)=>(await dt("git",["-C",n,...f],{encoding:"utf8",timeout:3e3})).stdout.trim(),"git"),oe=/errSecInternalComponent|keychain[^\n]*\blocked\b|\blocked\b[^\n]*keychain/i,W={first:8500,last:8599},ut=o(n=>/^\d+$/.test(String(n))&&Number(n)>=W.first&&Number(n)<=W.last,"isTryPort"),ae=30*6e4,Mt=o(n=>x.join(n,".kickflip","build"),"scriptAt"),Pt=o(n=>T.existsSync(n),"exists"),_t=o((n,f)=>x.join(n.dir,"data","try",`${f.split("/").at(-1)}.log`),"logFileOf");function At(n,f,y){const h=_t(n,f);return T.mkdirSync(x.dirname(h),{recursive:!0}),T.writeFileSync(h,y.message+`
|
|
2
|
+
`,{mode:384}),T.chmodSync(h,384),h}o(At,"failureLog");const ce=o(n=>new Promise(f=>{const y=Kt.get({host:"127.0.0.1",port:n,path:"/",timeout:1e3},h=>{h.destroy(),f(!0)});y.on("timeout",()=>y.destroy()),y.on("error",()=>f(!1))}),"probe"),Nt=o((n,f)=>{try{process.kill(-n.pid,f)}catch{}},"signalGroup");async function Dt(n,f,y){const h=await ee(n.dir,f),[b,u]=f.split("/"),m=n.waves.find(v=>v.slug===b)?.wave,p=h?.path||m?.items.find(v=>v.id===u)?.worktree;if(typeof p!="string"||!p||p.split(x.sep).includes(".."))return"";let k=h?.repo;const w=(n.github||m?.repo||"").toLowerCase();if(!k&&w){const v=[n.owner?.repo,n.dir,...Object.values(y?.sites||{}).map(P=>P.owner?.repo)];for(const P of new Set(v.filter(C=>typeof C=="string"&&x.isAbsolute(C))))try{if(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(await j(P,"remote","get-url","origin"))?.[1].toLowerCase()===w){k=await j(P,"rev-parse","--show-toplevel");break}}catch{}}if(!h?.path&&!k||h?.path&&!x.isAbsolute(p))return"";try{const v=[x.join(T.realpathSync(Tt.homedir()),".claude","kickflip","worktrees")];if(typeof k=="string"&&x.isAbsolute(k))try{v.push(x.join(T.realpathSync(k),".claude","worktrees"))}catch{}const P=x.resolve(k||"/",p),C=T.realpathSync(P);return v.some(D=>P.startsWith(D+x.sep)&&C.startsWith(D+x.sep))&&T.statSync(C).isDirectory()?C:""}catch{return""}}o(Dt,"installWorktree");function le({now:n=Date.now,answers:f=ce,log:y=console.log,waiting:h=o(async()=>null,"waiting"),event:b=Ut}={}){const u=new Map,m=new Map,p=new Set,k=new Set,w=new Map,v=new Map,P=new Map,C=new Map;let D=!1,L=null,J=null,tt=null;const it=o(()=>new Date(n()).toISOString(),"stamp");function B(t){if(u.has(t.dir))return u.get(t.dir);const e=x.join(t.dir,"data","try.json"),s=rt(e,{kind:null,main:null,cards:{}}),i={...ut(s.main_port)?{main_port:s.main_port}:{},kind:s.kind||null,main:s.main||null,cards:{...s.cards},...s.pull?{pull:{...s.pull,running:void 0}}:{}},r={state:i,file:e,written:JSON.stringify(s)};u.set(t.dir,r),i.main_port&&v.set(t.dir,i.main_port);const a=Object.entries(i.cards).filter(([,l])=>l.state==="running");for(const[l]of a)k.add(R(t,l));return i.kind==="web"?(i.cards=Object.fromEntries(a),i.main&&i.main.state!=="failed"&&(delete i.main.state,delete i.main.port,delete i.main.https)):i.main?.state==="running"&&(delete i.main.state,delete i.main.sha),A(t),r}o(B,"stateOf");function A(t){const e=u.get(t.dir),s=JSON.stringify(e.state);s!==e.written&&(It(e.file,e.state),e.written=s)}o(A,"persist");const R=o((t,e)=>`${t.dir}\0${e}`,"runKey"),ht=o((t,e)=>e==="main"?t.main:t.cards[e],"entryOf");function z(t,e,s){const{state:i}=B(t),r=ht(i,e);if(!r)return;const a=Object.hasOwn(s,"state")&&s.state!==r.state;Object.assign(r,s,e!=="main"&&a?{at:it()}:{}),A(t)}o(z,"update");function st(t){const e=[...Object.values(t?.sites||{}),...Object.values(t?.closed||{}).map(s=>s.site)];for(const s of e){if(!s?.dir)continue;const i=rt(x.join(s.dir,"data","try.json"),{}).main_port;ut(i)&&v.set(s.dir,Number(i))}}o(st,"reserveMains");function Bt(t){const{board:e,key:s}=t,i=R(e,s),r=s==="main"?v.get(e.dir):w.get(i);if(r)return r;const a=new Set([...v.values(),...w.values()]);let l=W.first;for(;a.has(l)&&l<=W.last;)l++;if(l>W.last)throw new Error(`No try ports available (${W.first}\u2013${W.last}). Stop a served card and retry.`);return s==="main"?(v.set(e.dir,l),B(e).state.main_port=l,A(e)):w.set(i,l),l}o(Bt,"publicPort");const nt=o(t=>dt("tailscale",t,{encoding:"utf8",timeout:1e4}),"tailscale");async function mt(t){try{await nt(["serve",`--https=${t}`,"off"])}catch(e){y(`try port ${t}: could not close port: ${(e.stderr||e.message).trim()}`)}}o(mt,"removePort");async function Rt(t){t.https=Bt(t);const e=t.sockets=new Set,s=o(()=>{t.visited=n()},"visit");if(t.relay=xt.createServer(i=>{s();const r=xt.connect(t.port,"127.0.0.1");for(const a of[i,r])e.add(a),a.on("data",s),a.on("error",()=>{i.destroy(),r.destroy()}),a.on("close",()=>{e.delete(a),i.destroy(),r.destroy()});i.pipe(r),r.pipe(i)}),await new Promise((i,r)=>{t.relay.once("error",r),t.relay.listen(0,"127.0.0.1",i)}),!t.stopped){t.exposed=!0;try{await nt(["serve","--bg",`--https=${t.https}`,`http://127.0.0.1:${t.relay.address().port}`])}catch(i){throw new Error(`Couldn't open try port ${t.https}: ${(i.stderr||i.message).trim()}`)}}}o(Rt,"openPort");async function Ft(t){if(await t.opening?.catch(()=>{}),t.exposed&&await mt(t.https),t.relay){for(const e of t.sockets)e.destroy();await new Promise(e=>t.relay.close(e))}t.keepPort||w.delete(R(t.board,t.key))}o(Ft,"closePort");function V(t=K()){if(tt)return tt;st(t);for(const e of q(t))B(e);return tt=(async()=>{try{const{stdout:e}=await nt(["serve","status","--json"]),s=JSON.parse(e);for(const i of Object.keys(s?.TCP||{}))ut(i)&&![...m.values()].some(r=>r.https===Number(i))&&await mt(i)}catch(e){y(`try startup cleanup: ${(e.stderr||e.message).trim()}`)}})(),tt}o(V,"initialize");async function wt(t,e,s,i){const{board:r,key:a}=t;if(z(r,a,{state:"failed",port:void 0,https:void 0}),a==="main")return;const l=[];let g=!1;try{for await(const d of Ot({input:T.createReadStream(t.logFile),crlfDelay:1/0}))g||=oe.test(d),l.push(d),l.length>5&&l.shift()}catch(d){l.push(`Could not read the build log: ${d.message}`)}const _=t.port||(B(r).state.kind||(r.waves.some(({wave:d})=>d.items.some(O=>O.install?.url))?"app":"web"))==="web"?"Serve":"Build";await te(r.dir,a,{text:[`${_} failed (exit ${e??1})`,i?.message,s&&`Stopped by ${s}.`,g&&"The login keychain must be unlocked on the Mac.",...l].filter(Boolean).join(`
|
|
3
|
+
`)})}o(wt,"failure");function et(t){return t.ending||(Nt(t.child,"SIGTERM"),t.ending=new Promise(e=>{const s=o(()=>{clearTimeout(i),clearInterval(r),e()},"finish"),i=setTimeout(()=>{Nt(t.child,"SIGKILL"),s()},4e3),r=setInterval(()=>{try{process.kill(-t.child.pid,0)}catch{s()}},20)})),t.ending}o(et,"terminate");async function yt(t,e=!1){t.keepPort=e,t.stopped=!0,clearTimeout(t.deadline),clearInterval(t.poll),await et(t),await t.done}o(yt,"halt");async function X(t,e=!1){await yt(t,e),z(t.board,t.key,{state:void 0,port:void 0,https:void 0,...t.ready?{}:{sha:void 0}}),t.ready||P.delete(R(t.board,t.key))}o(X,"stopRun");async function gt(t,e,s,i={}){if(!s)throw new S("This card has no valid worktree.");const r=Mt(s),a=Zt(r);if(a)throw new S(a);if(!T.realpathSync(r).startsWith(T.realpathSync(s)+x.sep))throw new S("Build script must be inside the worktree.");const l=await j(s,"rev-parse","HEAD");if(D)throw new S("The hub is stopping. Try again after it restarts.",503);const{state:g}=B(t),_=ht(g,e),d={...e==="main"?{}:_,...i,sha:l,script:!0,state:"running",...e==="main"?{}:{at:it(),head:l}};delete d.port,delete d.https;const O=_t(t,e);T.mkdirSync(x.dirname(O),{recursive:!0});const I=T.openSync(O,"w",384);T.fchmodSync(I,384);const $=Jt(r,[e,s],{cwd:s,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,KICKFLIP_BOARD:t.route}});e==="main"?g.main=d:g.cards[e]=d,A(t);const N=R(t,e),c={child:$,board:t,key:e,logFile:O,visited:n(),stopped:!1,port:null,ready:!1};m.set(N,c),P.set(N,l);let F,E;const U=o(M=>{E||=new Error(M),et(c)},"fail");$.on("error",M=>{F=M}),$.stdout.on("data",M=>T.writeSync(I,M)),$.stderr.on("data",M=>T.writeSync(I,M));const G=Ot({input:$.stdout,crlfDelay:1/0});return G.on("line",M=>{const Z=/^port (\d{1,5})$/.exec(M);if(!Z||c.port||c.stopped)return;const H=Number(Z[1]);if(H<1||H>65535){U("Build script printed an invalid port.");return}c.port=H,clearTimeout(c.deadline);const at=n()+6e4;let ct=!1;const St=o(async()=>{if(!(ct||c.stopped||c.ready||$.exitCode!==null||$.signalCode!==null)){ct=!0;try{if(await f(H)){if(c.stopped||E||$.exitCode!==null||$.signalCode!==null||(c.opening=Rt(c),await c.opening,c.stopped||E||$.exitCode!==null||$.signalCode!==null))return;c.ready=!0,c.visited=n(),g.kind="web",z(t,e,{state:"ready",port:H,https:c.https}),clearInterval(c.poll)}else n()>=at&&U("Nothing answered on the build script\u2019s port within 60 seconds.")}finally{ct=!1}}},"check");c.poll=setInterval(()=>St().catch(lt=>U(lt.message)),250),St().catch(lt=>U(lt.message))}),c.deadline=setTimeout(()=>U("No port line within 60 minutes."),60*6e4),$.once("exit",()=>{et(c)}),c.done=new Promise(M=>$.once("close",(Z,H)=>{clearTimeout(c.deadline),clearInterval(c.poll),G.close(),T.closeSync(I),(async()=>{await et(c),await Ft(c),c.finished=!0,!c.stopped&&(E||F||Z!==0||c.port&&!c.ready?await wt(c,Z??1,H,E||F||(c.port&&!c.ready?new Error("Build script exited before its port answered."):null)):c.ready?(e==="main"?(delete g.main.state,delete g.main.port,delete g.main.https):delete g.cards[e],A(t)):(g.kind="app",z(t,e,{state:"ready"})))})().catch(at=>y(`build /${t.route} ${e}: ${at.message}`)).finally(()=>{m.get(N)===c&&m.delete(N),M()})})),y(`build /${t.route} ${e}: started; log ${O}`),{status:"started"}}o(gt,"launch");async function $t(t,e,s){const i=R(t,"main");if(p.has(i))throw new S("A build is already running for main.",409);p.add(i);try{m.has(i)&&await X(m.get(i),!0);const r=x.join(Tt.homedir(),".claude","kickflip","try",`${t.route}-main`);return T.mkdirSync(x.dirname(r),{recursive:!0}),Pt(r)?await j(r,"checkout","--detach","--force",s.sha):(await j(e,"worktree","prune"),await j(e,"worktree","add","--detach",r,s.sha)),await gt(t,"main",r,s)}catch(r){throw r.status!==503&&(B(t).state.main={...s,state:"failed"},At(t,"main",r),A(t)),r}finally{p.delete(i)}}o($t,"launchMain");async function vt(t,{manifest:e=K()}={}){if(await V(e),st(e),D)throw new S("The hub is stopping. Try again after it restarts.",503);if(!t||Array.isArray(t)||typeof t!="object"||Object.keys(t).some(d=>!["route","key"].includes(d))||typeof t.route!="string"||typeof t.key!="string")throw new S("Send only the board route and card key.");const{route:s,key:i}=t;if(i!=="main"&&(!/^[\w.-]+\/[\w.-]+$/.test(i)||i.split("/").some(d=>d==="."||d==="..")))throw new S("Card key must be <wave>/<id>.");const r=q(e).find(d=>d.route===s);if(!r)throw new S(`/${s} is not a board.`,404);if(i!=="main"&&!r.waves.some(({slug:d,wave:O})=>O.items.some(I=>`${d}/${I.id}`===i)))throw new S("There is no item with this card key.",404);const a=await h();if(a)throw new S(a,409);const l=R(r,i),g=m.get(l);if(p.has(l)||g&&!g.ready&&!g.finished)throw new S(`A build is already running for ${i==="main"?"main":"this card"}.`,409);if(i==="main"){const d=B(r).state.main;if(d?.state==="running")throw new S("A build is already running for main.",409);if(d?.state!=="failed"||!d.sha)throw new S("Main has no failed build to retry.",409);const{sha:O,branch:I,slug:$,at:N,script:c}=d;return $t(r,Y(s,e).repo,{sha:O,branch:I,slug:$,at:N,script:c})}p.add(l);const _=k.delete(l);try{m.has(l)&&await X(m.get(l),!0);const d=await Dt(r,i,e);return await gt(r,i,d)}catch(d){throw w.delete(l),_&&d.status!==503&&z(r,i,{state:void 0,sha:void 0}),d}finally{p.delete(l)}}o(vt,"start");function bt(t,e,{manifest:s=K()}={}){const i=q(s).find(a=>a.route===t);if(!i)return null;const r=[...m.values()].find(a=>a.board.dir===i.dir&&a.key.split("/").at(-1).toLowerCase()===e.toLowerCase()&&a.ready&&!a.stopped&&a.child.exitCode===null&&a.child.signalCode===null);return r?{key:r.key,port:r.port}:null}o(bt,"lookup");async function ot({manifest:t=K(),routes:e}={}){if(await V(t),st(t),D)return L;if(L&&e){if(!J){const s={routes:new Set,manifest:t};s.done=L.catch(()=>{}).then(()=>(J=null,ot({manifest:s.manifest,routes:[...s.routes]}))),J=s}J.manifest=t;for(const s of e)J.routes.add(s);return J.done}return L||(L=(async()=>{const s=q(t),i=rt(Yt,{}).prs||{};for(const r of[...m.values()])if(!s.some(a=>a.dir===r.board.dir)||r.key!=="main"&&r.ready&&n()-r.visited>=ae){await X(r);const{state:a}=B(r.board);r.key==="main"?a.main=null:delete a.cards[r.key],A(r.board)}for(const r of s){if(D)return;if(e&&!e.includes(r.route))continue;const{state:a}=B(r),l=Y(r.route,t),g=l.branch||"main",_=l.local?`refs/heads/${g}`:`refs/remotes/origin/${g}`;for(const{slug:d,wave:O}of r.waves)for(const I of O.items){const $=`${d}/${I.id}`,N=ie(I,r.github||O.repo).map(c=>i[ne(c)]);if(!(["done","merged","dropped"].includes(String(I.status).toLowerCase())||N.length&&N.every(c=>["MERGED","CLOSED"].includes(c?.state))))try{const c=R(r,$),F=await Dt(r,$,t);if(F){const G=await j(F,"rev-parse","HEAD");let M=0;try{M=Number(await j(F,"rev-list","--count",`${_}..HEAD`))}catch{}Object.assign(a.cards[$]||={},{head:G,ahead:M,script:Pt(Mt(F))}),A(r)}else if(!k.has(c))continue;const E=a.cards[$];if((k.has(c)||r.auto_build&&E.script&&E.ahead>0&&(E.sha||P.get(c))!==E.head&&E.state!=="running")&&!p.has(c))try{await vt({route:r.route,key:$},{manifest:t})}catch(G){if([409,503].includes(G.status))continue;throw z(r,$,{sha:E.head}),await wt({board:r,key:$,logFile:At(r,$,G)},1),G}}catch(c){y(`try /${r.route} ${$}: ${c.message}`)}}try{if(!l.repo||await h())continue;const d=await j(l.repo,"rev-parse",_);let O=!1;try{await j(l.repo,"cat-file","-e",`${d}:.kickflip/build`),O=!0}catch{}if(!O){const E=m.get(R(r,"main"));E&&await X(E),a.main=null,A(r);continue}const I=a.main;if(I?.state==="running"||I?.sha===d&&(I.state==="failed"||I.state==="ready"&&(a.kind!=="web"||bt(r.route,"main",{manifest:t}))))continue;const $=R(r,"main");if(p.has($))continue;const N=await j(l.repo,"log","-1","--format=%cI",d);let c=r.github;if(!c)try{c=Et(await j(l.repo,"remote","get-url","origin"))}catch{}const F={sha:d,branch:g,slug:c||"",at:N,script:O};await $t(r,l.repo,F)}catch(d){y(`try /${r.route} main: ${d.message}`)}}})().finally(()=>{L=null}),L)}o(ot,"tick");function kt(t,e){if(C.has(t.dir))return C.get(t.dir);const s=(async()=>{const i=Y(t.route,e),r=i.branch||"main",{state:a}=B(t);a.pull={...a.pull,running:!0},A(t);let l,g;try{l=await de(i.repo,r)}catch(_){g=_.message}if(l===null?delete a.pull:a.pull={at:it(),...g?{error:g}:{}},A(t),l===null)return null;if(g)return y(`pull /${t.route}: ${g}`),{commits:0,error:g};if(l.commits){y(`pull /${t.route}: ${r} fast-forwarded ${l.commits} commit${l.commits===1?"":"s"} to ${l.to.slice(0,7)}`);try{await b(t,"main-pulled",{branch:r,...l})}catch(_){y(`pull /${t.route}: could not send main-pulled (${_.message})`)}}return{commits:l.commits}})().finally(()=>C.delete(t.dir));return C.set(t.dir,s),s}o(kt,"pullMain");async function Lt({manifest:t=K(),routes:e}={}){await V(t);const s=[];for(const i of q(t)){if(D)break;if(e&&!e.includes(i.route))continue;const r=Y(i.route,t);!r.local||!r.repo||(await kt(i,t))?.commits&&s.push(i.route)}return s}o(Lt,"pullMains");async function Gt(t,{manifest:e=K()}={}){if(await V(e),D)throw new S("The hub is stopping. Try again after it restarts.",503);if(!t||Array.isArray(t)||typeof t!="object"||Object.keys(t).some(a=>a!=="route")||typeof t.route!="string")throw new S("Send only the board route.");const s=q(e).find(a=>a.route===t.route);if(!s)throw new S(`/${t.route} is not a board.`,404);const i=Y(s.route,e);if(!i.local||!i.repo)throw new S("This board fetches its branch on every poll; only a local board pulls.",409);const r=await kt(s,e);if(!r)throw new S("This board\u2019s folder has no origin to pull from.",409);return r.commits&&ot({manifest:e,routes:[s.route]}).catch(a=>y(`try /${s.route} main: ${a.message}`)),r}o(Gt,"pull");async function Ht(){D=!0;const t=Promise.all([...m.values()].map(e=>e.ready?X(e):yt(e)));await Promise.all([t,L,...C.values()])}return o(Ht,"stop"),{start:vt,tick:ot,stop:Ht,lookup:bt,initialize:V,pull:Gt,pullMains:Lt}}o(le,"createTryManager");const ft=1e4,pt=o(async(n,...f)=>(await dt("git",["-C",n,...f],{encoding:"utf8",timeout:ft,env:Vt()})).stdout,"originGit");async function de(n,f,{run:y=pt}={}){const h=o(async(...u)=>(await y(...u)).trim(),"git"),b=o(u=>{throw new Error(`can\u2019t pull: ${u}`)},"refuse");try{await h(n,"config","--get","remote.origin.url")}catch{return null}try{await h(n,"fetch","--quiet","--no-tags","origin",`+refs/heads/${f}:refs/remotes/origin/${f}`)}catch(u){b(u.killed?`git fetch timed out after ${ft/1e3} s`:jt(u.stderr,{repo:n}).error)}try{const u=await h(n,"rev-parse","--verify",`refs/heads/${f}^{commit}`),m=await h(n,"rev-parse","--verify",`refs/remotes/origin/${f}^{commit}`),p=o((v,P)=>h(n,"merge-base","--is-ancestor",v,P).then(()=>!0,C=>{if(C.code===1)return!1;throw C}),"isAncestor");if(u===m||await p(m,u))return{from:u,to:u,commits:0};await p(u,m)||b(`${f} has split from origin`);const k=Number(await h(n,"rev-list","--count",`${u}..${m}`)),w=(await h(n,"worktree","list","--porcelain")).split(`
|
|
4
|
+
|
|
5
|
+
`).map(v=>v.split(`
|
|
6
|
+
`)).find(v=>v.includes(`branch refs/heads/${f}`))?.[0].slice(9);return w?(await h(w,"status","--porcelain","--untracked-files=no")&&b("local changes"),await h(w,"merge","--ff-only","--quiet",m)):await h(n,"update-ref",`refs/heads/${f}`,m,u),{from:u,to:m,commits:k}}catch(u){if(u.message.startsWith("can\u2019t pull: "))throw u;b(String(u.stderr||u.message).trim().split(`
|
|
7
|
+
`).at(-1))}}o(de,"pullBranch");async function Ce({manifest:n=K(),log:f=console.log,routes:y}={}){const h=y?rt(Ct,{}):{};for(const b of q(n)){if(y&&!y.includes(b.route))continue;const u=Y(b.route,n);if(u.local||!u.repo)continue;const m=u.branch||"main",p=new Date().toISOString(),k=Date.now();try{await pt(u.repo,"fetch","--quiet","--no-tags","origin",`+refs/heads/${m}:refs/remotes/origin/${m}`),h[b.route]={at:p,ok:!0}}catch(w){f(`fetch /${b.route} after ${Date.now()-k} ms: ${w.message}`);let v=b.github;if(!v&&!b.remote)try{v=Et(await j(u.repo,"remote","get-url","origin"))}catch{}h[b.route]={at:p,ok:!1,...jt(w.killed?`git fetch timed out after ${ft/1e3} s`:w.stderr,{github:v||"",remote:b.remote,repo:u.repo})};continue}if(b.remote)try{await ue(b,u.repo,m,f)}catch(w){f(`pushed branches /${b.route}: ${w.message}`)}}It(Ct,h)}o(Ce,"fetchTryBranches");async function ue(n,f,y,h){const b=n.waves.flatMap(({slug:p,wave:k})=>k.items.filter(w=>w.pushed?.branch&&!se(w)&&!["done","merged","dropped"].includes(String(w.status).toLowerCase())).map(w=>({key:`${p}/${w.id}`,branch:w.pushed.branch})));if(!b.length)return;const u=new Map((await pt(f,"ls-remote","--heads","origin")).split(`
|
|
8
|
+
`).map(p=>/^([\da-f]+)\trefs\/heads\/(.+)$/.exec(p)).filter(Boolean).map(p=>[p[2],p[1]])),m=Qt(n.remote)?.host||"the remote";for(const p of b){let k=u.get(p.branch);if(!k)try{k=await j(f,"rev-parse","--verify","--quiet",`refs/heads/${p.branch}^{commit}`)}catch{}let w=!1;if(k)try{await j(f,"merge-base","--is-ancestor",k,`refs/remotes/origin/${y}`),w=!0}catch{}if(!(!w&&u.has(p.branch)))try{await re(n.dir,p.key,{status:w?"merged":"done",force:!0,text:w?`${p.branch} is merged into ${y} on ${m}, so this card is Done.`:`${p.branch} is gone from ${m}, so this card is Done.`})}catch(v){h(`pushed ${p.key}: ${v.message}`)}}}o(ue,"settlePushed");const Q=le({waiting:o(()=>Xt.waiting("tailscale"),"waiting")}),Ee=o((...n)=>Q.start(...n),"startBuild"),je=o((...n)=>Q.tick(...n),"tryTick"),Me=o((...n)=>Q.pull(...n),"pullNow"),Pe=o((...n)=>Q.pullMains(...n),"pullMains"),_e=o(()=>Q.stop(),"stopTries"),Ae=o((...n)=>Q.initialize(...n),"initializeTries");export{S as BuildError,W as TRY_PORTS,le as createTryManager,Ce as fetchTryBranches,Ae as initializeTries,Dt as installWorktree,ut as isTryPort,de as pullBranch,Pe as pullMains,Me as pullNow,Ee as startBuild,_e as stopTries,je as tryTick};
|
package/hub/usage.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);s>0&&
|
|
3
|
-
`),f.renameSync(u,r)}a(W,"checkUsagePause");export{W as checkUsagePause,R as contextReading,J as usageReader};
|
|
1
|
+
var x=Object.defineProperty;var a=(t,e)=>x(t,"name",{value:e,configurable:!0});import f from"node:fs";import _ from"node:os";import m from"node:path";const S=6,N=180,b={five_hour:5*36e5,seven_day:7*864e5},h=a(t=>{try{return JSON.parse(f.readFileSync(t,"utf8"))}catch{return null}},"readJson"),y=a(t=>t==null||t===""||!Number.isFinite(Number(t))?null:Number(t),"num"),g=a(t=>{if(t==null||t==="")return null;const n=typeof t=="number"||/^\d+(\.\d+)?$/.test(String(t))?Number(t)>1e12?Number(t):Number(t)*1e3:Date.parse(String(t));return Number.isFinite(new Date(n).getTime())?new Date(n).toISOString():null},"isoOf"),w=a((t,e)=>({used_percentage:y(t),resets_at:g(e)}),"win");function O(t){let e;try{e=f.openSync(t,"r");const n=f.fstatSync(e).size;for(const r of[256*1024,2*1024*1024]){const s=Math.max(0,n-r),u=Buffer.alloc(n-s);f.readSync(e,u,0,u.length,s);const c=u.toString("utf8").split(`
|
|
2
|
+
`);s>0&&c.shift();for(let i=c.length-1;i>=0;i--)if(c[i].includes("rate_limits"))try{const d=JSON.parse(c[i]),o=d?.payload?.rate_limits??d?.rate_limits;if(o?.primary)return{rl:o}}catch{}if(s===0)break}}catch{}finally{if(e!==void 0)try{f.closeSync(e)}catch{}}return null}a(O,"lastRateLimits");function k(t){const e=[],n=a(r=>{try{return f.readdirSync(r).sort().reverse()}catch{return[]}},"kids");t:for(const r of n(t))for(const s of n(m.join(t,r)))for(const u of n(m.join(t,r,s))){const c=m.join(t,r,s,u);for(const i of n(c))if(/^rollout-.*\.jsonl$/.test(i))try{e.push({file:m.join(c,i),mtime:f.statSync(m.join(c,i)).mtimeMs})}catch{}if(e.length>=S*2)break t}return e.sort((r,s)=>s.mtime-r.mtime).slice(0,S)}a(k,"newestRollouts");function D(t){const e=[];for(const{file:o,mtime:l}of k(t)){const p=O(o);p&&e.push({...p,mtime:l,resets:y(p.rl.primary.resets_at)})}if(!e.length)return null;const n=Math.max(...e.map(o=>o.resets??-1/0)),r=e.filter(o=>o.resets!=null&&Math.abs(o.resets-n)<=N),s=a(o=>r.reduce((l,p)=>(y(p.rl[o]?.used_percent)??-1)>(y(l?.rl[o]?.used_percent)??-1)?p:l,null),"pick");if(!r.length)return null;const u=s("primary"),c=s("secondary"),i=r.reduce((o,l)=>l.mtime>o.mtime?l:o),d=a((o,l)=>o?w(o.rl[l].used_percent,o.rl[l].resets_at):null,"w");return{five_hour:d(u,"primary"),seven_day:d(c,"secondary"),at:new Date(i.mtime).toISOString()}}a(D,"scanCodex");function j(t,e){if(!t||typeof t!="object"||Array.isArray(t))return null;const n=g(t.at),r=a(s=>{const u=t[s];if(!u)return null;const c=w(u.used_percentage,u.resets_at);if(c.used_percentage==null)return null;const i=!n||e-Date.parse(n)>b[s]?"stale":c.resets_at&&e>=Date.parse(c.resets_at)?"reset":"live";return{...c,used_percentage:i==="reset"?0:c.used_percentage,state:i}},"window");return{at:n,five_hour:r("five_hour"),seven_day:r("seven_day")}}a(j,"readingOf");function J({home:t=_.homedir(),now:e=Date.now,cacheMs:n=6e4}={}){const r=m.join(t,".codex","sessions");let s=null,u=-1/0;return({codexShare:c="off"}={})=>{const i=e(),d=j(h(m.join(t,".claude","kickflip","usage.json"))?.claude,i);return c==="off"?{claude:d,codex:null}:(i-u>=n&&(s=D(r),u=i),{claude:d,codex:j(s||{at:null},i)})}}a(J,"usageReader");const F=95,L=a((t,e)=>t==="deaf"&&e?.percent>=F,"contextFull");function R(t,{home:e=_.homedir()}={}){if(typeof t!="string"||!/^[\w-]+$/.test(t))return null;const n=h(m.join(e,".claude","kickflip","context",`${t}.json`));return y(n?.percent)==null||!n.at?null:{percent:y(n.percent),at:n.at}}a(R,"contextReading");async function W({gate:t,home:e=_.homedir(),resume:n}){const r=m.join(e,".claude","kickflip","usage-gate-state.json"),s=h(r);s?.state==="paused"&&t.state==="normal"&&await n(s.window),f.mkdirSync(m.dirname(r),{recursive:!0});const u=`${r}.${process.pid}.tmp`;f.writeFileSync(u,JSON.stringify(t)+`
|
|
3
|
+
`),f.renameSync(u,r)}a(W,"checkUsagePause");export{F as CONTEXT_FULL,W as checkUsagePause,L as contextFull,R as contextReading,J as usageReader};
|
package/hub/views.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _=Object.defineProperty;var s=(e,t)=>_(e,"name",{value:t,configurable:!0});import{clock as c,holdLine as w,sendWords as H,snoozeEnd as f}from"./schedule.mjs";import{CHOICES as T,FOREVER as k,durationEnd as V,endOf as F}from"./duration.mjs";import{siteIcon as K}from"./icons.mjs";import{codexStatus as M}from"../shared/codex.mjs";const W=s(e=>e.charAt(0).toUpperCase()+e.slice(1),"capital"),b=s((e,t)=>`${e} ${t}${e===1?"":"s"}`,"plural"),h=s(e=>{const[t,n]=e.split(":").map(Number),o=new Date;return o.setHours(t,n,0,0),c(o,o)},"timeOfDay"),B=s(e=>`checks every ${e.every===1?"minute":`${e.every} min`} while you\u2019re ${e.present?"here":"away"}${e.low?", slower while GitHub\u2019s points are low":""}`,"cadenceLine"),G=s((e,t,n)=>`${B(t)}${e.hold?`; ${w(e.hold,n)}`:""}`,"nowLine"),S=s((e,t)=>e.hold?w(e.hold,t):"pushes go out after each check","deviceLine"),Z=s(e=>`${h(e.quiet.start)} \u2013 ${h(e.quiet.end)}${e.quiet.hold?" \xB7 pushes held":""}`,"quietSummary"),Q="checks every minute while you're here, every 5 when away",X=s((e,t)=>e.count?`${e.count} push${e.count===1?"":"es"} queued; next send ${H(e.nextFlushAt,t)}.`:"No pushes queued.","queuedLine");function Y({running:e=!1,nextAt:t,last:n=null},o){if(e)return"Checking GitHub now";const l=`Next check ${c(t,o)}`;if(!n)return l;const u=n.failed.length?"could not reach GitHub for every PR":n.watched?`${b(n.watched,"PR")}, ${n.changes.length?`${n.changes.length} changed`:"no change"}`:"no PRs watched";return`${l} \xB7 last ${c(new Date(n.at),o)}, ${u}`}s(Y,"pollLine");function j(e,t,n){return{title:W(G(e,t,n)),lines:[Y(t,n),X(e,n)],count:e.count}}s(j,"pollingNow");function J(e,t){const n={port:"down \xB7 not answering",files:"down \xB7 folder missing"}[e.serves]||"down \xB7 restarting";if(e.state!=="up")return{tone:e.state==="down"?"down":"wait",word:e.state==="down"?n:e.state,lines:[]};if(!t)return{tone:"ok",word:"up",lines:[]};const o=t.filter(r=>!r.ok),l=o.filter(r=>r.state==="broken"),u=t.find(r=>r.link==="events"),a=u?.listen==="asleep"||u?.listen==="waking"?u.listen:u?.ok?"listening":"not listening",d=l.length?`degraded \xB7 ${a}`:o.length?`up \xB7 ${a} \xB7 ${o.length} settling`:`up \xB7 ${a} \xB7 every link passes`;return{tone:o.length?"wait":"ok",word:d,lines:o.map(r=>({link:r.link,detail:`${r.state==="broken"?"":"settling: "}${r.detail}`}))}}s(J,"siteHealth");const A=[{value:"always",label:"Always on",description:s(()=>"Codex implements and reviews. Work pauses when it runs out.","description")},{value:"auto",label:"Auto",description:s(e=>`Codex implements and reviews, and ${e} takes over while it's out.`,"description")},{value:"off",label:"Off",description:s(e=>`${e} implements and reviews.`,"description")}],ee=s((e,t,n)=>({usable:t.usable,tag:t.usable?null:t.reason,share:e,choices:A.map(({value:o,label:l})=>({value:o,label:l,on:o===e})),description:t.usable?A.find(o=>o.value===e).description(q[n]):t.words,fix:t.fix}),"codexView"),q={opus:"Opus",sonnet:"Sonnet",auto:"Claude"},N=[{value:"opus",label:"Opus",description:"Always Opus. Auto would give small cards to Sonnet."},{value:"auto",label:"Auto",description:"Auto: small cards get Sonnet, the rest get Opus."},{value:"sonnet",label:"Sonnet",description:"Always Sonnet. Auto would give large cards to Opus."}],te=s(e=>({model:e,builder:q[e],choices:N.map(({value:t,label:n})=>({value:t,label:n,on:t===e})),description:N.find(t=>t.value===e).description}),"claudeView");function de({now:e,st:t,poll:n,sidebar:o,rows:l,links:u=new Map,code:a={},host:d="",rules:r=[],remembered:y=new Map,integrations:p=[],codexShare:R="off",claudeModel:x="auto",codex:U=M({installed:!1}),awake:O=null}){const $=new Set(o.sites.filter(i=>i.board).map(i=>i.route)),E=!!(a.running&&a.running===a.onDisk),z=E?` \xB7 runs the code in its files (${a.onDisk})`:"",D=s(i=>({route:i.route,title:i.title,icon:K(i.route,i),href:`/${encodeURIComponent(i.route)}/`,...J(i,u.get(i.route)),remembered:y.get(i.route)||[],restart:$.has(i.route)&&i.restart===!0}),"site"),I=[["Boards",l.filter(i=>$.has(i.route))],["Pages",l.filter(i=>!$.has(i.route))]].filter(([,i])=>i.length).map(([i,L])=>({label:i,sites:L.map(D)}));return{hub:{tone:o.hub.tone,word:o.hub.word,detail:`${o.hub.detail}${z}`,restart:!E},awake:O&&g(O,e,v),groups:I,integrations:p,usage:o.usage,pause:o.pause,codex:ee(R,U,x),claude:te(x),empty:l.length===0,polling:j(t,n,e),notifications:{on:t.settings.notifications.on,text:o.notifications.text,device:S(t,e)},hold:t.hold&&t.hold.why!=="off"?{text:`Notifications ${w(t.hold,e)}`,end:t.hold.why==="snoozed"}:null,rules:r.length?b(r.length,"rule"):"None yet",sites:b(l.length,"site"),host:d,total:o.total}}s(de,"hubView");const ce="That snooze ends in the past or more than 30 days on. Pick another time.",he="That keep awake ends in the past or more than 30 days on. Pick another time.",C="until you end it",v="until you turn it off",g=s((e,t,n)=>e===k?n:`until ${c(e,t)}`,"untilWords"),P=s((e,t)=>T.map(([n,o])=>({value:n,label:o,until:g(V(e,n),e,t)})),"durationChoices"),ne=s((e,t)=>e.on?F(e.snoozed_until,t):null,"snoozedUntil");function pe({now:e,st:t,rules:n=[],route:o={atMac:!1,desktops:0},linear:l={set:!1},awake:u={until:null,unsupported:null}}){const a=t.settings,d=a.notifications,r=ne(d,e),y=t.count?` The ${t.count} queued push${t.count===1?" is":"es are"} dropped now.`:"",p=r&&`Snoozed ${g(r,e,C)}`;return{snoozed:r?{title:p,summary:r===k?"Snoozed \xB7 forever":p}:null,device:S(t,e),on:{on:d.on,sub:d.on?"On. Turn off to drop every push, urgent ones too.":"Off. Every push is dropped, urgent ones too. Needs you and the badge still update.",confirm:`Turn off notifications? Every push is dropped until you turn them back on, urgent ones too.${y} Needs you and the badge still update.`},presence:d.on?o.atMac?o.desktops?{title:"At the host",sub:"Pushes go to the host only. Prompts, faults and urgent pushes still reach the phone."}:{title:"At the host",sub:"No notifications on the host, so pushes still go to the phone."}:{title:"Away from the host",sub:"Pushes go to every device. At the host means unlocked and used in the last 3 minutes."}:null,snooze:d.on&&!r?{choices:P(e,C)}:null,awake:{unsupported:u.unsupported,on:u.until?{title:`Keeping awake ${g(u.until,e,v)}`}:null,choices:u.unsupported||u.until?null:P(e,v),summary:u.unsupported||(u.until?u.until===k?"On \xB7 forever":`On until ${c(u.until,e)}`:"Off")},weekends:{on:d.weekends_off,sub:`Pushes wait from Friday ${h(a.quiet.start)} until Monday ${h(a.quiet.end)}. Urgent ones still go.`},quiet:se(a,e),rules:n,linear:oe(l)}}s(pe,"settingsView");const m={url:"https://linear.app/settings/account/security",label:"Linear \u203A Settings \u203A Security & access \u203A Personal API keys"};function oe(e){const t=e.workspace?`${e.workspace} workspace`:"";return e.set?e.refused?{set:!0,refused:!0,title:t||"Linear key",down:"doesn\u2019t work",sub:`Linear refused the key. Make a new one in ${m.label} and paste it here.`,keys:m,summary:t?`Key doesn\u2019t work \xB7 ${t}`:"Key doesn\u2019t work"}:{set:!0,title:t,sub:"Key \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",summary:`Key set \xB7 ${t}`}:{set:!1,title:"No key",sub:`Make a personal API key in ${m.label}, then paste it here.`,keys:m,summary:"No key"}}s(oe,"linearWords");function se(e,t){const n=e.quiet,[o,l]=[h(n.start),h(n.end)],u=f(t,"tonight",e),a=[["Snooze tonight",`Until ${c(u,t)}${n.hold?`, then quiet hours hold pushes until ${c(f(u,"morning",e),t)}`:""}.`],["Snooze morning",`Until ${c(f(t,"morning",e),t)}.`],["Snooze monday",`Until ${c(f(t,"monday",e),t)}.`],["Off on weekends",e.notifications.weekends_off?`Pushes wait from Friday ${o} until Monday ${l}.`:"Off."],["Daily wake",`Every board wakes once at ${l}, when quiet hours end.`]];return{start:n.start,end:n.end,summary:Z(e),hint:Q,hold:{on:n.hold,sub:n.hold?`Pushes queued after ${o} wait until ${l}. Urgent ones still go.`:"Off. Pushes go out all night."},reads:a.map(([d,r])=>({title:d,sub:r}))}}s(se,"quietView");function fe(e){return e?e.ok?{sent:e.sent,count:e.count,ok:!0,message:`Sent ${e.count} queued push${e.count===1?"":"es"}.`}:{sent:e.sent,count:e.count,ok:!1,message:"Could not send the queue. It stays queued for the next check."}:{sent:0,count:0,ok:!0,message:"Nothing was queued."}}s(fe,"flushView");export{he as AWAKE_REFUSED,Q as QUIET_HINT,ce as SNOOZE_REFUSED,B as cadenceLine,W as capital,P as durationChoices,fe as flushView,de as hubView,G as nowLine,b as plural,Y as pollLine,Z as quietSummary,pe as settingsView,J as siteHealth};
|