@lovek4d/kickflip 0.1.0 → 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.
Files changed (120) hide show
  1. package/CONTEXT.md +239 -104
  2. package/README.md +54 -4
  3. package/SKILL.md +63 -42
  4. package/bin/doctor.mjs +4 -3
  5. package/bin/install.mjs +3 -3
  6. package/bin/kickflip.mjs +103 -40
  7. package/bin/statusline.mjs +4 -3
  8. package/bin/wait-events.mjs +2 -2
  9. package/board/arch-review.mjs +5 -0
  10. package/board/auto-review.mjs +2 -0
  11. package/board/bin/agent.mjs +1 -1
  12. package/board/bin/board.mjs +371 -82
  13. package/board/bin/builder-stop-hook.mjs +4 -3
  14. package/board/domain.mjs +8 -3
  15. package/board/finish.mjs +3 -0
  16. package/board/headless.mjs +3 -0
  17. package/board/on-host.mjs +1 -0
  18. package/board/permissions.mjs +2 -0
  19. package/board/public/app-arch.js +75 -0
  20. package/board/public/app-asks.js +66 -28
  21. package/board/public/app-banner.js +2 -2
  22. package/board/public/app-cards.js +354 -77
  23. package/board/public/app-core.js +40 -8
  24. package/board/public/app-header.js +33 -8
  25. package/board/public/app-lanes.js +238 -34
  26. package/board/public/app-needs.js +2 -0
  27. package/board/public/app-snapshot.js +45 -11
  28. package/board/public/app-threads.js +20 -21
  29. package/board/public/app.html +6 -2
  30. package/board/public/app.js +114 -33
  31. package/board/public/attach.js +39 -3
  32. package/board/public/dialogs.js +161 -118
  33. package/board/public/hub-kit.js +27 -7
  34. package/board/public/hub.css +26 -33
  35. package/board/public/linear-key.js +143 -0
  36. package/board/public/log.html +48 -0
  37. package/board/public/prompts.js +9 -8
  38. package/board/public/prototype-kit.js +6 -6
  39. package/board/public/prototype-switcher.js +13 -5
  40. package/board/public/prototype.html +1 -0
  41. package/board/public/router.js +14 -10
  42. package/board/public/rules-editor.js +4 -5
  43. package/board/public/shell.js +21 -7
  44. package/board/public/sidebar.css +51 -11
  45. package/board/public/sidebar.js +124 -19
  46. package/board/public/style.css +244 -56
  47. package/board/public/toasts.js +5 -3
  48. package/board/public/ui-cards.js +236 -66
  49. package/board/public/ui-enums.js +5 -4
  50. package/board/public/ui-header.js +23 -14
  51. package/board/public/ui-hub.js +34 -16
  52. package/board/public/ui-links.js +18 -10
  53. package/board/public/ui-markdown.js +1 -1
  54. package/board/public/ui-order.js +21 -0
  55. package/board/public/ui-page-header.js +13 -8
  56. package/board/public/ui-patch.js +53 -0
  57. package/board/public/ui-phase-bars.js +17 -0
  58. package/board/public/ui-prompts.js +8 -8
  59. package/board/public/ui-questions.js +35 -11
  60. package/board/public/ui-sidebar.js +83 -21
  61. package/board/public/ui-snapshot.js +30 -13
  62. package/board/public/ui-threads.js +38 -23
  63. package/board/public/ui.js +96 -16
  64. package/board/public/view-frame.js +1 -1
  65. package/board/public/view-hub-settings.js +67 -44
  66. package/board/public/view-hub.js +105 -13
  67. package/board/public/view-notes.js +8 -5
  68. package/board/public/view-questions.js +123 -52
  69. package/board/public/view-settings.js +235 -62
  70. package/board/review.mjs +1 -0
  71. package/board/server.mjs +18 -7
  72. package/board/store.mjs +15 -6
  73. package/board/tickets.mjs +3 -3
  74. package/board/worktree.mjs +20 -13
  75. package/docs/hub-session.md +4 -4
  76. package/hooks-plugin/hooks/codex-share-auto.mjs +7 -5
  77. package/hooks-plugin/hooks/watcher-stop.mjs +41 -0
  78. package/hub/awake.mjs +1 -0
  79. package/hub/board-repo.mjs +1 -1
  80. package/hub/boards.mjs +4 -4
  81. package/hub/close-board.mjs +1 -1
  82. package/hub/duration.mjs +1 -0
  83. package/hub/github.mjs +3 -4
  84. package/hub/home.mjs +1 -1
  85. package/hub/hub.mjs +12 -10
  86. package/hub/incoming.mjs +2 -0
  87. package/hub/linear.mjs +2 -2
  88. package/hub/live.mjs +2 -2
  89. package/hub/new-board.mjs +2 -2
  90. package/hub/permission-denied-hook.mjs +2 -0
  91. package/hub/pr-report.mjs +3 -0
  92. package/hub/presence.mjs +1 -1
  93. package/hub/prompts.mjs +1 -1
  94. package/hub/push.mjs +2 -2
  95. package/hub/readiness.mjs +2 -0
  96. package/hub/repos.mjs +3 -2
  97. package/hub/restart-board.mjs +1 -0
  98. package/hub/routes.mjs +1 -1
  99. package/hub/schedule.mjs +1 -1
  100. package/hub/sessions.mjs +2 -2
  101. package/hub/shell.mjs +2 -1
  102. package/hub/slack.mjs +2 -0
  103. package/hub/stream.mjs +12 -12
  104. package/hub/sw.js +2 -2
  105. package/hub/trust.mjs +2 -0
  106. package/hub/try.mjs +8 -3
  107. package/hub/upgrade.mjs +1 -0
  108. package/hub/usage.mjs +3 -3
  109. package/hub/views.mjs +1 -1
  110. package/package.json +5 -1
  111. package/shared/card-prs.mjs +1 -0
  112. package/shared/colors.css +9 -6
  113. package/shared/fake-gh.mjs +105 -0
  114. package/shared/repos.mjs +1 -1
  115. package/shared/service.mjs +16 -16
  116. package/shared/skills.mjs +2 -0
  117. package/shared/usage-gate.mjs +1 -1
  118. package/starter/public/claude.js +3 -2
  119. package/bin/web-ts.mjs +0 -2
  120. package/board/public/view-polling.js +0 -87
package/hub/repos.mjs CHANGED
@@ -1,2 +1,3 @@
1
- var E=Object.defineProperty;var c=(t,e)=>E(t,"name",{value:e,configurable:!0});import h from"node:fs";import p from"node:path";import{spawn as N}from"node:child_process";import{reposDir as O}from"../shared/repos.mjs";import{withFileLock as D}from"./locks.mjs";import{storedPath as A}from"../bin/install.mjs";const m=c((t,e=400)=>{throw Object.assign(new Error(t),{status:e})},"refuse");function C(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()))&&m("Repo must be owner/name on GitHub."),t}c(C,"validateGithub");function S(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")))&&m("Choose a valid branch name."),t}c(S,"validateBranch");const x=c((t,e)=>{try{return t(e),!0}catch{return!1}},"valid");function G(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}c(G,"githubFromOrigin");function W(t){if(typeof t!="string")return null;const e=t.trim(),a=/^(?:https?:\/\/(?:www\.)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/\s?#]+\/[^/\s?#]+)(?:\/[^\s]*)?(?:[?#][^\s]*)?$/i.exec(e),n=a?a[1].replace(/\.git$/i,""):e;try{return C(n)}catch{return null}}c(W,"githubFromInput");async function Q(t,{repos:e,manifest:a,sendJSON:n}){try{return n(200,await e.lookup(t.searchParams.get("github"),a))}catch(i){return n(i.status||502,{error:i.message})}}c(Q,"repoLookupRoute");function T(t,e,a={}){return new Promise(n=>{const i=N(t,e,{...a,shell:!1,stdio:["ignore","pipe","pipe"]});let f="",y="";i.stdout.on("data",g=>{f+=g}),i.stderr.on("data",g=>{y+=g}),i.on("error",g=>n({status:1,stdout:f,stderr:g.message})),i.on("close",g=>n({status:g,stdout:f,stderr:y}))})}c(T,"runRepo");function v(t,e=O()){C(t);const a=p.resolve(e),n=p.resolve(a,t.toLowerCase());n.startsWith(`${a}${p.sep}`)||m("Clone path must stay inside .repos.");let i=a;for(const y of["",...t.toLowerCase().split("/")])y&&(i=p.join(i,y)),h.lstatSync(i,{throwIfNoEntry:!1})?.isSymbolicLink()&&m("Clone path must stay inside .repos; symlinks are refused.");let f=a;for(;!h.existsSync(f);)f=p.dirname(f);return h.realpathSync(f)!==f&&m("Clone path must stay inside .repos; symlinks are refused."),n}c(v,"repoPath");const L=c((t,e)=>(t.stderr||t.stdout||e).trim().split(`
2
- `)[0].replace(/(\w+:\/\/)[^/\s@]+@/g,"$1"),"firstLine"),z=c(async(t,e,a,n)=>{const i=await t(e,a,n);return i.status!==0&&m(L(i,`${e} failed`),502),i.stdout},"checked"),$=c(async(t,e)=>JSON.parse(await z(t,"gh",e)),"ghJSON");async function B(t,e,a){h.lstatSync(p.join(e,".git"),{throwIfNoEntry:!1})?.isDirectory()||m("The clone path must have a real .git metadata directory; symlinks are refused.");const n=await t("git",["-C",e,"rev-parse","--show-toplevel"]);(n.status!==0||p.resolve(n.stdout.trim())!==h.realpathSync(e))&&m("The clone path must be the root of a Git work tree.");const i=await t("git",["-C",e,"remote","get-url","origin"]);(i.status!==0||G(i.stdout)?.toLowerCase()!==a.toLowerCase())&&m(`The clone path origin must be github.com/${a}.`)}c(B,"verifyClone");const j=c((t,e)=>t("git",["-c","credential.helper=",...e],{env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),"publicGit");async function P(t,e,a,n){const i=await t("git",["-C",e,"fetch","--no-tags","origin",`+refs/heads/${n}:refs/remotes/origin/${n}`]);i.status!==0&&m(`Could not fetch branch "${n}" from ${a}: ${L(i,"git fetch failed")}`,502)}c(P,"fetchBranch");function U({run:t=T,base:e=O(),now:a=Date.now}={}){let n,i;const f=new Map,y=c(s=>({github:s.nameWithOwner,private:s.isPrivate,pushedAt:s.pushedAt||"",defaultBranch:s.defaultBranchRef?.name||"",description:s.description||""}),"repoRow"),g=c((s,l)=>{const o=v(s.github,e),r=Object.entries(l.sites||{}).filter(([,u])=>u.github?.toLowerCase()===s.github.toLowerCase()&&typeof u.owner?.repo=="string"&&A(p.resolve(u.owner.repo)).toLowerCase()===A(o).toLowerCase()).map(([u,d])=>({route:u,title:d.title||u}));return{...s,clone:o,cloned:h.lstatSync(p.join(o,".git"),{throwIfNoEntry:!1})?.isDirectory()||!1,shared:r}},"decorate");async function R(s){const l=await j(t,["ls-remote","--symref",`https://github.com/${s}.git`,"HEAD","refs/heads/*"]);if(l.status!==0)return null;const o=l.stdout,r=[...new Set([...o.matchAll(/^[\da-f]+\s+refs\/heads\/(.+)$/gm)].map(d=>d[1]).filter(d=>x(S,d)))],u=/^ref:\s+refs\/heads\/(.+)\s+HEAD$/m.exec(o)?.[1];return{defaultBranch:r.includes(u)?u:r[0]||"",branches:r}}c(R,"remoteBranches");async function I(s){const l=await t("gh",["repo","view",s,"--json","nameWithOwner,isPrivate,description,pushedAt,defaultBranchRef"]);if(l.status===0){const r=JSON.parse(l.stdout);return C(r.nameWithOwner),y(r)}return(await j(t,["ls-remote","--heads",`https://github.com/${s}.git`])).status!==0?null:{github:s,private:!1,pushedAt:"",defaultBranch:"",description:""}}c(I,"find");async function _(){if((await t("gh",["auth","status"])).status!==0)return{signedIn:!1,repos:[]};const l=await $(t,["api","user"]),o=await $(t,["api","user/orgs","--paginate","--slurp"]),r=[...new Set([l.login,...o.flat().map(w=>w.login)])],u=await Promise.all(r.map(w=>$(t,["repo","list",w,"--limit","100000","--json","nameWithOwner,isPrivate,pushedAt,defaultBranchRef,description"]))),d=new Map;for(const w of u.flat())x(C,w.nameWithOwner)&&d.set(w.nameWithOwner.toLowerCase(),y(w));return{signedIn:!0,login:l.login,owners:r,repos:[...d.values()].sort((w,k)=>(k.pushedAt||"").localeCompare(w.pushedAt||"")||w.github.localeCompare(k.github))}}return c(_,"discover"),{path:c(s=>v(s,e),"path"),cloned:c(s=>h.lstatSync(p.join(v(s,e),".git"),{throwIfNoEntry:!1})?.isDirectory()||!1,"cloned"),async list(s={},{fresh:l=!1}={}){return(l||!n||a()-n.at>=6e4)&&(i||=_().then(o=>(n={at:a(),value:o},o)).finally(()=>{i=null}),await i),{...n.value,repos:n.value.repos.map(o=>g(o,s))}},async lookup(s,l={}){const o=W(s);o||m("Repo must be owner/name on GitHub.");const r=o.toLowerCase();let u=f.get(r);if(!u||a()-u.at>=6e4){for(const[w,k]of f)a()-k.at>=6e4&&f.delete(w);u={at:a(),pending:I(o)},f.set(r,u),u.pending.catch(()=>{f.get(r)===u&&f.delete(r)})}const d=await u.pending;return d||m("Not found, or you don't have access.",404),g({...d,listed:!1},l)},async branches(s){C(s);try{const l=await $(t,["api",`repos/${s}`]),o=await $(t,["api",`repos/${s}/branches?per_page=100`,"--paginate","--slurp"]);return{defaultBranch:l.default_branch,branches:o.flat().map(r=>r.name).filter(r=>x(S,r))}}catch(l){const o=await R(s);if(!o)throw l;return o}},async ensure(s,l="main"){const o=v(s,e);return S(l),h.mkdirSync(p.dirname(o),{recursive:!0}),D(p.join(p.resolve(e),".locks",s.toLowerCase()),async()=>{if(v(s,e),h.existsSync(o))return await B(t,o,s),await P(t,o,s,l),o;const r=h.mkdtempSync(p.join(p.resolve(e),".clone-"));try{const u=await t("gh",["repo","clone",s,p.join(r,"repo")]);u.status!==0&&(h.rmSync(p.join(r,"repo"),{recursive:!0,force:!0}),(await j(t,["clone",`https://github.com/${s}.git`,p.join(r,"repo")])).status!==0&&m(L(u,"gh failed"),502)),await B(t,p.join(r,"repo"),s),await P(t,p.join(r,"repo"),s,l),v(s,e),h.renameSync(p.join(r,"repo"),o)}finally{h.rmSync(r,{recursive:!0,force:!0})}return o},{timeout:10*6e4,heartbeat:!0})}}}c(U,"repoService");export{W as githubFromInput,G as githubFromOrigin,Q as repoLookupRoute,v as repoPath,U as repoService,T as runRepo,S as validateBranch,C as validateGithub};
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};
@@ -0,0 +1 @@
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/routes.mjs CHANGED
@@ -1 +1 @@
1
- var r=Object.defineProperty;var o=(e,t)=>r(e,"name",{value:t,configurable:!0});const a=/^[a-z0-9][a-z0-9-]{0,40}$/,c=o(e=>typeof e=="string"&&a.test(e),"validRoute");function p(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,41).replace(/-+$/,"")}o(p,"routeFromName");const s=o((e,t)=>Object.hasOwn(e||{},t)?e[t]:void 0,"routeRecord");export{a as ROUTE_RE,p as routeFromName,s as routeRecord,c as validRoute};
1
+ var n=Object.defineProperty;var t=(e,o)=>n(e,"name",{value:o,configurable:!0});const a=/^[a-z0-9][a-z0-9-]{0,40}$/,p=t(e=>typeof e=="string"&&a.test(e),"validRoute");function r(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,41).replace(/-+$/,"")}t(r,"routeFromName");const s=t((e,o)=>Object.hasOwn(e||{},o)?e[o]:void 0,"routeRecord"),x=t((e,o)=>o&&r(o)===e?o:e,"joinName");export{a as ROUTE_RE,x as joinName,r as routeFromName,s as routeRecord,p as validRoute};
package/hub/schedule.mjs CHANGED
@@ -1 +1 @@
1
- var O=Object.defineProperty;var f=(e,n)=>O(e,"name",{value:n,configurable:!0});const c=Object.freeze({windows:Object.freeze([Object.freeze({from:"08:00",every_minutes:15}),Object.freeze({from:"18:00",every_minutes:30}),Object.freeze({from:"22:00",every_minutes:60})]),hold_overnight:!0,wakes:Object.freeze(["08:00","09:00"]),notifications:Object.freeze({on:!0,weekends_off:!1,snoozed_until:null})}),h="never",w=8,v=8,g=/^([01]\d|2[0-3]):([0-5]\d)$/,k=2*6e4,d=f(e=>{const[n,t]=e.split(":").map(Number);return n*60+t},"minutes"),z=f(e=>e.getHours()*60+e.getMinutes()+e.getSeconds()/60+e.getMilliseconds()/6e4,"minuteOfDay"),l=f((e,n,t=0)=>{const[o,r]=n.split(":").map(Number);return new Date(e.getFullYear(),e.getMonth(),e.getDate()+t,o,r)},"atOn"),_=f((e,n)=>{const t=l(e,n);return t>e?t:l(e,n,1)},"nextAt"),N=f((e,n)=>{const t=l(e,n);return t<=e?t:l(e,n,-1)},"lastAt"),b=f(e=>({windows:e.windows.map(n=>({from:n.from,every_minutes:n.every_minutes})),hold_overnight:e.hold_overnight,wakes:[...e.wakes],notifications:{...e.notifications}}),"copy"),E=30*864e5;function x(e){const n=e?.on??c.notifications.on,t=e?.weekends_off??c.notifications.weekends_off,o=e?.snoozed_until??null;return typeof n!="boolean"?{error:"Notifications must be on or off."}:typeof t!="boolean"?{error:"Off on weekends must be on or off."}:o!==null&&(typeof o!="string"||Number.isNaN(Date.parse(o)))?{error:"Snooze must end at a date and time."}:{notifications:{on:n,weekends_off:t,snoozed_until:o===null?null:new Date(o).toISOString()}}}f(x,"validateNotifications");function S(e){const n=e?.windows,t=e?.hold_overnight??c.hold_overnight,o=e?.wakes??c.wakes,{notifications:r,error:s}=x(e?.notifications);if(s)return{error:s};if(typeof t!="boolean")return{error:"Hold pushes overnight must be on or off."};if(!Array.isArray(o))return{error:"Wake times must be a list of HH:MM times."};if(o.length>v)return{error:`Use at most ${v} wake times.`};for(const[a,u]of o.entries()){if(typeof u!="string"||!g.test(u))return{error:`Wake ${a+1} must be HH:MM (24-hour).`};if(o.indexOf(u)!==a)return{error:`Two wakes are at ${u}; keep one.`}}if(!Array.isArray(n)||!n.length)return{error:"Add at least one window."};if(n.length>w)return{error:`Use at most ${w} windows.`};const i=[];for(const[a,u]of n.entries()){if(typeof u?.from!="string"||!g.test(u.from))return{error:`Window ${a+1}'s start must be HH:MM (24-hour).`};const m=Number(u.every_minutes);if(u.every_minutes===""||u.every_minutes==null||!Number.isInteger(m)||m<5||m>120)return{error:`Window ${a+1}'s interval must be a whole number of minutes from 5 to 120.`};if(i.some(D=>D.from===u.from))return{error:`Two windows start at ${u.from}; give each its own start.`};i.push({from:u.from,every_minutes:m})}return{settings:{windows:i.sort((a,u)=>d(a.from)-d(u.from)),hold_overnight:t,wakes:[...o].sort((a,u)=>d(a)-d(u)),notifications:r}}}f(S,"validate");function T(e){const n=e?.immediate?.start,t=e?.immediate?.end,o=e?.bundle?.until;if(![n,t,o].every(a=>typeof a=="string"&&g.test(a)))return null;const r=Number(e.bundle.every_minutes),s=[{from:n,every_minutes:c.windows[0].every_minutes}];t!==n&&o!==t&&s.push({from:t,every_minutes:Number.isInteger(r)?r:c.windows[1].every_minutes});const i=o===t?t:o;return i!==n&&!s.some(a=>a.from===i)&&s.push({from:i,every_minutes:c.windows[2].every_minutes}),S({windows:s,hold_overnight:o!==n}).settings||null}f(T,"fromPush");function X(e){const n=x(e?.notifications).notifications||b(c).notifications,t=f(o=>o&&{...o,notifications:n},"withThem");return S({...e?.polling,notifications:n}).settings||t(T(e?.push))||t(b(c))}f(X,"pollingOf");function p(e,n){const t=n.windows,o=z(e);let r=t.length-1;for(let a=0;a<t.length;a++)d(t[a].from)<=o&&(r=a);const s=t[r],i=t[(r+1)%t.length];return{from:s.from,every_minutes:s.every_minutes,startedAt:N(e,s.from),endsAt:_(e,i.from)}}f(p,"windowAt");function y(e,n){const t=e.windows;if(t.length===1)return 1440;const o=d(t[(n+1)%t.length].from)-d(t[n].from);return o>0?o:o+1440}f(y,"windowSpan");const H=f((e,n)=>Math.ceil(y(e,n)/e.windows[n].every_minutes),"checksIn"),Z=f(e=>e.windows.reduce((n,t,o)=>n+H(e,o),0),"checksADay"),A=f(e=>e.hold_overnight&&e.windows.length>1,"holdsOvernight");function K(e){const n=e.windows.length-1;return e.windows.flatMap((t,o)=>{const r=d(t.from),s=r+y(e,o),i=A(e)&&o===n;return e.windows.length===1?[{window:o,start:0,end:1440,held:i}]:s<=1440?[{window:o,start:r,end:s,held:i}]:[{window:o,start:r,end:1440,held:i},{window:o,start:0,end:s-1440,held:i}]})}f(K,"daySegments");function j(e,n){if(e.windows.length>=w)return null;const t=d(e.windows[n].from),o=y(e,n),r=Math.round((t+o/2)/15)*15;if(r<=t||r>=t+o)return null;const s=r%1440;return`${String(Math.floor(s/60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`}f(j,"splitPoint");function Y(e,{op:n,w:t,value:o}){const r=e.windows.map(u=>({from:u.from,every_minutes:u.every_minutes})),s={windows:r,hold_overnight:e.hold_overnight,wakes:[...e.wakes]},i=r.findIndex(u=>u.from===t);if(["from","every","split","remove"].includes(n)&&i<0)return{error:"That window has changed. Pick it again on the bar."};const a=i<0?e.windows[0].from:t;switch(n){case"from":return r[i].from=o,{input:s,select:o};case"every":return r[i].every_minutes=o,{input:s,select:a};case"split":{const u=j(e,i);return u?(r.push({from:u,every_minutes:r[i].every_minutes}),{input:s,select:u}):{error:r.length>=w?`Use at most ${w} windows.`:"This window is too short to split."}}case"remove":{if(r.length<2)return{error:"Keep at least one window."};const u=r[(i-1+r.length)%r.length].from;return r.splice(i,1),{input:s,select:u}}case"hold":return s.hold_overnight=o==="on",{input:s,select:a};case"wake-add":return s.wakes.push(o),{input:s,select:a};case"wake-remove":return s.wakes=s.wakes.filter(u=>u!==o),{input:s,select:a};default:return{error:"That change is not one the Polling modal makes."}}}f(Y,"editPolling");function I(e,n){if(!A(n))return!1;const t=p(e,n);return t.from===n.windows.at(-1).from&&e-t.startedAt>k}f(I,"holdsPushes");function M(e,n){if(!n.notifications?.weekends_off)return null;const[t,o]=[n.windows[0].from,n.windows.at(-1).from];let r=l(e,o,-((e.getDay()-5+7)%7));r>e&&(r=l(r,o,-7));const s=l(r,t,3);return e-r>k&&e<s?s:null}f(M,"weekendEnd");function W(e,n){if(n.notifications?.on===!1)return{until:h,why:"off"};const t=n.notifications?.snoozed_until?new Date(n.notifications.snoozed_until):null,o=f(i=>(t>i?["snoozed",t]:null)||M(i,n)&&["weekend",M(i,n)]||I(i,n)&&["overnight",p(i,n).endsAt],"at"),r=o(e);if(!r)return null;let s=r[1];for(let i=o(s),a=0;i&&a<8;i=o(s),a++)s=i[1];return{until:s,why:r[0]}}f(W,"hold");function P(e,n){return W(e,n)?.until??null}f(P,"heldUntil");function C(e,n){let t=$(e,n);for(let o=0;o<8;o++){const r=P(t,n);if(r===h)return h;if(!r)return t;t=$(new Date(r.getTime()-1),n)}return t}f(C,"flushAt");const U=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})?$/;function G(e,n,t){const o=String(n),[r,s]=[t.windows[0].from,t.windows.length];let i;if(o==="morning")i=_(e,r);else if(o==="tonight")i=s>1?_(e,t.windows[Math.max(1,s-2)].from):null;else if(o==="monday")i=l(e,r,(8-e.getDay())%7),i<=e&&(i=l(i,r,7));else if(U.test(o))i=new Date(o);else{const a=/^([1-9]\d{0,3})([mhdw])$/.exec(o);if(!a)return null;const u=Number(a[1]);i=new Date(e.getTime()+u*{m:6e4,h:36e5,d:864e5,w:7*864e5}[a[2]])}return i&&i>e&&i-e<=E?i:null}f(G,"snoozeEnd");function V(e,n=new Date){if(e.why==="off")return"notifications are off";const t=R(e.until,n);return e.why==="snoozed"?`snoozed until ${t}`:e.why==="weekend"?`held for the weekend until ${t}`:`held overnight until ${t}`}f(V,"holdLine");function $(e,n){const t=p(e,n),o=t.every_minutes*6e4,r=new Date(t.startedAt.getTime()+(Math.floor((e-t.startedAt)/o)+1)*o);return r<t.endsAt?r:t.endsAt}f($,"nextSlot");function F(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}f(F,"localDay");function q(e,n,t={}){const o=F(e);return n.wakes.filter(r=>l(e,r)<=e&&t?.[r]!==o)}f(q,"wakesDue");function B(e){const n=new Map;return e.forEach((t,o)=>{t.tag&&n.set(t.tag,o)}),e.filter((t,o)=>!t.tag||n.get(t.tag)===o).map(t=>({id:t.id,title:t.title,body:t.body||"",url:t.url||"/",tag:t.tag||void 0}))}f(B,"notifications");function R(e,n=new Date){const t=e.getHours(),o=`${t%12||12}:${String(e.getMinutes()).padStart(2,"0")}${t<12?"am":"pm"}`,r=Math.round((l(e,"00:00")-l(n,"00:00"))/864e5);return r===0?o:r===1?`${o} tomorrow`:`${o} ${e.toDateString().slice(0,10)}`}f(R,"clock");export{c as DEFAULTS,h as NEVER,Z as checksADay,H as checksIn,R as clock,K as daySegments,Y as editPolling,C as flushAt,T as fromPush,P as heldUntil,W as hold,V as holdLine,A as holdsOvernight,I as holdsPushes,F as localDay,$ as nextSlot,B as notifications,X as pollingOf,G as snoozeEnd,j as splitPoint,S as validate,q as wakesDue,p as windowAt,y as windowSpan};
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 K=Object.defineProperty;var c=(e,s)=>K(e,"name",{value:s,configurable:!0});import O from"node:fs";import h from"node:path";import j from"node:os";import{spawn as D}from"node:child_process";import{fileURLToPath as F}from"node:url";import{routeRecord as m,validRoute as J}from"./routes.mjs";import{withFileLock as W}from"./locks.mjs";import{RESUME_STATE as C,carryCursor as H,hubBoard as Q,isListening as q,listBoards as P,oldestUnheard as Y,readManifest as $,readJSON as z,saveJSON as V,watchedCounts as X,watchedLines as Z,watcherCursor as ee,withManifestLock as se,writeManifest as te}from"./boards.mjs";import{readUsageGate as oe,heldUsageEvent as ne}from"../shared/usage-gate.mjs";import{liveSessions as y,sessionRecords as re,processStarts as ie,verifiedProcess as ae}from"./live.mjs";import{deliver as ce}from"./push.mjs";import{WAIT_MS as de}from"./prompts.mjs";import{storedPath as U}from"../bin/install.mjs";const v=U(h.resolve(h.dirname(F(import.meta.url)),"..")),ue=3*6e4,le=5*6e4,fe=15*6e4;function Me(e,s=Date.now()){return Object.entries(e.starting||{}).filter(([t])=>!m(e.sites,t)).map(([t,o])=>{const i=o.asked_at||o.since;return{route:t,title:o.title||o.label||t,repo:o.repo,...o.phase?{phase:o.phase}:{},askedAt:i,failed:!!o.error||s-Date.parse(i)>=fe,...o.error?{error:o.error}:{}}})}c(Me,"startingBoards");const pe=de/1e3+60,me=JSON.stringify({worktree:{bgIsolation:"none"},hooks:{PermissionRequest:[{matcher:"*",hooks:[{type:"command",command:`"${process.execPath}" "${h.join(v,"hub","permission-hook.mjs")}"`,timeout:pe}]}]}});class l extends Error{static{c(this,"SessionError")}constructor(s,t){super(s),this.reason=t}}function he(e,s){if(!J(e))throw new l("Choose a board route.","none");return W(h.join(j.homedir(),".claude","kickflip","session-locks",e),()=>s({resume:c(t=>Te(e,t),"resume")}),{staleAfter:12e4,timeout:9e4})}c(he,"withSessionLock");function S(){if(process.env.KICKFLIP_CLAUDE)return process.env.KICKFLIP_CLAUDE;const e=h.join(j.homedir(),".local","bin","claude");return O.existsSync(e)?e:"claude"}c(S,"claudeBin");const R=c(e=>e==="CLAUDECODE"||e==="CLAUDE_PID"||e==="CLAUDE_EFFORT"||e.startsWith("CLAUDE_CODE_"),"inherited");function E(e,{cwd:s,timeout:t=6e4}){const o=S(),i=Object.fromEntries(Object.entries(process.env).filter(([n])=>!R(n)));return i.CLAUDE_BG_ISOLATION="none",h.isAbsolute(o)&&(i.PATH=`${h.dirname(o)}:${i.PATH||""}`),new Promise(n=>{let u="",d="",r;try{r=D(o,e,{cwd:s,env:i,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(a){n({status:1,stdout:u,stderr:a.message});return}const f=c(a=>{clearTimeout(p),r.stdout.destroy(),r.stderr.destroy(),n({status:a,stdout:u,stderr:d})},"done"),p=setTimeout(()=>{try{r.kill("SIGKILL")}catch{}f(1)},t);r.stdout.on("data",a=>{u+=a}),r.stderr.on("data",a=>{d+=a}),r.on("error",a=>{d+=a.message,f(1)}),r.on("close",a=>f(a??1)),r.on("exit",a=>setTimeout(()=>f(a??1),300)),r.unref()})}c(E,"runClaude");async function we(e,{cwd:s,run:t=E,starts:o=ie,signal:i=process.kill}={}){if(e.kind==="bg"){const n=await t(["stop",e.jobId||e.sessionId.slice(0,8)],{cwd:s,timeout:8e3});if(n.status!==0)throw new l(`claude stop failed: ${(n.stderr||n.stdout).trim().slice(0,300)}`,"failed")}else{if(!ae(e,o))throw new l(`Cannot verify session ${e.sessionId}'s process identity; refusing to signal pid ${e.pid}.`,"failed");i(e.pid,"SIGTERM")}}c(we,"runSessionStop");async function Ke(e,{live:s=y,stop:t=we}={}){if(!e?.session)return;const o=s().get(e.session);if(!o)return;await t(o,{cwd:e.repo||o.cwd||j.homedir()});const i=Date.now()+5e3;for(;s().get(e.session)?.pid===o.pid;){if(Date.now()>=i)throw new l(`session ${e.session} did not stop`,"failed");await new Promise(n=>setTimeout(n,100))}}c(Ke,"stopSession");function ge(e,{cwd:s}){const t=Object.fromEntries(Object.entries(process.env).filter(([n])=>!R(n)&&n!=="CLAUDE_BG_ISOLATION")),o=c(()=>{},"ignore");process.on("SIGINT",o).on("SIGQUIT",o);const i=c(()=>process.off("SIGINT",o).off("SIGQUIT",o),"settle");return new Promise((n,u)=>{const d=D(S(),e,{cwd:s,env:t,stdio:"inherit"});d.on("error",r=>{i(),u(new l(r.message,"failed"))}),d.on("close",r=>{i(),n({status:r??1})})})}c(ge,"runForegroundClaude");const N=c(({name:e,model:s})=>["--name",e,"--permission-mode","auto","--settings",me,...s?["--model",s]:[]],"common"),be=c(({route:e,name:s,model:t,prompt:o})=>["--bg",...N({name:s,model:t}),`/kickflip ${e}${o?` ${o}`:""}`],"startArgv"),$e=c((e,s)=>`The hub resumed this session because /${e} had nobody listening. Rejoin the board as session ${s} (kickflip steps 3 and 5): rerun \`node ${h.join(v,"bin","kickflip.mjs")} join ${e} --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"),ke=c(({id:e,route:s,name:t,model:o,background:i})=>["--resume",e,"--bg",...i?[]:N({name:t,model:o}),$e(s,e)],"resumeArgv"),B=c(e=>`You are the hub session. Read \`${h.join(v,"docs","hub-session.md")}\`, then rejoin /${e} and relaunch its watcher.`,"hubPrompt"),ye=c(({route:e,id:s,model:t})=>[...s?["--resume",s]:[],...t?["--model",t]:[],s?`${B(e)} If your session id (the folder above your scratchpad) isn't ${s}, rejoin with yours and --force.`:`/kickflip ${e} --hub
2
- ${B(e)}`],"hubArgv");async function Fe({manifest:e=$(),repo:s,run:t=ge,live:o=y}={}){const i=Q(e);if(!i)throw new l("No hub board is flagged; flag one with kickflip set <route> --hub, or join one with kickflip join hub-orchestrator --template board --hub --session <id>","hub");const n=i.owner?.session?i.owner:null;if(n&&!n.repo&&!s)throw new l(`/${i.route}'s session ${n.session} has no folder recorded; pass --repo <its folder>`,"none");x(n,o);const u=n?.repo||h.resolve(s||process.cwd());if(!O.statSync(u,{throwIfNoEntry:!1})?.isDirectory())throw new l(n?.repo?`/${i.route}'s recorded folder ${u} is gone; rejoin from its new folder with --repo`:`no folder at ${u}`,"none");return t(ye({route:i.route,id:n?.session,model:n?.model}),{cwd:u})}c(Fe,"hubSession");function A(e,s){const t=m(e?.sites,s),o=t?.owner?.session?t.owner:m(e?.starting,s);return o?.session?{...o,title:t?.title||s}:null}c(A,"sessionOf");async function G(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 o=0;o<20;o++){const i=re().find(n=>n.jobId===t||n.sessionId.startsWith(t));if(i)return{session:i.sessionId,confirmed:!0};await new Promise(n=>setTimeout(n,500))}return{session:s,confirmed:!1}}c(G,"startedId");async function Ie(e,{run:s,cwd:t}){const o=await s(["agents","--json","--all"],{cwd:t});try{return JSON.parse(o.stdout).some(i=>i?.sessionId===e&&i.kind==="background")}catch{return!1}}c(Ie,"isBackground");function x(e,s){const t=e&&s().get(e.session);if(t)throw new l(`session ${e.session} is live (${t.kind==="bg"?"in the background":"in a terminal"}, pid ${t.pid}); it gets no second process`,"live")}c(x,"refuseLive");async function Se(e,{from:s,to:t,mark:o}){await se(async()=>{const i=$(),n=P(i).find(d=>d.route===e);if(n?.owner?.session===s&&(o||t!==s)&&H(n,{from:s,to:t,mark:o}),t===s)return;const u=m(i.sites,e);if(u?.owner?.session===s)Object.assign(u,{owner:{...u.owner,session:t},updated:new Date().toISOString()});else if(m(i.starting,e)?.session===s)i.starting[e]={...m(i.starting,e),session:t};else return;await te(i)})}c(Se,"moveOwner");async function Je(e,{manifest:s=$(),repo:t,model:o,prompt:i,run:n=E,live:u=y}={}){if(m(s.closed,e))throw new l(`/${e} is closed; use kickflip reopen ${e}`,"none");const d=A(s,e);x(d,u);const r=h.resolve(t||d?.repo||process.cwd());if(!O.statSync(r,{throwIfNoEntry:!1})?.isDirectory())throw new l(`no folder at ${r}`,"none");const f=m(s?.sites,e)?.title||m(s?.starting,e)?.title||e,p=be({route:e,name:f,model:o||d?.model,prompt:i}),a=await n(p,{cwd:r});if(a.status!==0)throw new l(`claude --bg failed (${a.status}): ${(a.stderr||a.stdout).trim().slice(0,300)}`,"failed");const{session:g,confirmed:k}=await G(a.stdout);if(!g)throw new l(`claude --bg started a session but no session record names it yet; find it with claude agents (${a.stdout.trim().slice(0,300)})`,"failed");return{route:e,session:g,confirmed:k,repo:U(r),model:o||d?.model||null,name:f,argv:[S(),...p],output:a.stdout.trim()}}c(Je,"startSession");function _e(e,s={}){return he(e,({resume:t})=>t(s))}c(_e,"resumeSession");async function Te(e,{manifest:s=$(),run:t=E,live:o=y,mark:i=null}={}){if(m($().closed,e))throw new l(`/${e} is closed; use kickflip reopen ${e}`,"none");const n=A(s,e);if(!n)throw new l(`/${e} has no recorded session`,"none");if(!n.repo)throw new l(`/${e}'s session ${n.session} has no folder recorded; its session records one by rejoining (kickflip join, --repo)`,"none");x(n,o);const u=await Ie(n.session,{run:t,cwd:n.repo}),d=ke({id:n.session,route:e,name:n.title,model:n.model,background:u}),r=await t(d,{cwd:n.repo});if(r.status!==0)throw new l(`claude --resume failed (${r.status}): ${(r.stderr||r.stdout).trim().slice(0,300)}`,"failed");const{session:f,confirmed:p}=await G(r.stdout,n.session);return await Se(e,{from:n.session,to:f,mark:i}),{route:e,session:f,previous:n.session,confirmed:p,repo:n.repo,argv:[S(),...d],output:r.stdout.trim()}}c(Te,"resumeRecordedSession");function Oe(e,{listening:s,live:t,recorded:o,counts:i,waiting:n,now:u}){if(s)return{action:"none",entry:null};const d=new Date(u).toISOString(),r=e?{...e}:{down_since:d};return t?delete r.mark:!r.mark&&i&&(r.mark=i),r.pushed_at?{action:"none",entry:r}:r.resumed_at?r.error||u-Date.parse(r.resumed_at)>=le?{action:"push",entry:{...r,pushed_at:d}}:{action:"none",entry:r}:!o||t?{action:"none",entry:r}:!!(e?.mark&&i&&Object.entries(i).some(([p,a])=>a>(m(e.mark,p)??0)))||n&&u-Date.parse(r.down_since)>=ue?{action:"resume",entry:{...r,resumed_at:d}}:{action:"none",entry:r}}c(Oe,"resumeStep");async function We({manifest:e=$(),now:s=new Date,live:t=y,listening:o=c((d,r)=>q(d,{now:s.getTime(),running:r}),"listening"),resume:i=c((d,r)=>_e(d,{manifest:e,live:t,mark:r}),"resume"),push:n=ce,gate:u=oe({now:s})}={}){const d=z(C,{}),r=t(),f=Object.create(null),p={resumed:[],pushed:[],failed:[]};for(const a of P(e)){const g=A(e,a.route),k=!!(g&&r.has(g.session)),_=o(a,r);let{action:I,entry:w}=Oe(m(d,a.route),{listening:_,live:k,recorded:!!g?.repo,now:s.getTime(),counts:_?null:X(a),waiting:!_&&!k&&Y(a)!==null});if(I==="resume"&&u.state==="paused"){const b=m(d,a.route)?.mark||ee(a);Object.entries(Z(a)).flatMap(([T,M])=>M.slice(m(b,T)||0)).some(T=>!ne(T))||(I="none",delete w.resumed_at)}if(I==="resume")try{await i(a.route,w.mark),p.resumed.push(a.route)}catch(b){w={...w,error:b.message},p.failed.push(`${a.route}: could not resume its session (${b.message})`)}else if(I==="push"){const b=w.error?`The hub couldn't resume it: ${w.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 ${a.route}, or claude agents.`;try{await n({title:`${a.title}'s session didn't come back`,body:b,url:`/${a.route}/`,tag:`resume-${a.route}`},{kind:"fault",immediate:!0,at:s}),p.pushed.push(a.route)}catch(L){w={...w,pushed_at:void 0},p.failed.push(`${a.route}: could not push that its session didn't come back (${L.message})`)}}w&&(f[a.route]=w)}return JSON.stringify(f)!==JSON.stringify(d)&&V(C,f),p}c(We,"checkSessions");export{me as BG_SETTINGS,le as COMEBACK_WAIT,pe as PROMPT_HOOK_TIMEOUT_S,ue as RESUME_AFTER,fe as STARTING_WAIT,l as SessionError,We as checkSessions,S as claudeBin,ye as hubArgv,Fe as hubSession,ke as resumeArgv,$e as resumePrompt,_e as resumeSession,Oe as resumeStep,E as runClaude,ge as runForegroundClaude,we as runSessionStop,A as sessionOf,be as startArgv,Je as startSession,Me as startingBoards,Ke as stopSession,he as withSessionLock};
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/shell.mjs CHANGED
@@ -1 +1,2 @@
1
- var h=Object.defineProperty;var s=(t,o)=>h(t,"name",{value:o,configurable:!0});import u from"node:fs";import i from"node:path";import{fileURLToPath as b}from"node:url";const f=i.dirname(b(import.meta.url)),p=i.join(f,"..","board","public"),m=[p,i.join(f,"..","starter","public")],_=i.join(f,"..","shared","colors.css"),A=new Set(["","settings.html","questions.html","notes.html"]),d=s(t=>t===""||t.endsWith("/")||/\.html?$/.test(t),"isPagePath"),S=new Set(["/","/_hub/","/_hub/settings","/_hub/settings/polling"]),E=s(t=>t["x-app-shell"]==="1"?"document":t["sec-fetch-dest"],"destOf");function O({method:t="GET",pathname:o="/",search:e="",dest:l,sites:c=new Set}){if(S.has(o))return t==="GET"||t==="HEAD"?"shell":"hub";if(o==="/_hub"||o.startsWith("/_hub/")||o==="/sw.js"||o==="/manifest.webmanifest"||o==="/favicon.ico")return"hub";if(t!=="GET"||l!=="document"||new URLSearchParams(e).has("alone"))return"forward";const r=/^\/([^/]+)\/(.*)$/.exec(o);let n=null;try{n=r?decodeURIComponent(r[1]):null}catch{n=null}return r&&/^try(?:\/|$)/.test(r[2])?"forward":n!==null&&c.has(n)&&d(r[2])?"shell":"forward"}s(O,"pageOf");function g(t,o){return t.replace(/\b(src|href)="\/_hub\/app\/([\w.-]+\.(?:js|css))"/g,(e,l,c)=>{const r=o(c);return r?`${l}="/_hub/app/${c}?v=${r}"`:e})}s(g,"versionAppAssets");function w(t){if(!/^[\w.-]+\.(?:js|css|png)$/.test(t))return null;for(const o of m){const e=i.join(o,t);try{if(u.statSync(e).isFile())return e}catch{}}return null}s(w,"appFile");const a=s(t=>{try{const o=u.statSync(t);return`${Math.floor(o.mtimeMs).toString(36)}-${o.size.toString(36)}`}catch{return null}},"fileVersion"),x=s(()=>a(_)||"0","colorsVersion");function R({sidebar:t="",sidebarData:o="null",touchIcon:e="/_hub/icon-180.png"}={}){const l=g(u.readFileSync(i.join(p,"app.html"),"utf8"),r=>{const n=w(r);return n&&a(n)}),c={sidebar:t,sidebarData:o,touchIcon:e,colorsVersion:x()};return l.replace(/\{\{(sidebar|sidebarData|touchIcon|colorsVersion)\}\}/g,(r,n)=>c[n])}s(R,"shellHtml");export{p as BOARD_PUBLIC,A as VIEW_PAGES,w as appFile,x as colorsVersion,E as destOf,a as fileVersion,O as pageOf,R as shellHtml,g as versionAppAssets};
1
+ var d=Object.defineProperty;var s=(t,o)=>d(t,"name",{value:o,configurable:!0});import _ from"node:crypto";import a from"node:fs";import l from"node:path";import{fileURLToPath as g}from"node:url";const f=l.dirname(g(import.meta.url)),b=l.join(f,"..","board","public"),S=[b,l.join(f,"..","starter","public")],x=l.join(f,"..","shared","colors.css"),U=new Set(["","settings.html","questions.html","notes.html"]),w=s(t=>t===""||t.endsWith("/")||/\.html?$/.test(t),"isPagePath"),$=new Set(["/","/_hub/","/_hub/settings","/_hub/settings/polling"]),G=s(t=>t["x-app-shell"]==="1"?"document":t["sec-fetch-dest"],"destOf");function H({method:t="GET",pathname:o="/",search:n="",dest:e,sites:c=new Set}){if($.has(o))return t==="GET"||t==="HEAD"?"shell":"hub";if(o==="/_hub"||o.startsWith("/_hub/")||o==="/sw.js"||o==="/manifest.webmanifest"||o==="/favicon.ico")return"hub";if(t!=="GET"||e!=="document"||new URLSearchParams(n).has("alone"))return"forward";const r=/^\/([^/]+)\/(.*)$/.exec(o);let i=null;try{i=r?decodeURIComponent(r[1]):null}catch{i=null}return i!==null&&c.has(i)&&w(r[2])?"shell":"forward"}s(H,"pageOf");function j(t,o){return t.replace(/\b(src|href)="\/_hub\/app\/([\w.-]+\.(?:js|css))"/g,(n,e,c)=>{const r=o(c);return r?`${e}="/_hub/app/${c}?v=${r}"`:n})}s(j,"versionAppAssets");function P(t){if(!/^[\w.-]+\.(?:js|css|png)$/.test(t))return null;for(const o of S){const n=l.join(o,t);try{if(a.statSync(n).isFile())return n}catch{}}return null}s(P,"appFile");const m=s(t=>{try{const o=a.statSync(t);return`${Math.floor(o.mtimeMs).toString(36)}-${o.size.toString(36)}`}catch{return null}},"fileVersion"),y=s(()=>m(x)||"0","colorsVersion");function I({sidebar:t="",sidebarData:o="null",touchIcon:n="/_hub/icon-180.png"}={}){const e=[],c=j(a.readFileSync(l.join(b,"app.html"),"utf8"),p=>{const u=P(p),h=u&&m(u);return e.push(`${p} ${h}`),h}),r=_.createHash("sha1").update(e.join(`
2
+ `)).digest("base64url").slice(0,16),i={sidebar:t,sidebarData:o,touchIcon:n,colorsVersion:y(),build:r};return c.replace(/\{\{(sidebar|sidebarData|touchIcon|colorsVersion|build)\}\}/g,(p,u)=>i[u])}s(I,"shellHtml");export{b as BOARD_PUBLIC,U as VIEW_PAGES,P as appFile,y as colorsVersion,G as destOf,m as fileVersion,H as pageOf,I as shellHtml,j as versionAppAssets};
package/hub/slack.mjs ADDED
@@ -0,0 +1,2 @@
1
+ var w=Object.defineProperty;var n=(r,t)=>w(r,"name",{value:t,configurable:!0});import o from"node:fs";import s from"node:path";import m from"node:os";import{withFileLock as h}from"./locks.mjs";const i=["self_dm","owner_slack_user","slack_domain","timezone"],a=n(()=>s.join(m.homedir(),".claude","kickflip","slack.json"),"fileOf"),c=n(r=>{try{return JSON.parse(o.readFileSync(r,"utf8"))||{}}catch{return{}}},"read"),d=n(r=>Object.fromEntries(i.map(t=>[t,typeof r?.[t]=="string"?r[t]:""])),"identityOf");function f(r){const t=a();o.mkdirSync(s.dirname(t),{recursive:!0});const e=`${t}.${process.pid}.tmp`;return o.writeFileSync(e,JSON.stringify(r,null,2)+`
2
+ `,{mode:384}),o.chmodSync(e,384),o.renameSync(e,t),r}n(f,"save");function l(){const r=d(c(a()));if(i.some(e=>r[e]))return r;const t=d(c(s.join(m.homedir(),".claude","slack-bridge","state.json")).config);return i.some(e=>t[e])?f(t):r}n(l,"readSlack");async function $(r){for(const[t,e]of Object.entries(r)){if(!i.includes(t)||typeof e!="string")throw new Error(`Unknown Slack setting ${t}`);if(t==="self_dm"&&e&&!/^D[A-Z0-9]+$/.test(e))throw new Error("self-dm must be a DM channel id");if(t==="owner_slack_user"&&e&&!/^U[A-Z0-9]+$/.test(e))throw new Error("user must be a Slack user id");if(t==="slack_domain"&&e&&!/^[a-z0-9][a-z0-9-]*$/.test(e))throw new Error("domain must be a Slack workspace domain");if(t==="timezone"&&e)try{new Intl.DateTimeFormat("en",{timeZone:e})}catch{throw new Error("timezone must be an IANA timezone such as Area/City")}}return h(a(),()=>f({...l(),...r}))}n($,"setSlack");function z(r=new Date){const t=l().timezone||Intl.DateTimeFormat().resolvedOptions().timeZone,e=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",hourCycle:"h23"}).formatToParts(r).map(({type:u,value:p})=>[u,p]));return{date:`${e.year}-${e.month}-${e.day}`,morning:!["Sat","Sun"].includes(e.weekday)&&Number(e.hour)>=9}}n(z,"slackDay");export{l as readSlack,$ as setSlack,z as slackDay};
package/hub/stream.mjs CHANGED
@@ -1,19 +1,19 @@
1
- var j=Object.defineProperty;var n=(m,g)=>j(m,"name",{value:g,configurable:!0});import C from"node:http";function A({targets:m,sidebar:g,retryMs:q=2e3,sidebarMs:x=15e3,pingMs:z=25e3,settleMs:I=300,log:b=n(()=>{},"log")}){const o=new Set,a=new Map,w=new Set;let f=null,v=[],d=new Set,l=null;const u=n((e,t=o)=>{for(const r of t)r.write(e)},"write"),O=n((e,t)=>`event: ${e}
2
- data: ${JSON.stringify(t)}
1
+ var F=Object.defineProperty;var r=(w,g)=>F(w,"name",{value:g,configurable:!0});import W from"node:http";import A from"node:fs";import B from"node:path";function P({targets:w,watched:g=r(()=>[],"watched"),sidebar:I,retryMs:O=2e3,sidebarMs:j=15e3,pingMs:H=25e3,settleMs:M=300,log:v=r(()=>{},"log")}){const o=new Set,a=new Map,c=new Map,S=new Set;let l=null,y=[],u=new Set,d=null;const h=r((t,e=o)=>{for(const n of e)n.write(t)},"write"),T=r((t,e)=>`event: ${t}
2
+ data: ${JSON.stringify(e)}
3
3
 
4
- `,"event");async function h(e=[]){let t;try{t=await g({fresh:new Set(e)})}catch(s){b(`sidebar for the stream failed: ${s.message}`);return}const r=JSON.stringify(t);r!==f&&(f=r,u(`event: sidebar
5
- data: ${r}
4
+ `,"event");async function m(t=[]){let e;try{e=await I({fresh:new Set(t)})}catch(i){v(`sidebar for the stream failed: ${i.message}`);return}const n=JSON.stringify(e);n!==l&&(l=n,h(`event: sidebar
5
+ data: ${n}
6
6
 
7
- `))}n(h,"refreshSidebar");function H(e){d.add(e),!l&&(l=setTimeout(()=>{l=null;const t=[...d];d=new Set,h(t)},I))}n(H,"sidebarSoon");function S(e){u(O("change",{route:e})),H(e)}n(S,"changed");function T(e,t){const r={port:t,req:null};a.set(e,r);const s=n(()=>{a.get(e)===r&&a.delete(e),r.req?.destroy()},"drop");r.req=C.get({host:"127.0.0.1",port:t,path:"/api/stream",headers:{accept:"text/event-stream"}},i=>{if(i.statusCode!==200){i.resume(),s();return}w.has(e)&&S(e),w.add(e),i.setEncoding("utf8");let c="";i.on("data",N=>{c+=N.replace(/\r\n/g,`
8
- `);for(let p=c.indexOf(`
7
+ `))}r(m,"refreshSidebar");function $(t){t&&u.add(t),!d&&(d=setTimeout(()=>{d=null;const e=[...u];u=new Set,m(e)},M))}r($,"sidebarSoon");function b(t){h(T("change",{route:t})),$(t)}r(b,"changed");function _(t,e){const n={port:e,req:null};a.set(t,n);const i=r(()=>{a.get(t)===n&&a.delete(t),n.req?.destroy()},"drop");n.req=W.get({host:"127.0.0.1",port:e,path:"/api/stream",headers:{accept:"text/event-stream"}},s=>{if(s.statusCode!==200){s.resume(),i();return}S.has(t)&&b(t),S.add(t),s.setEncoding("utf8");let f="";s.on("data",C=>{f+=C.replace(/\r\n/g,`
8
+ `);for(let p=f.indexOf(`
9
9
 
10
- `);p>=0;p=c.indexOf(`
10
+ `);p>=0;p=f.indexOf(`
11
11
 
12
- `)){const _=c.slice(0,p);c=c.slice(p+2),/^event: ?change$/m.test(_)&&S(e)}}),i.on("close",s),i.on("error",s)}),r.req.on("error",s)}n(T,"connect");function y(){let e;try{e=new Map(m().map(t=>[t.route,t.port]))}catch(t){b(`stream targets failed: ${t.message}`);return}for(const[t,r]of a)e.get(t)!==r.port&&(a.delete(t),r.req?.destroy());for(const[t,r]of e)a.has(t)||T(t,r)}n(y,"reconcile");function k(){y(),v=[setInterval(y,q),setInterval(()=>h(),x),setInterval(()=>u(`: ping
12
+ `)){const E=f.slice(0,p);f=f.slice(p+2),/^event: ?change$/m.test(E)&&b(t)}}),s.on("close",i),s.on("error",i)}),n.req.on("error",i)}r(_,"connect");function q(){let t;try{t=new Map(w().map(e=>[e.route,e.port]))}catch(e){v(`stream targets failed: ${e.message}`);return}for(const[e,n]of a)t.get(e)!==n.port&&(a.delete(e),n.req?.destroy());for(const[e,n]of t)a.has(e)||_(e,n)}r(q,"reconcile");function x(){let t;try{t=new Set(g().map(e=>e.dir))}catch(e){v(`stream watched failed: ${e.message}`);return}for(const[e,n]of c)t.has(e)||(n.close(),c.delete(e));for(const e of t)if(!c.has(e))try{const n=A.watch(B.join(e,"data"),(i,s)=>{s==="watcher.json"&&$()});n.on("error",()=>{n.close(),c.delete(e)}),c.set(e,n)}catch{}}r(x,"watchWatchers");function k(){q(),x(),y=[setInterval(()=>{q(),x()},O),setInterval(()=>m(),j),setInterval(()=>h(`: ping
13
13
 
14
- `),z)]}n(k,"startHolding");function $(){for(const e of v)clearInterval(e);v=[],clearTimeout(l),l=null,d=new Set;for(const e of a.values())e.req?.destroy();a.clear(),w.clear(),f=null}n($,"stopHolding");function J(e,t){t.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive"}),t.write(`retry: 3000
14
+ `),H)]}r(k,"startHolding");function z(){for(const t of y)clearInterval(t);y=[],clearTimeout(d),d=null,u=new Set;for(const t of a.values())t.req?.destroy();a.clear();for(const t of c.values())t.close();c.clear(),S.clear(),l=null}r(z,"stopHolding");function J(t,e){e.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive"}),e.write(`retry: 3000
15
15
 
16
- `),o.add(t),o.size===1&&k(),f?u(`event: sidebar
17
- data: ${f}
16
+ `),o.add(e),o.size===1&&k(),l?h(`event: sidebar
17
+ data: ${l}
18
18
 
19
- `,[t]):h(),e.on("close",()=>{o.delete(t),o.size||$()})}n(J,"handle");function M(){for(const e of o)e.end();o.clear(),$()}return n(M,"close"),{handle:J,close:M,changed:n(e=>{o.size&&S(e)},"changed"),refresh:n(()=>{o.size&&h()},"refresh")}}n(A,"hubStream");export{A as hubStream};
19
+ `,[e]):m(),t.on("close",()=>{o.delete(e),o.size||z()})}r(J,"handle");function N(){for(const t of o)t.end();o.clear(),z()}return r(N,"close"),{handle:J,close:N,changed:r(t=>{o.size&&b(t)},"changed"),refresh:r(()=>{o.size&&m()},"refresh")}}r(P,"hubStream");export{P as hubStream};
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/0055-one-app-for-the-whole-hub.md). Nothing else is cached: API calls, streams, uploads and frames always
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';
@@ -16,7 +16,7 @@ function isShellPage(url) {
16
16
  if (HUB_PAGES.has(url.pathname)) return true;
17
17
  if (url.searchParams.has('alone')) return false;
18
18
  const m = /^\/([^/]+)\/(.*)$/.exec(url.pathname);
19
- return Boolean(m) && m[1] !== '_hub' && !/^try(?:\/|$)/.test(m[2]) && (m[2] === '' || m[2].endsWith('/') || /\.html?$/.test(m[2]));
19
+ return Boolean(m) && m[1] !== '_hub' && (m[2] === '' || m[2].endsWith('/') || /\.html?$/.test(m[2]));
20
20
  }
21
21
  const isAsset = (url) => url.pathname.startsWith('/_hub/app/') || url.pathname === '/_hub/colors.css' || url.pathname === '/_hub/kickflip.png';
22
22
  // hub/hub.mjs marks the shell it serves with the sidebar written in; a site's own page and the board server's copy
package/hub/trust.mjs ADDED
@@ -0,0 +1,2 @@
1
+ var p=Object.defineProperty;var c=(t,r)=>p(t,"name",{value:r,configurable:!0});import n from"node:fs";import l from"node:os";import s from"node:path";import{randomUUID as f}from"node:crypto";const y=c(()=>s.join(process.env.CLAUDE_CONFIG_DIR||l.homedir(),".claude.json"),"claudeConfigFile"),m=c(t=>t.startsWith(l.homedir()+s.sep)?`~${t.slice(l.homedir().length)}`:t,"shown");function d(t){let r;try{r=n.readFileSync(t,"utf8")}catch(o){throw o.code==="ENOENT"?new Error(`${m(t)} doesn't exist; run claude once to make it`):o}let e=null;try{e=JSON.parse(r)}catch{}if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${m(t)} isn't valid JSON`);return e}c(d,"load");const w=c((t,r)=>t.projects?.[r]?.hasTrustDialogAccepted===!0,"marked");function S(t,r,e){const o=n.realpathSync(t),{mode:a}=n.statSync(o),h={...r.projects,[e]:{...r.projects?.[e],hasTrustDialogAccepted:!0}},i=s.join(s.dirname(o),`.${s.basename(o)}.kickflip-${f()}`);try{n.writeFileSync(i,`${JSON.stringify({...r,projects:h},null,2)}
2
+ `,{flag:"wx",mode:384}),n.chmodSync(i,a&4095),n.renameSync(i,o)}catch(u){throw n.rmSync(i,{force:!0}),u}}c(S,"save");function k(t){const r=y(),e=n.realpathSync(t);let o=d(r);for(let a=0;!w(o,e);a++){if(a===2)throw new Error(`a running Claude session overwrote the trust mark in ${m(r)}; retry`);S(r,o,e),o=d(r)}return e}c(k,"trustFolder");export{k as trustFolder};
package/hub/try.mjs CHANGED
@@ -1,3 +1,8 @@
1
- var pt=Object.defineProperty;var s=(r,d)=>pt(r,"name",{value:d,configurable:!0});import y from"node:fs";import b from"node:path";import et from"node:os";import ht from"node:http";import{execFile as mt,spawn as yt}from"node:child_process";import{createInterface as it}from"node:readline";import{promisify as wt}from"node:util";import{listBoards as R,readManifest as G,readJSON as rt,saveJSON as gt,GITHUB_STATE as bt}from"./boards.mjs";import{boardRepo as nt,githubFromOrigin as kt}from"./board-repo.mjs";import{buildScriptError as vt}from"../board/build-script.mjs";import{appendThread as St,recordedWorktree as $t}from"../board/store.mjs";class L extends Error{static{s(this,"BuildError")}constructor(d,w=400){super(d),this.status=w}}const Tt=wt(mt),O=s(async(r,...d)=>(await Tt("git",["-C",r,...d],{encoding:"utf8",timeout:3e3})).stdout.trim(),"git"),xt=/errSecInternalComponent|keychain[^\n]*\blocked\b|\blocked\b[^\n]*keychain/i,It=30*6e4,st=s(r=>b.join(r,".kickflip","build"),"scriptAt"),ot=s(r=>y.existsSync(r),"exists"),at=s((r,d)=>b.join(r.dir,"data","try",`${d.split("/").at(-1)}.log`),"logFileOf");function ct(r,d,w){const u=at(r,d);return y.mkdirSync(b.dirname(u),{recursive:!0}),y.writeFileSync(u,w.message+`
2
- `,{mode:384}),y.chmodSync(u,384),u}s(ct,"failureLog");const Ct=s(r=>new Promise(d=>{const w=ht.get({host:"127.0.0.1",port:r,path:"/",timeout:1e3},u=>{u.destroy(),d(!0)});w.on("timeout",()=>w.destroy()),w.on("error",()=>d(!1))}),"probe"),lt=s((r,d)=>{try{process.kill(-r.pid,d)}catch{}},"signalGroup");async function dt(r,d,w){const u=await $t(r.dir,d),[m,E]=d.split("/"),M=r.waves.find($=>$.slug===m)?.wave,j=u?.path||M?.items.find($=>$.id===E)?.worktree;if(typeof j!="string"||!j||j.split(b.sep).includes(".."))return"";let I=u?.repo;const N=(r.github||M?.repo||"").toLowerCase();if(!I&&N){const $=[r.owner?.repo,r.dir,...Object.values(w?.sites||{}).map(k=>k.owner?.repo)];for(const k of new Set($.filter(T=>typeof T=="string"&&b.isAbsolute(T))))try{if(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(await O(k,"remote","get-url","origin"))?.[1].toLowerCase()===N){I=await O(k,"rev-parse","--show-toplevel");break}}catch{}}if(!u?.path&&!I||u?.path&&!b.isAbsolute(j))return"";try{const $=[b.join(y.realpathSync(et.homedir()),".claude","kickflip","worktrees")];if(typeof I=="string"&&b.isAbsolute(I))try{$.push(b.join(y.realpathSync(I),".claude","worktrees"))}catch{}const k=b.resolve(I||"/",j),T=y.realpathSync(k);return $.some(_=>k.startsWith(_+b.sep)&&T.startsWith(_+b.sep))&&y.statSync(T).isDirectory()?T:""}catch{return""}}s(dt,"installWorktree");function Ot({now:r=Date.now,answers:d=Ct,log:w=console.log}={}){const u=new Map,m=new Map,E=new Set,M=new Map;let j=!1,I=null;const N=s(()=>new Date(r()).toISOString(),"stamp");function $(t){if(u.has(t.dir))return u.get(t.dir);const i=b.join(t.dir,"data","try.json"),l=rt(i,{kind:null,main:null,cards:{}}),e={kind:l.kind||null,main:l.main||null,cards:{...l.cards}},n={state:e,file:i,written:JSON.stringify(l)};if(u.set(t.dir,n),e.kind==="web")e.cards={},e.main&&e.main.state!=="failed"&&(delete e.main.state,delete e.main.port);else{for(const o of Object.values(e.cards))o.state==="running"&&(delete o.state,delete o.sha);e.main?.state==="running"&&(delete e.main.state,delete e.main.sha)}return k(t),n}s($,"stateOf");function k(t){const i=u.get(t.dir),l=JSON.stringify(i.state);l!==i.written&&(gt(i.file,i.state),i.written=l)}s(k,"persist");const T=s((t,i)=>`${t.dir}\0${i}`,"runKey"),_=s((t,i)=>i==="main"?t.main:t.cards[i],"entryOf");function K(t,i,l){const{state:e}=$(t),n=_(e,i);if(!n)return;const o=Object.hasOwn(l,"state")&&l.state!==n.state;Object.assign(n,l,i!=="main"&&o?{at:N()}:{}),k(t)}s(K,"update");async function Y(t,i,l,e){const{board:n,key:o}=t;if(K(n,o,{state:"failed",port:void 0}),o==="main")return;const c=[];let v=!1;try{for await(const g of it({input:y.createReadStream(t.logFile),crlfDelay:1/0}))v||=xt.test(g),c.push(g),c.length>5&&c.shift()}catch(g){c.push(`Could not read the build log: ${g.message}`)}const S=t.port||($(n).state.kind||(n.waves.some(({wave:g})=>g.items.some(x=>x.install?.url))?"app":"web"))==="web"?"Serve":"Build";await St(n.dir,o,{text:[`${S} failed (exit ${i??1})`,e?.message,l&&`Stopped by ${l}.`,v&&"The login keychain must be unlocked on the Mac.",...c].filter(Boolean).join(`
3
- `)})}s(Y,"failure");function J(t){return t.ending||(lt(t.child,"SIGTERM"),t.ending=new Promise(i=>{const l=s(()=>{clearTimeout(e),clearInterval(n),i()},"finish"),e=setTimeout(()=>{lt(t.child,"SIGKILL"),l()},4e3),n=setInterval(()=>{try{process.kill(-t.child.pid,0)}catch{l()}},20)})),t.ending}s(J,"terminate");async function P(t){t.stopped=!0,clearTimeout(t.deadline),clearInterval(t.poll),await J(t),await t.done,K(t.board,t.key,{state:void 0,port:void 0,...t.ready?{}:{sha:void 0}}),t.ready||M.delete(T(t.board,t.key))}s(P,"stopRun");async function Q(t,i,l,e={}){if(!l)throw new L("This card has no valid worktree.");const n=st(l),o=vt(n);if(o)throw new L(o);if(!y.realpathSync(n).startsWith(y.realpathSync(l)+b.sep))throw new L("Build script must be inside the worktree.");const c=await O(l,"rev-parse","HEAD");if(j)throw new L("The hub is stopping. Try again after it restarts.",503);const{state:v}=$(t),S=_(v,i),g={...i==="main"?{}:S,...e,sha:c,script:!0,state:"running",...i==="main"?{}:{at:N(),head:c}};delete g.port;const x=at(t,i);y.mkdirSync(b.dirname(x),{recursive:!0});const f=y.openSync(x,"w",384);y.fchmodSync(f,384);const p=yt(n,[i,l],{cwd:l,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,KICKFLIP_BOARD:t.route,KICKFLIP_BASE:`/${t.route}/try/${i.split("/").at(-1).toLowerCase()}/`}});i==="main"?v.main=g:v.cards[i]=g,k(t);const C=T(t,i),a={child:p,board:t,key:i,logFile:x,visited:r(),stopped:!1,port:null,ready:!1};m.set(C,a),M.set(C,c);let h,D;const B=s(A=>{D||=new Error(A),J(a)},"fail");p.on("error",A=>{h=A}),p.stdout.on("data",A=>y.writeSync(f,A)),p.stderr.on("data",A=>y.writeSync(f,A));const Z=it({input:p.stdout,crlfDelay:1/0});return Z.on("line",A=>{const H=/^port (\d{1,5})$/.exec(A);if(!H||a.port||a.stopped)return;const F=Number(H[1]);if(F<1||F>65535){B("Build script printed an invalid port.");return}a.port=F,clearTimeout(a.deadline);const z=r()+6e4;let q=!1;const tt=s(async()=>{if(!(q||a.stopped||a.ready||p.exitCode!==null||p.signalCode!==null)){q=!0;try{if(await d(F)){if(a.stopped||D||p.exitCode!==null||p.signalCode!==null)return;a.ready=!0,a.visited=r(),v.kind="web",K(t,i,{state:"ready",port:F}),clearInterval(a.poll)}else r()>=z&&B("Nothing answered on the build script\u2019s port within 60 seconds.")}finally{q=!1}}},"check");a.poll=setInterval(()=>tt().catch(U=>B(U.message)),250),tt().catch(U=>B(U.message))}),a.deadline=setTimeout(()=>B("No port line within 60 minutes."),60*6e4),p.once("exit",()=>{J(a)}),a.done=new Promise(A=>p.once("close",(H,F)=>{clearTimeout(a.deadline),clearInterval(a.poll),Z.close(),y.closeSync(f),(async()=>{await J(a),!a.stopped&&(D||h||H!==0||a.port&&!a.ready?await Y(a,H??1,F,D||h||(a.port&&!a.ready?new Error("Build script exited before its port answered."):null)):a.ready?(i==="main"?(delete v.main.state,delete v.main.port):delete v.cards[i],k(t)):(v.kind="app",K(t,i,{state:"ready"})))})().catch(z=>w(`build /${t.route} ${i}: ${z.message}`)).finally(()=>{m.get(C)===a&&m.delete(C),A()})})),w(`build /${t.route} ${i}: started; log ${x}`),{status:"started"}}s(Q,"launch");async function V(t,{manifest:i=G()}={}){if(j)throw new L("The hub is stopping. Try again after it restarts.",503);if(!t||Array.isArray(t)||typeof t!="object"||Object.keys(t).some(c=>!["route","key"].includes(c))||typeof t.route!="string"||typeof t.key!="string")throw new L("Send only the board route and card key.");const{route:l,key:e}=t;if(!/^[\w.-]+\/[\w.-]+$/.test(e)||e.split("/").some(c=>c==="."||c===".."))throw new L("Card key must be <wave>/<id>.");const n=R(i).find(c=>c.route===l);if(!n)throw new L(`/${l} is not a board.`,404);if(!n.waves.some(({slug:c,wave:v})=>v.items.some(S=>`${c}/${S.id}`===e)))throw new L("There is no item with this card key.",404);const o=T(n,e);if(E.has(o)||m.has(o)&&!m.get(o).ready)throw new L("A build is already running for this card.",409);E.add(o);try{m.has(o)&&await P(m.get(o));const c=await dt(n,e,i);return await Q(n,e,c)}finally{E.delete(o)}}s(V,"start");function X(t,i,{manifest:l=G(),visit:e=!1}={}){const n=R(l).find(c=>c.route===t);if(!n)return null;const o=[...m.values()].find(c=>c.board.dir===n.dir&&c.key.split("/").at(-1).toLowerCase()===i.toLowerCase()&&c.ready&&!c.stopped&&c.child.exitCode===null&&c.child.signalCode===null);return o?(e&&(o.visited=r()),{key:o.key,port:o.port}):null}s(X,"lookup");async function ut({manifest:t=G()}={}){return I||j||(I=(async()=>{const i=R(t),l=rt(bt,{}).prs||{};for(const e of[...m.values()])if(!i.some(n=>n.dir===e.board.dir)||e.key!=="main"&&e.ready&&r()-e.visited>=It){await P(e);const{state:n}=$(e.board);e.key==="main"?n.main=null:delete n.cards[e.key],k(e.board)}for(const e of i){if(j)return;const{state:n}=$(e),o=nt(e.route,t),c=o.branch||"main",v=o.hub?"refs/heads/main":`refs/remotes/origin/${c}`;for(const{slug:S,wave:g}of e.waves)for(const x of g.items){const f=`${S}/${x.id}`;if(!(["done","merged","dropped"].includes(String(x.status).toLowerCase())||["MERGED","CLOSED"].includes(l[`${e.github||g.repo}#${x.pr}`]?.state)))try{const p=await dt(e,f,t);if(!p)continue;const C=await O(p,"rev-parse","HEAD");let a=0;try{a=Number(await O(p,"rev-list","--count",`${v}..HEAD`))}catch{}const h=ot(st(p)),D=n.cards[f]||={};if(Object.assign(D,{head:C,ahead:a,script:h}),k(e),e.auto_build&&h&&a>0&&(D.sha||M.get(T(e,f)))!==C&&D.state!=="running"&&!E.has(T(e,f)))try{await V({route:e.route,key:f},{manifest:t})}catch(B){if([409,503].includes(B.status))continue;throw K(e,f,{sha:C}),await Y({board:e,key:f,logFile:ct(e,f,B)},1),B}}catch(p){w(`try /${e.route} ${f}: ${p.message}`)}}try{if(!o.repo)continue;const S=await O(o.repo,"rev-parse",v);let g=!1;try{await O(o.repo,"cat-file","-e",`${S}:.kickflip/build`),g=!0}catch{}if(!g){const h=m.get(T(e,"main"));h&&await P(h),n.main=null,k(e);continue}const x=n.main;if(x?.state==="running"||x?.sha===S&&(x.state==="failed"||x.state==="ready"&&(n.kind!=="web"||X(e.route,"main",{manifest:t}))))continue;const f=T(e,"main");if(E.has(f))continue;const p=await O(o.repo,"log","-1","--format=%cI",S);let C=e.github;if(!C)try{C=kt(await O(o.repo,"remote","get-url","origin"))}catch{}const a={sha:S,branch:c,slug:C||"",at:p,script:g};E.add(f);try{m.has(f)&&await P(m.get(f));const h=b.join(et.homedir(),".claude","kickflip","try",`${e.route}-main`);y.mkdirSync(b.dirname(h),{recursive:!0}),ot(h)?await O(h,"checkout","--detach","--force",S):await O(o.repo,"worktree","add","--detach",h,S),await Q(e,"main",h,a)}catch(h){if(h.status===503)return;throw n.main={...a,state:"failed"},ct(e,"main",h),k(e),h}finally{E.delete(f)}}catch(S){w(`try /${e.route} main: ${S.message}`)}}})().finally(()=>{I=null})),I}s(ut,"tick");async function ft(){j=!0;const t=Promise.all([...m.values()].map(P));await Promise.all([t,I])}return s(ft,"stop"),{start:V,tick:ut,stop:ft,lookup:X,initialize:s((t=G())=>{for(const i of R(t))$(i)},"initialize")}}s(Ot,"createTryManager");async function Ht({manifest:r=G(),log:d=console.log}={}){for(const w of R(r)){const u=nt(w.route,r);if(u.hub||!u.repo)continue;const m=u.branch||"main";try{await O(u.repo,"fetch","--quiet","--no-tags","origin",`+refs/heads/${m}:refs/remotes/origin/${m}`)}catch(E){d(`fetch /${w.route}: ${E.message}`)}}}s(Ht,"fetchTryBranches");const W=Ot(),Rt=s((...r)=>W.start(...r),"startBuild"),Gt=s((...r)=>W.tick(...r),"tryTick"),Wt=s(()=>W.stop(),"stopTries"),Jt=s((...r)=>W.lookup(...r),"servingTry"),zt=s((...r)=>W.initialize(...r),"initializeTries");export{L as BuildError,Ot as createTryManager,Ht as fetchTryBranches,zt as initializeTries,dt as installWorktree,Jt as servingTry,Rt as startBuild,Wt as stopTries,Gt as tryTick};
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};
@@ -0,0 +1 @@
1
+ var E=Object.defineProperty;var t=(r,s)=>E(r,"name",{value:s,configurable:!0});import h from"node:fs";import d from"node:path";const _="https://registry.npmjs.org/@lovek4d%2Fkickflip/latest",C=60*6e4,v=t(r=>String(r).split("-")[0].split(".").map(Number),"parts");function F(r,s){const[l,u]=[v(r),v(s)];for(let n=0;n<3;n++)if((l[n]||0)!==(u[n]||0))return(l[n]||0)>(u[n]||0);return!1}t(F,"newer");function L({root:r,fetch:s=globalThis.fetch,builders:l,run:u,log:n=t(()=>{},"log"),changed:c=t(()=>{},"changed")}){const k=h.existsSync(d.join(r,".git"));let i=null,f=!1,a=!1,p=0,o=null;const y=t(()=>JSON.parse(h.readFileSync(d.join(r,"package.json"),"utf8")).version,"installed");async function S(){if(!k){try{const e=await s(_,{signal:AbortSignal.timeout(15e3)});if(!e.ok)throw new Error(`npm answered ${e.status}`);i=(await e.json()).version}catch(e){n(`kickflip update check failed: ${e.message}`)}c()}}t(S,"check");function g(){return k||!i||!F(i,y())?null:a?{state:"updating",version:i}:f?{state:"waiting",version:i,builders:p}:o?{state:"failed",version:i,error:o}:{state:"available",version:i}}t(g,"state");let m=Promise.resolve();const w=t(()=>m=m.catch(()=>{}).then(b),"tick");async function b(){if(!(!f||a)){if(p=(await l()).length,p){c();return}f=!1,a=!0,o=null,c(),u().then(({ok:e,error:x})=>{e||(o=x)},e=>{o=e.message}).finally(()=>{a=!1,c()})}}t(b,"tickOnce");async function j(){if(!g())throw Object.assign(new Error("kickflip is up to date."),{status:409});return a||(f=!0),await w(),g()}return t(j,"request"),{check:S,state:g,request:j,tick:w}}t(L,"upgrader");export{C as CHECK_MS,_ as LATEST_URL,F as newer,L as upgrader};
package/hub/usage.mjs CHANGED
@@ -1,3 +1,3 @@
1
- var N=Object.defineProperty;var u=(e,t)=>N(e,"name",{value:t,configurable:!0});import f from"node:fs";import _ from"node:os";import m from"node:path";const h=6,b=180,D={five_hour:5*36e5,seven_day:7*864e5},S=u(e=>{try{return JSON.parse(f.readFileSync(e,"utf8"))}catch{return null}},"readJson"),y=u(e=>e==null||e===""||!Number.isFinite(Number(e))?null:Number(e),"num"),g=u(e=>{if(e==null||e==="")return null;const s=typeof e=="number"||/^\d+(\.\d+)?$/.test(String(e))?Number(e)>1e12?Number(e):Number(e)*1e3:Date.parse(String(e));return Number.isFinite(new Date(s).getTime())?new Date(s).toISOString():null},"isoOf"),w=u((e,t)=>({used_percentage:y(e),resets_at:g(t)}),"win");function O(e){let t;try{t=f.openSync(e,"r");const s=f.fstatSync(t).size;for(const n of[256*1024,2*1024*1024]){const r=Math.max(0,s-n),a=Buffer.alloc(s-r);f.readSync(t,a,0,a.length,r);const i=a.toString("utf8").split(`
2
- `);r>0&&i.shift();for(let c=i.length-1;c>=0;c--)if(i[c].includes("rate_limits"))try{const d=JSON.parse(i[c]),o=d?.payload?.rate_limits??d?.rate_limits;if(o?.primary)return{rl:o}}catch{}if(r===0)break}}catch{}finally{if(t!==void 0)try{f.closeSync(t)}catch{}}return null}u(O,"lastRateLimits");function k(e){const t=[],s=u(n=>{try{return f.readdirSync(n).sort().reverse()}catch{return[]}},"kids");e:for(const n of s(e))for(const r of s(m.join(e,n)))for(const a of s(m.join(e,n,r))){const i=m.join(e,n,r,a);for(const c of s(i))if(/^rollout-.*\.jsonl$/.test(c))try{t.push({file:m.join(i,c),mtime:f.statSync(m.join(i,c)).mtimeMs})}catch{}if(t.length>=h*2)break e}return t.sort((n,r)=>r.mtime-n.mtime).slice(0,h)}u(k,"newestRollouts");function x(e){const t=[];for(const{file:o,mtime:l}of k(e)){const p=O(o);p&&t.push({...p,mtime:l,resets:y(p.rl.primary.resets_at)})}if(!t.length)return null;const s=Math.max(...t.map(o=>o.resets??-1/0)),n=t.filter(o=>o.resets!=null&&Math.abs(o.resets-s)<=b),r=u(o=>n.reduce((l,p)=>(y(p.rl[o]?.used_percent)??-1)>(y(l?.rl[o]?.used_percent)??-1)?p:l,null),"pick");if(!n.length)return null;const a=r("primary"),i=r("secondary"),c=n.reduce((o,l)=>l.mtime>o.mtime?l:o),d=u((o,l)=>o?w(o.rl[l].used_percent,o.rl[l].resets_at):null,"w");return{five_hour:d(a,"primary"),seven_day:d(i,"secondary"),at:new Date(c.mtime).toISOString()}}u(x,"scanCodex");function j(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const s=g(e.at),n=u(r=>{const a=e[r];if(!a)return null;const i=w(a.used_percentage,a.resets_at);if(i.used_percentage==null)return null;const c=!s||t-Date.parse(s)>D[r]?"stale":i.resets_at&&t>=Date.parse(i.resets_at)?"reset":"live";return{...i,used_percentage:c==="reset"?0:i.used_percentage,state:c}},"window");return{at:s,five_hour:n("five_hour"),seven_day:n("seven_day")}}u(j,"readingOf");function W({home:e=_.homedir(),now:t=Date.now,cacheMs:s=6e4}={}){const n=m.join(e,".codex","sessions");let r=null,a=-1/0;return({codexShare:i="off"}={})=>{const c=t(),d=j(S(m.join(e,".claude","kickflip","usage.json"))?.claude,c);return i==="off"?{claude:d,codex:null}:(c-a>=s&&(r=x(n),a=c),{claude:d,codex:j(r||{at:null},c)})}}u(W,"usageReader");async function $({gate:e,home:t=_.homedir(),resume:s}){const n=m.join(t,".claude","kickflip","usage-gate-state.json"),r=S(n);r?.state==="paused"&&e.state==="normal"&&await s(r.window),f.mkdirSync(m.dirname(n),{recursive:!0});const a=`${n}.${process.pid}.tmp`;f.writeFileSync(a,JSON.stringify(e)+`
3
- `),f.renameSync(a,n)}u($,"checkUsagePause");export{$ as checkUsagePause,W 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};