@lovek4d/kickflip 0.4.0 → 0.5.3

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 (90) hide show
  1. package/CONTEXT.md +69 -48
  2. package/README.md +1 -1
  3. package/SKILL.md +22 -20
  4. package/bin/doctor.mjs +4 -4
  5. package/bin/install.mjs +3 -3
  6. package/bin/kickflip.mjs +27 -18
  7. package/bin/wait-events.mjs +2 -2
  8. package/board/agents.mjs +2 -0
  9. package/board/bin/board.mjs +108 -39
  10. package/board/domain.mjs +7 -7
  11. package/board/finish.mjs +4 -3
  12. package/board/headless.mjs +5 -3
  13. package/board/merge3.mjs +1 -0
  14. package/board/on-host.mjs +1 -1
  15. package/board/permissions.mjs +2 -2
  16. package/board/public/app-asks.js +9 -92
  17. package/board/public/app-banner.js +7 -13
  18. package/board/public/app-cards.js +70 -37
  19. package/board/public/app-core.js +24 -25
  20. package/board/public/app-header.js +2 -1
  21. package/board/public/app-lanes.js +55 -23
  22. package/board/public/app-needs.js +129 -4
  23. package/board/public/app-reader.js +174 -0
  24. package/board/public/app-snapshot.js +6 -5
  25. package/board/public/app-threads.js +83 -58
  26. package/board/public/app.html +2 -0
  27. package/board/public/app.js +66 -24
  28. package/board/public/attach.js +2 -2
  29. package/board/public/dialogs.js +9 -39
  30. package/board/public/hub-kit.js +4 -2
  31. package/board/public/hub.css +1 -0
  32. package/board/public/linear-key.js +46 -35
  33. package/board/public/new-task.js +100 -0
  34. package/board/public/prototype-kit.js +28 -3
  35. package/board/public/prototype-switcher.js +42 -107
  36. package/board/public/shell.js +7 -1
  37. package/board/public/sidebar.css +1 -0
  38. package/board/public/sidebar.js +44 -5
  39. package/board/public/style.css +194 -35
  40. package/board/public/ui-cards.js +80 -44
  41. package/board/public/ui-enums.js +1 -1
  42. package/board/public/ui-header.js +2 -2
  43. package/board/public/ui-order.js +12 -10
  44. package/board/public/ui-phase-bars.js +4 -4
  45. package/board/public/ui-questions.js +63 -47
  46. package/board/public/ui-sidebar.js +27 -15
  47. package/board/public/ui-threads.js +27 -14
  48. package/board/public/ui.js +76 -14
  49. package/board/public/view-frame.js +1 -0
  50. package/board/public/view-hub-settings.js +11 -10
  51. package/board/public/view-hub.js +17 -3
  52. package/board/public/view-questions.js +174 -202
  53. package/board/public/view-settings.js +208 -70
  54. package/board/server.mjs +19 -18
  55. package/board/store.mjs +20 -13
  56. package/board/transcript.mjs +2 -0
  57. package/board/worktree.mjs +24 -20
  58. package/hooks-plugin/hooks/board-data-gate.mjs +50 -0
  59. package/hooks-plugin/hooks/hooks.json +9 -0
  60. package/hub/boards.mjs +4 -4
  61. package/hub/front-door.mjs +20 -0
  62. package/hub/github.mjs +3 -3
  63. package/hub/hub.mjs +11 -14
  64. package/hub/linear.mjs +1 -2
  65. package/hub/live.mjs +2 -2
  66. package/hub/locks.mjs +1 -1
  67. package/hub/new-board.mjs +2 -2
  68. package/hub/owner-checks.mjs +1 -0
  69. package/hub/pr-report.mjs +2 -2
  70. package/hub/presence.mjs +1 -1
  71. package/hub/push.mjs +2 -2
  72. package/hub/readiness.mjs +1 -2
  73. package/hub/review-send.mjs +1 -0
  74. package/hub/secrets.mjs +2 -0
  75. package/hub/self-restart.mjs +2 -0
  76. package/hub/sessions.mjs +2 -2
  77. package/hub/share.mjs +1 -0
  78. package/hub/slack.mjs +2 -2
  79. package/hub/stream.mjs +10 -13
  80. package/hub/try.mjs +7 -7
  81. package/hub/upgrade.mjs +1 -1
  82. package/hub/usage.mjs +3 -3
  83. package/hub/views.mjs +1 -1
  84. package/package.json +2 -1
  85. package/shared/audit.mjs +4 -0
  86. package/shared/fake-gh.mjs +17 -4
  87. package/shared/owner-check.mjs +3 -0
  88. package/shared/service.mjs +4 -4
  89. package/shared/tailscale.mjs +1 -0
  90. package/shared/usage-gate.mjs +1 -1
package/hub/readiness.mjs CHANGED
@@ -1,2 +1 @@
1
- var T=Object.defineProperty;var i=(t,r)=>T(t,"name",{value:r,configurable:!0});import f from"node:fs";import m from"node:os";import y from"node:path";import{execFile as N}from"node:child_process";import{githubLogin as P}from"./pr-report.mjs";import{codexStatusReader as w}from"../shared/codex.mjs";import{linearStatus as R}from"./linear.mjs";import{readSettings as O,subscriptions as C}from"./push.mjs";import{tailscaleState as I,tailscaleInstallHint as L}from"../bin/install.mjs";const x=[["github","GitHub","GitHub polling and PR reports wait on this."],["codex","Codex","Codex implementing and reviewing wait on this; Codex share stays Off."],["linear","Linear",null],["slack","Slack","Reviewer DMs and digests wait on this."],["tailscale","Tailscale","Try builds wait on this."],["notifications","Notifications","Pushes wait on this."]],k=i(t=>y.join(t,".claude","kickflip","integrations.json"),"reportFile");function F(t=m.homedir()){try{return JSON.parse(f.readFileSync(k(t),"utf8")).slack||null}catch{return null}}i(F,"readSlackReport");function Q(t,{home:r=m.homedir(),now:s=new Date,route:d=null,title:o="Board"}={}){const e=k(r),n={ready:t,at:s.toISOString(),route:d,title:o};f.mkdirSync(y.dirname(e),{recursive:!0});const a=`${e}.${process.pid}.tmp`;return f.writeFileSync(a,JSON.stringify({slack:n},null,2)+`
2
- `,{mode:384}),f.renameSync(a,e),n}i(Q,"reportSlack");const H=i((t,r)=>{const s=Math.floor((r-Date.parse(t))/6e4);return s<1?"just now":s<60?`${s} min ago`:s<1440?`${Math.floor(s/60)} h ago`:`${Math.floor(s/1440)} days ago`},"age"),u=i((t,r,s)=>({settings:t,label:`Hub settings \u203A ${r}`,text:s}),"settingsFix");function $(t,{now:r=Date.now(),platform:s=process.platform}={}){const d=i((o,e)=>{switch(o){case"github":return e?{ready:!0,detail:`gh logged in as ${e}`}:{ready:!1,missing:"gh isn't logged in on the host",fix:{command:"gh auth login"}};case"codex":return e.usable?{ready:!0,detail:"Installed and logged in"}:{ready:!1,missing:e.words,fix:{command:e.fix}};case"linear":return e.set?e.refused?{ready:!1,missing:"Linear refused the key",fix:u("linear","Linear","Paste a new one in")}:{ready:!0,detail:`Key set \xB7 ${e.workspace} workspace`}:{ready:!1,missing:"No Linear key set",fix:u("linear","Linear","Add one in")};case"slack":{const n=e?`${e.title}\u2019s session reported ${e.ready?"a":"no"} Slack connector, ${H(e.at,r)}`:"No board session has reported yet";return e?.ready?{ready:!0,detail:n}:{ready:!1,missing:n,fix:{text:"Add Slack to Claude\u2019s connectors. The next board session to start reports it."}}}case"tailscale":{let n,a;return e.installed?e.signedIn?e.pointsAtHub?e.operatorChecked&&e.operator!==e.username&&(n=`Tailscale operator is ${e.operator||"none"} (expected ${e.username})`,a="sudo tailscale set --operator=$USER"):(n="Tailscale / is not serving the hub",a="kickflip doctor --fix"):(n="Tailscale isn't signed in",a="tailscale up"):(n="Tailscale isn't installed on the host",a=L(s)),n?{ready:!1,missing:n,fix:{command:a}}:{ready:!0,detail:`Serving ${e.dns}${e.operatorChecked?" \xB7 operator "+e.operator:""}`}}case"notifications":return e.on&&e.devices?{ready:!0,detail:`Pushes on \xB7 ${e.devices} device${e.devices===1?"":"s"}`}:{ready:!1,missing:e.on?"No device has turned on notifications":"Pushes are off",fix:u("notifications","Notifications","Turn on notifications in")}}},"row");return x.filter(([o])=>Object.hasOwn(t,o)).map(([o,e,n])=>({id:o,name:e,...d(o,t[o]),waits:n}))}i($,"readinessRows");const j=i(t=>(r,s)=>new Promise(d=>{N(r,s,{env:t,timeout:3e3},(o,e)=>d({status:o?1:0,stdout:e}))}),"asyncRun");function D({home:t=m.homedir(),env:r=process.env,now:s=Date.now,cacheMs:d=6e4,probes:o={}}={}){const e=w({home:t,env:r,now:s,cacheMs:d}),n={github:i(()=>P({env:r}).catch(()=>null),"github"),codex:e,linear:i(()=>R(t),"linear"),slack:i(()=>F(t),"slack"),tailscale:i(()=>I({run:j(r),port:Number(r.KICKFLIP_HUB_PORT||4500)}),"tailscale"),notifications:i(()=>({on:O(t).notifications.on,devices:C(t).length}),"notifications"),...o},a=new Map;async function g(l,c){if(!["github","tailscale"].includes(l))return n[l]({fresh:c});const p=a.get(l);if(!c&&p&&s()-p.at<d)return p.value;const h=Promise.resolve().then(()=>n[l]());return a.set(l,{at:s(),value:h}),h}i(g,"check");const b=i(async({fresh:l=!1}={})=>$(Object.fromEntries(await Promise.all(x.map(async([c])=>[c,await g(c,l)]))),{now:s()}),"rows");async function S(l){const[c]=$({[l]:await g(l,!1)},{now:s()});return c.ready||!c.waits?null:c.waits.replace("this",`${c.name}: ${c.missing.replace(/\.$/,"")}`)}return i(S,"waiting"),{rows:b,waiting:S}}i(D,"readinessReader");const A=w(),V=D({probes:{codex:A}});export{A as readCodex,F as readSlackReport,V as readiness,D as readinessReader,$ as readinessRows,Q as reportSlack};
1
+ var k=Object.defineProperty;var t=(s,n)=>k(s,"name",{value:n,configurable:!0});import b from"node:os";import{execFile as $}from"node:child_process";import{githubLogin as S}from"./pr-report.mjs";import{codexStatusReader as h}from"../shared/codex.mjs";import{linearStatus as P}from"./linear.mjs";import{slackStatus as T}from"./slack.mjs";import{readSettings as R,subscriptions as C}from"./push.mjs";import{tailscaleState as N}from"../bin/install.mjs";import{tailscaleBin as I,tailscaleInstallCommand as L}from"../shared/tailscale.mjs";const w=[["github","GitHub","GitHub polling and PR reports wait on this."],["codex","Codex","Codex implementing and reviewing wait on this; Codex share stays Off."],["linear","Linear",null],["slack","Slack","Reviewer DMs and digests wait on this."],["tailscale","Tailscale","Try builds wait on this."],["notifications","Notifications","Pushes wait on this."]],f=t((s,n,a)=>({settings:s,label:`Hub settings \u203A ${n}`,text:a}),"settingsFix");function x(s,{now:n=Date.now(),platform:a=process.platform}={}){const d=t((o,e)=>{switch(o){case"github":return e?{ready:!0,detail:`gh logged in as ${e}`}:{ready:!1,missing:"gh isn't logged in on the host",fix:{command:"gh auth login"}};case"codex":return e.usable?{ready:!0,detail:"Installed and logged in"}:{ready:!1,missing:e.words,fix:{command:e.fix}};case"linear":return e.set?e.refused?{ready:!1,missing:"Linear refused the key",fix:f("linear","Linear","Paste a new one in")}:{ready:!0,detail:`Key set \xB7 ${e.workspace} workspace`}:{ready:!1,missing:"No Linear key set",fix:f("linear","Linear","Add one in")};case"slack":return e.set?e.refused?{ready:!1,missing:"Slack refused the token",fix:f("slack","Slack","Paste a new one in")}:{ready:!0,detail:`Token set \xB7 ${e.team} workspace, sending as ${e.user}`}:{ready:!1,missing:"No Slack token set",fix:f("slack","Slack","Add one in")};case"tailscale":{let i,c;return e.installed?e.signedIn?e.pointsAtHub?e.operatorChecked&&e.operator!==e.username&&(i=`Tailscale operator is ${e.operator||"none"} (expected ${e.username})`,c="sudo tailscale set --operator=$USER"):(i="Tailscale / is not serving the hub",c="kickflip doctor --fix"):(i="Tailscale isn't signed in",c="tailscale up"):(i="Tailscale isn't installed on the host",c=L(a)),i?{ready:!1,missing:i,fix:{command:c}}:{ready:!0,detail:`Serving ${e.dns}${e.operatorChecked?" \xB7 operator "+e.operator:""}`}}case"notifications":return e.on&&e.devices.length?{ready:!0,detail:`Pushes on \xB7 ${e.devices.length} device${e.devices.length===1?"":"s"}`,devices:e.devices.map(({id:i,kind:c,browser:m,added:p})=>({id:i,kind:c,browser:m,added:p}))}:{ready:!1,missing:e.on?"No device has turned on notifications":"Pushes are off",fix:f("notifications","Notifications","Turn on notifications in")}}},"row");return w.filter(([o])=>Object.hasOwn(s,o)).map(([o,e,i])=>({id:o,name:e,...d(o,s[o]),waits:i}))}t(x,"readinessRows");const O=t(s=>(n,a)=>new Promise(d=>{$(n,a,{env:s,timeout:3e3},(o,e)=>d({status:o?1:0,stdout:e}))}),"asyncRun");function H({home:s=b.homedir(),env:n=process.env,now:a=Date.now,cacheMs:d=6e4,probes:o={}}={}){const e=h({home:s,env:n,now:a,cacheMs:d}),i={github:t(()=>S({env:n}).catch(()=>null),"github"),codex:e,linear:t(()=>P(s),"linear"),slack:t(()=>T(s),"slack"),tailscale:t(()=>N({run:O(n),port:Number(n.KICKFLIP_HUB_PORT||4500),tailscale:I({env:n})}),"tailscale"),notifications:t(()=>({on:R(s).notifications.on,devices:C(s)}),"notifications"),...o},c=new Map;async function m(l,r){if(!["github","tailscale"].includes(l))return i[l]({fresh:r});const g=c.get(l);if(!r&&g&&a()-g.at<d)return g.value;const u=Promise.resolve().then(()=>i[l]());return c.set(l,{at:a(),value:u}),u}t(m,"check");const p=t(async({fresh:l=!1}={})=>x(Object.fromEntries(await Promise.all(w.map(async([r])=>[r,await m(r,l)]))),{now:a()}),"rows");async function y(l){const[r]=x({[l]:await m(l,!1)},{now:a()});return r.ready||!r.waits?null:r.waits.replace("this",`${r.name}: ${r.missing.replace(/\.$/,"")}`)}return t(y,"waiting"),{rows:p,waiting:y}}t(H,"readinessReader");const A=h(),q=H({probes:{codex:A}});export{A as readCodex,q as readiness,H as readinessReader,x as readinessRows};
@@ -0,0 +1 @@
1
+ var $=Object.defineProperty;var f=(t,s)=>$(t,"name",{value:s,configurable:!0});import{listBoards as p}from"./boards.mjs";import{savedSlack as l}from"./slack.mjs";import{reviewDue as y,reviewSent as h,reviewReact as v,reviewDigestSent as g}from"../board/store.mjs";const u=f(t=>t.status===400&&t.message==="Slack refused the token.","refusedToken");async function k(t,s,d){const a=await y(t.dir,{now:d});if(a.waiting)return{sent:[],failed:[]};const c=[],o=[],r=f(async(e,n)=>{try{await n(),c.push(e)}catch(i){if(u(i))throw i;o.push(`${t.route}: ${e}: ${i.message}`)}},"attempt");for(const e of a.dms)await r(`link to ${e.reviewer} on ${e.key}`,async()=>{const n=await s.openDM(e.slack_user),i=await s.post({channel:n,text:e.text});await h(t.dir,e.key,e.reviewer,{ts:i,channel:n})});for(const e of a.reactions)await r(`${e.emoji} for ${e.reviewer} on ${e.key}`,async()=>{await s.react({channel:e.channel,ts:e.ts,name:e.emoji}),await v(t.dir,e.key,e.reviewer,e.emoji)});for(const e of a.digest?.reviewers||[]){const n=e.items.length;await r(`digest to ${e.name}`,async()=>{const i=await s.openDM(e.slack_user),m=await s.post({channel:i,text:`\u{1F916} ${t.title} digest: ${n} PR${n===1?"":"s"} pending your review`});for(const w of e.items)await s.post({channel:i,thread_ts:m,text:`${w.url} \xB7 ${w.title}${w.days_old?` (${w.days_old} days old)`:""}`});await g(t.dir,e.name,{ts:m,channel:i,items:e.items.map(w=>w.key).join(",")},{now:d})})}return{sent:c,failed:o}}f(k,"sendBoard");async function S({boards:t=p(),fetch:s,now:d=new Date}={}){const a=l({fetch:s}),c=[],o=[];if(!a)return{sent:c,failed:o};for(const r of t)try{const e=await k(r,a,d);c.push(...e.sent.map(n=>`${r.route}: ${n}`)),o.push(...e.failed)}catch(e){if(o.push(`${r.route}: ${e.message}`),u(e))break}return{sent:c,failed:o}}f(S,"sendReviews");export{S as sendReviews};
@@ -0,0 +1,2 @@
1
+ var d=Object.defineProperty;var c=(r,e)=>d(r,"name",{value:e,configurable:!0});import n from"node:fs";import o from"node:path";import m from"node:os";const l=c((r=m.homedir())=>o.join(r,".claude","kickflip"),"dirOf"),a=c(r=>o.join(l(r),"secrets.json"),"secretsFile");function f(r,e){n.mkdirSync(o.dirname(r),{recursive:!0});const t=`${r}.${process.pid}.tmp`;n.writeFileSync(t,JSON.stringify(e,null,2)+`
2
+ `,{mode:384}),n.chmodSync(t,384),n.renameSync(t,r)}c(f,"write");function p(r){const e=a(r);let t={};try{t=JSON.parse(n.readFileSync(e,"utf8"))||{}}catch{}const i=o.join(l(r),"linear.json");if(n.existsSync(i)){let s=null;try{s=JSON.parse(n.readFileSync(i,"utf8"))}catch{}!t.linear&&s&&(t={...t,linear:s},f(e,t)),n.rmSync(i,{force:!0})}return t}c(p,"readAll");const h=c((r,e)=>p(e)[r]||null,"readSecret");function x(r,e){const{[r]:t,...i}=p();f(a(),e?{...i,[r]:e}:i)}c(x,"writeSecret");export{h as readSecret,a as secretsFile,x as writeSecret};
@@ -0,0 +1,2 @@
1
+ var y=Object.defineProperty;var e=(n,i)=>y(n,"name",{value:i,configurable:!0});import d from"node:fs";import h from"node:path";import{execFileSync as b}from"node:child_process";const g=["index.lock","MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function w({root:n,files:i,restart:p,log:s=e(()=>{},"log"),git:c=e((...r)=>b("git",r,{cwd:n,encoding:"utf8"}),"git")}){const r=d.existsSync(h.join(n,".git"));let a=!1;function u(){try{const t=c("rev-parse","HEAD").trim();return a=!1,t}catch(t){return a||s(`self-restart can't read HEAD: ${t.message.split(`
2
+ `)[0]}`),a=!0,null}}e(u,"head");const f=r?u():null;let l=null;function o(t,R){if(l===t)return;l=t,s(`restarting the hub: ${R}`);const m=p();m&&s(`hub restart failed: ${m}`)}e(o,"attempt");const E=e(()=>g.some(t=>d.existsSync(h.join(n,".git",t))),"gitBusy"),A=e(()=>{try{return c("diff","--quiet","HEAD","--",...i),!0}catch{return!1}},"filesMatchHead");function H(){if(!r||E())return;const t=u();t===null||f===null||t===f||!A()||o(t,`HEAD moved to ${t.slice(0,7)} and the hub's files match it`)}e(H,"check");function D(){o(`npm-${Date.now()}`,"kickflip update finished")}return e(D,"restartNow"),{check:H,restartNow:D}}e(w,"restarter");export{w as restarter};
package/hub/sessions.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var ne=Object.defineProperty;var a=(e,s)=>ne(e,"name",{value:s,configurable:!0});import _ from"node:fs";import w from"node:path";import O from"node:os";import{spawn as K,spawnSync as oe}from"node:child_process";import{fileURLToPath as ie}from"node:url";import{joinName as re,routeRecord as h,validRoute as ae}from"./routes.mjs";import{withFileLock as ce}from"./locks.mjs";import{RESUME_STATE as D,carryCursor as ue,hubBoard as W,isListening as de,listBoards as L,listenState as le,oldestUnheard as fe,readManifest as S,readJSON as P,saveJSON as J,watchedCounts as pe,watchedLines as me,watcherCursor as he,withManifestLock as we,writeManifest as ge}from"./boards.mjs";import{readUsageGate as be,heldUsageEvent as ke}from"../shared/usage-gate.mjs";import{liveSessions as T,sessionRecords as $e,processStarts as ye,verifiedProcess as Se}from"./live.mjs";import{deliver as Ie}from"./push.mjs";import{WAIT_MS as Te}from"./prompts.mjs";import{nodeBin as H,storedPath as X}from"../bin/install.mjs";import{reposDir as xe}from"../shared/repos.mjs";import{isClone as _e}from"./repos.mjs";import{trustFolder as Oe}from"./trust.mjs";import{contextFull as ve,contextReading as je}from"./usage.mjs";const v=X(w.resolve(w.dirname(ie(import.meta.url)),"..")),Ae=3*6e4,Ee=5*6e4,Ce=15*6e4,q=w.join(O.homedir(),".claude","kickflip","compact-state.json"),De=a((e,s=Date.now())=>!!e.error||s-Date.parse(e.asked_at||e.since)>=Ce,"startFailed");function Le(e){return e.session?{step:"landing",stepAt:e.since}:e.phase==="cloning"?{step:"cloning",stepAt:e.asked_at}:{step:"starting",stepAt:e.phase_at||e.asked_at||e.since}}a(Le,"startStep");function ps(e,s=Date.now(),t=()=>{}){return Object.entries(e.starting||{}).filter(([i])=>!h(e.sites,i)).map(([i,n])=>({route:i,title:n.title||n.label||i,repo:n.repo,...Le(n),...n.phase==="cloning"&&t(i)!==void 0?{percent:t(i)}:{},...n.branch?{branch:n.branch,tickets:n.tickets}:{},askedAt:n.asked_at||n.since,failed:De(n,s),...n.error?{error:n.error}:{}}))}a(ps,"startingBoards");const Pe=Te/1e3+60,Ue=JSON.stringify({worktree:{bgIsolation:"none"},permissions:{deny:["Workflow"]},hooks:{PermissionRequest:[{matcher:"*",hooks:[{type:"command",command:`"${H()}" "${w.join(v,"hub","permission-hook.mjs")}"`,timeout:Pe}]}],PermissionDenied:[{matcher:"Bash",hooks:[{type:"command",command:`"${H()}" "${w.join(v,"hub","permission-denied-hook.mjs")}"`,timeout:15}]}]}});class m extends Error{static{a(this,"SessionError")}constructor(s,t){super(s),this.reason=t}}function Ne(e,s){if(!ae(e))throw new m("Choose a board route.","none");return ce(w.join(O.homedir(),".claude","kickflip","session-locks",e),()=>s({resume:a(t=>Xe(e,t),"resume")}),{staleAfter:12e4,timeout:9e4})}a(Ne,"withSessionLock");function j(){if(process.env.KICKFLIP_CLAUDE)return process.env.KICKFLIP_CLAUDE;const e=w.join(O.homedir(),".local","bin","claude");return _.existsSync(e)?e:"claude"}a(j,"claudeBin");const A=a(e=>e==="CLAUDECODE"||e==="CLAUDE_PID"||e==="CLAUDE_EFFORT"||e.startsWith("CLAUDE_CODE_"),"inherited");function Q(){return process.env.KICKFLIP_TMUX?process.env.KICKFLIP_TMUX:["/opt/homebrew/bin/tmux","/usr/local/bin/tmux","/usr/bin/tmux"].find(e=>_.existsSync(e))||"tmux"}a(Q,"tmuxBin");function U(e){const s=oe(Q(),e,{encoding:"utf8",timeout:1e4,env:Object.fromEntries(Object.entries(process.env).filter(([t])=>!A(t)))});return s.error?.code==="ENOENT"?{status:127,stdout:"",stderr:"tmux isn't installed; kickflip doctor names how to install it"}:{status:s.status??1,stdout:s.stdout||"",stderr:s.stderr||s.error?.message||""}}a(U,"runTmux");const I=a(e=>`kickflip-${e}`,"tmuxName"),N=a((e,s)=>e(["has-session","-t",`=${I(s)}`]).status===0,"hasTmux");async function ms({manifest:e=S(),now:s=new Date,running:t=T(),wakes:i=P(D,{}),tmux:n=U}={}){if(!t)return{compacted:[],failed:[]};const r=Object.assign(Object.create(null),P(q,{})),o=[],l=[];let u=!1;const c=W(e)?.route;for(const p of L(e)){const f=je(p.owner?.session);if(!ve(le(p,{now:s.getTime(),running:t,wakes:i}),f)){h(r,p.route)&&(delete r[p.route],u=!0);continue}if(p.route!==c||h(r,p.route)||!N(n,p.route))continue;const d=`=${I(p.route)}:`,$=n(["send-keys","-t",d,"-l","/compact"]),k=$.status===0?n(["send-keys","-t",d,"Enter"]):$,g=k.status===0?null:(k.stderr||k.stdout).trim().slice(0,300)||`tmux exited ${k.status}`;r[p.route]={session:p.owner.session,percent:f.percent,at:s.toISOString(),...g?{error:g}:{}},u=!0,g?l.push(`${p.route}: could not send /compact to tmux session ${I(p.route)} (${g})`):o.push(p.route)}return u&&J(q,r),{compacted:o,failed:l}}a(ms,"compactFullContexts");function B(e,{cwd:s,timeout:t=6e4}){const i=j(),n=Object.fromEntries(Object.entries(process.env).filter(([r])=>!A(r)));return n.CLAUDE_BG_ISOLATION="none",w.isAbsolute(i)&&(n.PATH=`${w.dirname(i)}:${n.PATH||""}`),new Promise(r=>{let o="",l="",u;try{u=K(i,e,{cwd:s,env:n,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(f){r({status:1,stdout:o,stderr:f.message});return}const c=a(f=>{clearTimeout(p),u.stdout.destroy(),u.stderr.destroy(),r({status:f,stdout:o,stderr:l})},"done"),p=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}c(1)},t);u.stdout.on("data",f=>{o+=f}),u.stderr.on("data",f=>{l+=f}),u.on("error",f=>{l+=f.message,c(1)}),u.on("close",f=>c(f??1)),u.on("exit",f=>setTimeout(()=>c(f??1),300)),u.unref()})}a(B,"runClaude");async function Be(e,{cwd:s,run:t=B,starts:i=ye,signal:n=process.kill}={}){if(e.kind==="bg"){const r=await t(["stop",e.jobId||e.sessionId.slice(0,8)],{cwd:s,timeout:8e3});if(r.status!==0)throw new m(`claude stop failed: ${(r.stderr||r.stdout).trim().slice(0,300)}`,"failed")}else{if(!Se(e,i))throw new m(`Cannot verify session ${e.sessionId}'s process identity; refusing to signal pid ${e.pid}.`,"failed");n(e.pid,"SIGTERM")}}a(Be,"runSessionStop");async function hs(e,{live:s=T,stop:t=Be}={}){if(!e?.session)return;const i=s();if(!i)throw new m(ee(e.session),"unknown");const n=i.get(e.session);if(!n)return;await t(n,{cwd:e.repo||n.cwd||O.homedir()});const r=Date.now()+5e3;for(let o=s();!o||o.get(e.session)?.pid===n.pid;o=s()){if(Date.now()>=r)throw new m(`session ${e.session} did not stop`,"failed");await new Promise(l=>setTimeout(l,100))}}a(hs,"stopSession");function Me(e){const s=`=${I(e)}`;return Re(Q(),process.env.TMUX?["switch-client","-t",s]:["attach-session","-t",s])}a(Me,"attachTmux");function Re(e,s){const t=Object.fromEntries(Object.entries(process.env).filter(([r])=>!A(r)&&r!=="CLAUDE_BG_ISOLATION")),i=a(()=>{},"ignore");process.on("SIGINT",i).on("SIGQUIT",i);const n=a(()=>process.off("SIGINT",i).off("SIGQUIT",i),"settle");return new Promise((r,o)=>{const l=K(e,s,{env:t,stdio:"inherit"});l.on("error",u=>{n(),o(new m(u.message,"failed"))}),l.on("close",u=>{n(),r({status:u??1})})})}a(Re,"runForeground");const M=a(({name:e,model:s})=>["--name",e,"--permission-mode","auto","--settings",Ue,...s?["--model",s]:[]],"common"),Fe=a(e=>`'${e.replaceAll("'","'\\''")}'`,"quote"),E=a((e,s)=>`--name ${Fe(re(e,s))}`,"boardFlag"),Ge=a(({route:e,name:s,model:t,prompt:i})=>["--bg",...M({name:s,model:t}),`/kickflip ${E(e,s)}${i?` ${i}`:""}`],"startArgv"),Ke=a((e,s,t)=>`The hub resumed this session because /${e} had nobody listening. Rejoin the board as session ${s} (kickflip steps 3 and 5): rerun \`node ${w.join(v,"bin","kickflip.mjs")} join ${E(e,t)} --session ${s}\`, relaunch its watcher as a background task, then go on with what its events ask. If your session id (the folder above your scratchpad) isn't ${s}, rejoin with yours and --force.`,"resumePrompt"),We=a(({id:e,route:s,name:t,model:i,background:n})=>["--resume",e,"--bg",...n?[]:M({name:t,model:i}),Ke(s,e,t)],"resumeArgv"),Y=a((e,s)=>`You are the hub session. Read \`${w.join(v,"docs","hub-session.md")}\`, then rejoin /${e} (join ${E(e,s)}) and relaunch its watcher.`,"hubPrompt"),z=a(({route:e,title:s,id:t,model:i})=>[...t?["--resume",t]:[],...M({name:s,model:i}),t?`${Y(e,s)} If your session id (the folder above your scratchpad) isn't ${t}, rejoin with yours and --force.`:`/kickflip ${E(e,s)} --hub
2
- ${Y(e,s)}`],"hubArgv");function V(e,s,{cwd:t,tmux:i}){const n=j(),r=[...new Set(["CLAUDECODE","CLAUDE_BG_ISOLATION",...Object.keys(process.env).filter(A)])].flatMap(l=>["-u",l]),o=i(["new-session","-d","-s",I(e),"-c",t,"/usr/bin/env",...r,...w.isAbsolute(n)?[`PATH=${w.dirname(n)}:${process.env.PATH||""}`]:[],n,...s]);if(o.status!==0)throw new m(`tmux new-session failed (${o.status}): ${(o.stderr||o.stdout).trim().slice(0,300)}`,"failed");return[n,...s]}a(V,"startTmux");async function ws({manifest:e=S(),repo:s,tmux:t=U,attach:i=Me,live:n=T}={}){const r=W(e);if(!r)throw new m("No hub board is flagged; flag one with kickflip set <route> --hub, or run kickflip join --hub in its repo folder","hub");if(!N(t,r.route)){const o=r.owner?.session?r.owner:null;if(o&&!o.repo&&!s)throw new m(`/${r.route}'s session ${o.session} has no folder recorded; pass --repo <its folder>`,"none");F(o,n);const l=o?.repo||w.resolve(s||process.cwd());if(!_.statSync(l,{throwIfNoEntry:!1})?.isDirectory())throw new m(o?.repo?`/${r.route}'s recorded folder ${l} is gone; rejoin from its new folder with --repo`:`no folder at ${l}`,"none");V(r.route,z({route:r.route,title:r.title,id:o?.session,model:o?.model}),{cwd:l,tmux:t})}return i(r.route)}a(ws,"hubSession");function R(e,s){const t=h(e?.sites,s),i=t?.owner?.session?t.owner:h(e?.starting,s);return i?.session?{...i,title:t?.title||s}:null}a(R,"sessionOf");async function Z(e,s=null){const t=e.match(/backgrounded\s*·\s*([0-9a-f]{8})\b/)?.[1]||e.match(/\bclaude attach ([0-9a-f]{8})\b/)?.[1];if(!t)return{session:s,confirmed:!1};if(s?.startsWith(t))return{session:s,confirmed:!0};for(let i=0;i<20;i++){const n=$e().find(r=>r.jobId===t||r.sessionId.startsWith(t));if(n)return{session:n.sessionId,confirmed:!0};await new Promise(r=>setTimeout(r,500))}return{session:s,confirmed:!1}}a(Z,"startedId");async function Je(e,{run:s,cwd:t}){const i=await s(["agents","--json","--all"],{cwd:t});try{return JSON.parse(i.stdout).some(n=>n?.sessionId===e&&n.kind==="background")}catch{return!1}}a(Je,"isBackground");const ee=a(e=>`Couldn't tell whether session ${e} is live: ps gave no answer in time, as happens on a busy Mac. Try again in a moment.`,"unknownLiveness");function F(e,s){if(!e)return;const t=s();if(!t)throw new m(ee(e.session),"unknown");const i=t.get(e.session);if(i)throw new m(`session ${e.session} is live (${i.kind==="bg"?"in the background":"in a terminal"}, pid ${i.pid}); it gets no second process`,"live")}a(F,"refuseLive");async function se(e,{from:s,to:t,mark:i}){await we(async()=>{const n=S(),r=L(n).find(l=>l.route===e);if(r?.owner?.session===s&&(i||t!==s)&&ue(r,{from:s,to:t,mark:i}),t===s)return;const o=h(n.sites,e);if(o?.owner?.session===s)Object.assign(o,{owner:{...o.owner,session:t},updated:new Date().toISOString()});else if(h(n.starting,e)?.session===s)n.starting[e]={...h(n.starting,e),session:t};else return;await ge(n)})}a(se,"moveOwner");async function gs(e,{manifest:s=S(),repo:t,model:i,prompt:n,run:r=B,live:o=T,clones:l=xe()}={}){if(h(s.closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const u=R(s,e);F(u,o);const c=w.resolve(t||u?.repo||process.cwd());if(!_.statSync(c,{throwIfNoEntry:!1})?.isDirectory())throw new m(`no folder at ${c}`,"none");if(_e(c,l))try{Oe(c)}catch(g){throw new m(`Couldn't trust this folder for Claude Code: ${g.message}`,"failed")}const p=h(s?.sites,e)?.title||h(s?.starting,e)?.title||e,f=Ge({route:e,name:p,model:i||u?.model,prompt:n}),d=await r(f,{cwd:c});if(d.status!==0){const g=(d.stderr||"").trim()||(d.stdout||"").trim();throw new m(g?`claude --bg failed (${d.status}): ${g.slice(0,300)}`:`claude exited ${d.status} with no output; check \`claude agents\``,"failed")}const{session:$,confirmed:k}=await Z(d.stdout);if(!$)throw new m(`claude --bg started a session but no session record names it yet; find it with claude agents (${d.stdout.trim().slice(0,300)})`,"failed");return{route:e,session:$,confirmed:k,repo:X(c),model:i||u?.model||null,name:p,argv:[j(),...f],output:d.stdout.trim()}}a(gs,"startSession");function He(e,s={}){return Ne(e,({resume:t})=>t(s))}a(He,"resumeSession");async function Xe(e,{manifest:s=S(),run:t=B,tmux:i=U,live:n=T,mark:r=null}={}){if(h(S().closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const o=R(s,e);if(!o)throw new m(`/${e} has no recorded session`,"none");if(!o.repo)throw new m(`/${e}'s session ${o.session} has no folder recorded; its session records one by rejoining (kickflip join, --repo)`,"none");if(F(o,n),h(s.sites,e)?.hub===!0){if(N(i,e))throw new m(`/${e}'s tmux session ${I(e)} is still open; attach with kickflip hub`,"live");const d=V(e,z({route:e,title:o.title,id:o.session,model:o.model}),{cwd:o.repo,tmux:i});return await se(e,{from:o.session,to:o.session,mark:r}),{route:e,session:o.session,previous:o.session,confirmed:!1,repo:o.repo,argv:d,output:`in tmux session ${I(e)}`}}const l=await Je(o.session,{run:t,cwd:o.repo}),u=We({id:o.session,route:e,name:o.title,model:o.model,background:l}),c=await t(u,{cwd:o.repo});if(c.status!==0)throw new m(`claude --resume failed (${c.status}): ${(c.stderr||c.stdout).trim().slice(0,300)}`,"failed");const{session:p,confirmed:f}=await Z(c.stdout,o.session);return await se(e,{from:o.session,to:p,mark:r}),{route:e,session:p,previous:o.session,confirmed:f,repo:o.repo,argv:[j(),...u],output:c.stdout.trim()}}a(Xe,"resumeRecordedSession");function qe(e,{listening:s,live:t,recorded:i,counts:n,waiting:r,asked:o=!1,now:l}){if(s)return{action:"none",entry:null};const u=new Date(l).toISOString(),c=e?{...e}:{down_since:u};return t?delete c.mark:!c.mark&&n&&(c.mark=n),c.pushed_at?{action:"none",entry:c}:c.resumed_at?c.error||l-Date.parse(c.resumed_at)>=Ee?{action:"push",entry:{...c,pushed_at:u}}:{action:"none",entry:c}:!i||t?{action:"none",entry:c}:!!(e?.mark&&n&&Object.entries(n).some(([f,d])=>d>(h(e.mark,f)??0)))||o||r&&l-Date.parse(c.down_since)>=Ae?{action:"resume",entry:{...c,resumed_at:u}}:{action:"none",entry:c}}a(qe,"resumeStep");async function bs({manifest:e=S(),now:s=new Date,live:t=T,asked:i=new Set,listening:n=a((u,c)=>de(u,{now:s.getTime(),running:c}),"listening"),resume:r=a((u,c)=>He(u,{manifest:e,live:t,mark:c}),"resume"),push:o=Ie,gate:l=be({now:s})}={}){const u=t();if(!u)return{resumed:[],pushed:[],failed:[]};const c=P(D,{}),p=Object.create(null),f={resumed:[],pushed:[],failed:[]};for(const d of L(e)){const $=R(e,d.route),k=!!($&&u.has($.session)),g=n(d,u);let{action:x,entry:b}=qe(h(c,d.route),{listening:g,live:k,recorded:!!$?.repo,now:s.getTime(),asked:i.has(d.route),counts:g?null:pe(d),waiting:!g&&!k&&fe(d)!==null});if(x==="resume"&&l.state==="paused"){const y=h(c,d.route)?.mark||he(d);Object.entries(me(d)).flatMap(([C,te])=>te.slice(h(y,C)||0)).some(C=>!ke(C))||(x="none",delete b.resumed_at)}if(x==="resume")try{await r(d.route,b.mark),f.resumed.push(d.route)}catch(y){y.reason==="unknown"?delete b.resumed_at:b={...b,error:y.message},f.failed.push(`${d.route}: could not resume its session (${y.message})`)}else if(x==="push"){const y=b.error?`The hub couldn't resume it: ${b.error}`:k?"Its session is running but hasn't relaunched its watcher.":`It still isn't listening after the hub resumed it. Try kickflip resume ${d.route}, or claude agents.`;try{await o({title:`${d.title}'s session didn't come back`,body:y,url:`/${d.route}/`,tag:`resume-${d.route}`},{kind:"fault",immediate:!0,at:s}),f.pushed.push(d.route)}catch(G){b={...b,pushed_at:void 0},f.failed.push(`${d.route}: could not push that its session didn't come back (${G.message})`)}}b&&(p[d.route]=b)}return JSON.stringify(p)!==JSON.stringify(c)&&J(D,p),f}a(bs,"checkSessions");export{Ue as BG_SETTINGS,Ee as COMEBACK_WAIT,Pe as PROMPT_HOOK_TIMEOUT_S,Ae as RESUME_AFTER,Ce as STARTING_WAIT,m as SessionError,Me as attachTmux,bs as checkSessions,j as claudeBin,ms as compactFullContexts,z as hubArgv,ws as hubSession,A as inherited,We as resumeArgv,Ke as resumePrompt,He as resumeSession,qe as resumeStep,B as runClaude,Be as runSessionStop,U as runTmux,R as sessionOf,Ge as startArgv,De as startFailed,gs as startSession,ps as startingBoards,hs as stopSession,Q as tmuxBin,I as tmuxName,Ne as withSessionLock};
1
+ var ce=Object.defineProperty;var a=(e,s)=>ce(e,"name",{value:s,configurable:!0});import O from"node:fs";import g from"node:path";import A from"node:os";import{spawn as J,spawnSync as de}from"node:child_process";import{fileURLToPath as ue}from"node:url";import{joinName as le,routeRecord as h,validRoute as fe}from"./routes.mjs";import{withFileLock as pe}from"./locks.mjs";import{RESUME_STATE as P,carryCursor as me,hubBoard as H,isListening as he,listBoards as U,listenState as we,oldestUnheard as ge,readManifest as _,readJSON as N,saveJSON as X,watchedCounts as be,watchedLines as $e,watcherCursor as ke,withManifestLock as ye,writeManifest as Ie}from"./boards.mjs";import{readUsageGate as Se,heldUsageEvent as _e}from"../shared/usage-gate.mjs";import{liveSessions as x,sessionRecords as Te,processStarts as xe,verifiedProcess as je}from"./live.mjs";import{deliver as ve}from"./push.mjs";import{WAIT_MS as Oe}from"./prompts.mjs";import{nodeBin as q,storedPath as Q}from"../bin/install.mjs";import{reposDir as Ae}from"../shared/repos.mjs";import{isClone as Ee}from"./repos.mjs";import{trustFolder as Ce}from"./trust.mjs";import{contextFull as De,contextReading as Le}from"./usage.mjs";import{audit as Y,boardAudit as z}from"../shared/audit.mjs";const E=Q(g.resolve(g.dirname(ue(import.meta.url)),"..")),Pe=3*6e4,Ue=5*6e4,Ne=15*6e4,V=g.join(A.homedir(),".claude","kickflip","compact-state.json"),Be=a((e,s=Date.now())=>!!e.error||s-Date.parse(e.asked_at||e.since)>=Ne,"startFailed");function Me(e){return e.joined_at?{step:"landing",stepAt:e.joined_at}:e.phase==="cloning"?{step:"cloning",stepAt:e.asked_at}:{step:"starting",stepAt:e.phase_at||e.asked_at||e.since}}a(Me,"startStep");function $s(e,s=Date.now(),t=()=>{},r=()=>!0){return Object.entries(e.starting||{}).filter(([i,n])=>h(e.sites,i)?n.joined_at&&!r(i):!0).map(([i,n])=>{const o=Be(n,s);return{route:i,title:n.title||n.label||i,repo:n.repo,...Me(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:o,...n.joined_at?{joined:!0}:{},...n.error?{error:n.error}:o&&n.joined_at?{error:"Its session joined, but the board is not listening yet."}:{}}})}a($s,"startingBoards");const Re=Oe/1e3+60,Fe=JSON.stringify({worktree:{bgIsolation:"none"},permissions:{deny:["Workflow"]},hooks:{PermissionRequest:[{matcher:"*",hooks:[{type:"command",command:`"${q()}" "${g.join(E,"hub","permission-hook.mjs")}"`,timeout:Re}]}],PermissionDenied:[{matcher:"Bash",hooks:[{type:"command",command:`"${q()}" "${g.join(E,"hub","permission-denied-hook.mjs")}"`,timeout:15}]}]}});class m extends Error{static{a(this,"SessionError")}constructor(s,t){super(s),this.reason=t}}function Ge(e,s){if(!fe(e))throw new m("Choose a board route.","none");return pe(g.join(A.homedir(),".claude","kickflip","session-locks",e),()=>s({resume:a(t=>Ve(e,t),"resume")}),{staleAfter:12e4,timeout:9e4})}a(Ge,"withSessionLock");function C(){if(process.env.KICKFLIP_CLAUDE)return process.env.KICKFLIP_CLAUDE;const e=g.join(A.homedir(),".local","bin","claude");return O.existsSync(e)?e:"claude"}a(C,"claudeBin");const D=a(e=>e==="CLAUDECODE"||e==="CLAUDE_PID"||e==="CLAUDE_EFFORT"||e.startsWith("CLAUDE_CODE_"),"inherited");function Z(){return process.env.KICKFLIP_TMUX?process.env.KICKFLIP_TMUX:["/opt/homebrew/bin/tmux","/usr/local/bin/tmux","/usr/bin/tmux"].find(e=>O.existsSync(e))||"tmux"}a(Z,"tmuxBin");function B(e){const s=de(Z(),e,{encoding:"utf8",timeout:1e4,env:Object.fromEntries(Object.entries(process.env).filter(([t])=>!D(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(B,"runTmux");const T=a(e=>`kickflip-${e}`,"tmuxName"),M=a((e,s)=>e(["has-session","-t",`=${T(s)}`]).status===0,"hasTmux");async function ks({manifest:e=_(),now:s=new Date,running:t=x(),wakes:r=N(P,{}),tmux:i=B}={}){if(!t)return{compacted:[],failed:[]};const n=Object.assign(Object.create(null),N(V,{})),o=[],f=[];let u=!1;const c=H(e)?.route;for(const p of U(e)){const l=Le(p.owner?.session);if(!De(we(p,{now:s.getTime(),running:t,wakes:r}),l)){h(n,p.route)&&(delete n[p.route],u=!0);continue}if(p.route!==c||h(n,p.route)||!M(i,p.route))continue;const d=`=${T(p.route)}:`,y=i(["send-keys","-t",d,"-l","/compact"]),b=y.status===0?i(["send-keys","-t",d,"Enter"]):y,w=b.status===0?null:(b.stderr||b.stdout).trim().slice(0,300)||`tmux exited ${b.status}`;n[p.route]={session:p.owner.session,percent:l.percent,at:s.toISOString(),...w?{error:w}:{}},Y(z(p.dir),{call:"compact",result:w?"failed":"typed /compact",reason:`Its session's context is ${l.percent}% full and it isn't listening.${w?` ${w}`:""}`,inputs:{session:p.owner.session,context:l}},{now:s}),u=!0,w?f.push(`${p.route}: could not send /compact to tmux session ${T(p.route)} (${w})`):o.push(p.route)}return u&&X(V,n),{compacted:o,failed:f}}a(ks,"compactFullContexts");function R(e,{cwd:s,timeout:t=6e4}){const r=C(),i=Object.fromEntries(Object.entries(process.env).filter(([n])=>!D(n)));return i.CLAUDE_BG_ISOLATION="none",g.isAbsolute(r)&&(i.PATH=`${g.dirname(r)}:${i.PATH||""}`),new Promise(n=>{let o="",f="",u;try{u=J(r,e,{cwd:s,env:i,detached:!0,stdio:["ignore","pipe","pipe"]})}catch(l){n({status:1,stdout:o,stderr:l.message});return}const c=a(l=>{clearTimeout(p),u.stdout.destroy(),u.stderr.destroy(),n({status:l,stdout:o,stderr:f})},"done"),p=setTimeout(()=>{try{u.kill("SIGKILL")}catch{}c(1)},t);u.stdout.on("data",l=>{o+=l}),u.stderr.on("data",l=>{f+=l}),u.on("error",l=>{f+=l.message,c(1)}),u.on("close",l=>c(l??1)),u.on("exit",l=>setTimeout(()=>c(l??1),300)),u.unref()})}a(R,"runClaude");async function Ke(e,{cwd:s,run:t=R,starts:r=xe,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 m(`claude stop failed: ${(n.stderr||n.stdout).trim().slice(0,300)}`,"failed")}else{if(!je(e,r))throw new m(`Cannot verify session ${e.sessionId}'s process identity; refusing to signal pid ${e.pid}.`,"failed");i(e.pid,"SIGTERM")}}a(Ke,"runSessionStop");async function ys(e,{live:s=x,stop:t=Ke}={}){if(!e?.session)return;const r=s();if(!r)throw new m(oe(e.session),"unknown");const i=r.get(e.session);if(!i)return;await t(i,{cwd:e.repo||i.cwd||A.homedir()});const n=Date.now()+5e3;for(let o=s();!o||o.get(e.session)?.pid===i.pid;o=s()){if(Date.now()>=n)throw new m(`session ${e.session} did not stop`,"failed");await new Promise(f=>setTimeout(f,100))}}a(ys,"stopSession");function We(e){const s=`=${T(e)}`;return Je(Z(),process.env.TMUX?["switch-client","-t",s]:["attach-session","-t",s])}a(We,"attachTmux");function Je(e,s){const t=Object.fromEntries(Object.entries(process.env).filter(([n])=>!D(n)&&n!=="CLAUDE_BG_ISOLATION")),r=a(()=>{},"ignore");process.on("SIGINT",r).on("SIGQUIT",r);const i=a(()=>process.off("SIGINT",r).off("SIGQUIT",r),"settle");return new Promise((n,o)=>{const f=J(e,s,{env:t,stdio:"inherit"});f.on("error",u=>{i(),o(new m(u.message,"failed"))}),f.on("close",u=>{i(),n({status:u??1})})})}a(Je,"runForeground");const F=a(({name:e,model:s})=>["--name",e,"--permission-mode","auto","--settings",Fe,...s?["--model",s]:[]],"common"),He=a(e=>`'${e.replaceAll("'","'\\''")}'`,"quote"),L=a((e,s)=>`--name ${He(le(e,s))}`,"boardFlag"),Xe=a(({route:e,name:s,model:t,prompt:r})=>["--bg",...F({name:s,model:t}),`/kickflip ${L(e,s)}${r?` ${r}`:""}`],"startArgv"),qe=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 ${g.join(E,"bin","kickflip.mjs")} join ${L(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"),Qe=a(({id:e,route:s,name:t,model:r,background:i})=>["--resume",e,"--bg",...i?[]:F({name:t,model:r}),qe(s,e,t)],"resumeArgv"),ee=a((e,s)=>`You are the hub session. Read \`${g.join(E,"docs","hub-session.md")}\`, then rejoin /${e} (join ${L(e,s)}) and relaunch its watcher.`,"hubPrompt"),se=a(({route:e,title:s,id:t,model:r})=>[...t?["--resume",t]:[],...F({name:s,model:r}),t?`${ee(e,s)} If your session id (the folder above your scratchpad) isn't ${t}, rejoin with yours and --force.`:`/kickflip ${L(e,s)} --hub
2
+ ${ee(e,s)}`],"hubArgv");function te(e,s,{cwd:t,tmux:r}){const i=C(),n=[...new Set(["CLAUDECODE","CLAUDE_BG_ISOLATION",...Object.keys(process.env).filter(D)])].flatMap(f=>["-u",f]),o=r(["new-session","-d","-s",T(e),"-c",t,"/usr/bin/env",...n,...g.isAbsolute(i)?[`PATH=${g.dirname(i)}:${process.env.PATH||""}`]:[],i,...s]);if(o.status!==0)throw new m(`tmux new-session failed (${o.status}): ${(o.stderr||o.stdout).trim().slice(0,300)}`,"failed");return[i,...s]}a(te,"startTmux");async function Is({manifest:e=_(),repo:s,tmux:t=B,attach:r=We,live:i=x}={}){const n=H(e);if(!n)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(!M(t,n.route)){const o=n.owner?.session?n.owner:null;if(o&&!o.repo&&!s)throw new m(`/${n.route}'s session ${o.session} has no folder recorded; pass --repo <its folder>`,"none");K(o,i);const f=o?.repo||g.resolve(s||process.cwd());if(!O.statSync(f,{throwIfNoEntry:!1})?.isDirectory())throw new m(o?.repo?`/${n.route}'s recorded folder ${f} is gone; rejoin from its new folder with --repo`:`no folder at ${f}`,"none");te(n.route,se({route:n.route,title:n.title,id:o?.session,model:o?.model}),{cwd:f,tmux:t})}return r(n.route)}a(Is,"hubSession");function G(e,s){const t=h(e?.sites,s),r=t?.owner?.session?t.owner:h(e?.starting,s);return r?.session?{...r,title:t?.title||s}:null}a(G,"sessionOf");async function ne(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 r=0;r<20;r++){const i=Te().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}}a(ne,"startedId");async function Ye(e,{run:s,cwd:t}){const r=await s(["agents","--json","--all"],{cwd:t});try{return JSON.parse(r.stdout).some(i=>i?.sessionId===e&&i.kind==="background")}catch{return!1}}a(Ye,"isBackground");const oe=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 K(e,s){if(!e)return;const t=s();if(!t)throw new m(oe(e.session),"unknown");const r=t.get(e.session);if(r)throw new m(`session ${e.session} is live (${r.kind==="bg"?"in the background":"in a terminal"}, pid ${r.pid}); it gets no second process`,"live")}a(K,"refuseLive");async function ie(e,{from:s,to:t,mark:r}){await ye(async()=>{const i=_(),n=U(i).find(f=>f.route===e);if(n?.owner?.session===s&&(r||t!==s)&&me(n,{from:s,to:t,mark:r}),t===s)return;const o=h(i.sites,e);if(o?.owner?.session===s)Object.assign(o,{owner:{...o.owner,session:t},updated:new Date().toISOString()});else if(h(i.starting,e)?.session===s)i.starting[e]={...h(i.starting,e),session:t};else return;await Ie(i)})}a(ie,"moveOwner");async function Ss(e,{manifest:s=_(),repo:t,model:r,prompt:i,run:n=R,live:o=x,clones:f=Ae()}={}){if(h(s.closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const u=G(s,e);K(u,o);const c=g.resolve(t||u?.repo||process.cwd());if(!O.statSync(c,{throwIfNoEntry:!1})?.isDirectory())throw new m(`no folder at ${c}`,"none");if(Ee(c,f))try{Ce(c)}catch(w){throw new m(`Couldn't trust this folder for Claude Code: ${w.message}`,"failed")}const p=h(s?.sites,e)?.title||h(s?.starting,e)?.title||e,l=Xe({route:e,name:p,model:r||u?.model,prompt:i}),d=await n(l,{cwd:c});if(d.status!==0){const w=(d.stderr||"").trim()||(d.stdout||"").trim();throw new m(w?`claude --bg failed (${d.status}): ${w.slice(0,300)}`:`claude exited ${d.status} with no output; check \`claude agents\``,"failed")}const{session:y,confirmed:b}=await ne(d.stdout);if(!y)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:y,confirmed:b,repo:Q(c),model:r||u?.model||null,name:p,argv:[C(),...l],output:d.stdout.trim()}}a(Ss,"startSession");function ze(e,s={}){return Ge(e,({resume:t})=>t(s))}a(ze,"resumeSession");async function Ve(e,{manifest:s=_(),run:t=R,tmux:r=B,live:i=x,mark:n=null}={}){if(h(_().closed,e))throw new m(`/${e} is closed; use kickflip reopen ${e}`,"none");const o=G(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(K(o,i),h(s.sites,e)?.hub===!0){if(M(r,e))throw new m(`/${e}'s tmux session ${T(e)} is still open; attach with kickflip hub`,"live");const d=te(e,se({route:e,title:o.title,id:o.session,model:o.model}),{cwd:o.repo,tmux:r});return await ie(e,{from:o.session,to:o.session,mark:n}),{route:e,session:o.session,previous:o.session,confirmed:!1,repo:o.repo,argv:d,output:`in tmux session ${T(e)}`}}const f=await Ye(o.session,{run:t,cwd:o.repo}),u=Qe({id:o.session,route:e,name:o.title,model:o.model,background:f}),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:l}=await ne(c.stdout,o.session);return await ie(e,{from:o.session,to:p,mark:n}),{route:e,session:p,previous:o.session,confirmed:l,repo:o.repo,argv:[C(),...u],output:c.stdout.trim()}}a(Ve,"resumeRecordedSession");function Ze(e,{listening:s,live:t,recorded:r,counts:i,waiting:n,asked:o=!1,now:f}){if(s)return{action:"none",entry:null};const u=new Date(f).toISOString(),c=e?{...e}:{down_since:u};return t?delete c.mark:!c.mark&&i&&(c.mark=i),c.pushed_at?{action:"none",entry:c}:c.resumed_at?c.error||f-Date.parse(c.resumed_at)>=Ue?{action:"push",entry:{...c,pushed_at:u}}:{action:"none",entry:c}:!r||t?{action:"none",entry:c}:!!(e?.mark&&i&&Object.entries(i).some(([l,d])=>d>(h(e.mark,l)??0)))||o||n&&f-Date.parse(c.down_since)>=Pe?{action:"resume",entry:{...c,resumed_at:u}}:{action:"none",entry:c}}a(Ze,"resumeStep");async function _s({manifest:e=_(),now:s=new Date,live:t=x,asked:r=new Set,listening:i=a((u,c)=>he(u,{now:s.getTime(),running:c}),"listening"),resume:n=a((u,c)=>ze(u,{manifest:e,live:t,mark:c}),"resume"),push:o=ve,gate:f=Se({now:s})}={}){const u=t();if(!u)return{resumed:[],pushed:[],failed:[]};const c=N(P,{}),p=Object.create(null),l={resumed:[],pushed:[],failed:[]};for(const d of U(e)){const y=G(e,d.route),b=!!(y&&u.has(y.session)),w=i(d,u);let{action:j,entry:$}=Ze(h(c,d.route),{listening:w,live:b,recorded:!!y?.repo,now:s.getTime(),asked:r.has(d.route),counts:w?null:be(d),waiting:!w&&!b&&ge(d)!==null});if(j==="resume"&&f.state==="paused"){const I=h(c,d.route)?.mark||ke(d);Object.entries($e(d)).flatMap(([S,ae])=>ae.slice(h(I,S)||0)).some(S=>!_e(S))||(j="none",delete $.resumed_at)}const W=h(c,d.route),re={listening:w,live:b,asked:r.has(d.route),downSince:W?.down_since??null,resumedAt:W?.resumed_at??null},v=a((I,k,S)=>Y(z(d.dir),{call:I,result:k,reason:S,inputs:re},{now:s}),"logged");if(j==="resume"){const I=r.has(d.route)?"The owner opened the board's page while its session wasn't listening.":"An event waited while the board's session wasn't listening.";try{await n(d.route,$.mark),l.resumed.push(d.route),v("session-resume","resumed",I)}catch(k){k.reason==="unknown"?delete $.resumed_at:$={...$,error:k.message},l.failed.push(`${d.route}: could not resume its session (${k.message})`),v("session-resume","failed",`${I} ${k.message}`)}}else if(j==="push"){const I=$.error?`The hub couldn't resume it: ${$.error}`:b?"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.`,k=`Its session didn't come back after the hub resumed it: ${I}`;try{await o({title:`${d.title}'s session didn't come back`,body:I,url:`/${d.route}/`,tag:`resume-${d.route}`},{kind:"fault",immediate:!0,at:s}),l.pushed.push(d.route),v("push","sent",k)}catch(S){$={...$,pushed_at:void 0},l.failed.push(`${d.route}: could not push that its session didn't come back (${S.message})`),v("push","not sent",`${k} Not sent: ${S.message}`)}}$&&(p[d.route]=$)}return JSON.stringify(p)!==JSON.stringify(c)&&X(P,p),l}a(_s,"checkSessions");export{Fe as BG_SETTINGS,Ue as COMEBACK_WAIT,Re as PROMPT_HOOK_TIMEOUT_S,Pe as RESUME_AFTER,Ne as STARTING_WAIT,m as SessionError,We as attachTmux,_s as checkSessions,C as claudeBin,ks as compactFullContexts,se as hubArgv,Is as hubSession,D as inherited,Qe as resumeArgv,qe as resumePrompt,ze as resumeSession,Ze as resumeStep,R as runClaude,Ke as runSessionStop,B as runTmux,G as sessionOf,Xe as startArgv,Be as startFailed,Ss as startSession,$s as startingBoards,ys as stopSession,Z as tmuxBin,T as tmuxName,Ge as withSessionLock};
package/hub/share.mjs ADDED
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var u=(t,e)=>m(t,"name",{value:e,configurable:!0});import E from"node:path";import{isBoardSite as _,readJSON as w,saveJSON as b}from"./boards.mjs";const g=u(t=>typeof t=="string"&&t.length<=200&&/^[^\s@]+@[^\s@]+$/.test(t),"validLogin"),y=u(t=>Array.isArray(t?.share)?[...new Set(t.share.filter(g))]:[],"shareOf");function M(t,e){const i=new Set;for(const[c,s]of Object.entries(e||{}))_(s)&&y(w(E.join(s.dir,"board.json"),{})).includes(t)&&i.add(c);return i}u(M,"sharedRoutes");const x=new Set(["/","/sw.js","/manifest.webmanifest","/favicon.ico"]),R=/^\/_hub\/(?:app\/[\w.-]+|colors\.css|kickflip\.png|hub\.css|icon-(?:180|192|512)\.png|sidebar\.json|stream)$/,j=new Set(["/_hub","/_hub/","/_hub/settings","/_hub/settings/polling"]),D=new RegExp("^/(?:"+["","questions\\.html","notes\\.html","plan\\.html","index\\.html","prototype-[a-z0-9-]+\\.html","[\\w-][\\w.-]*\\.(?:js|mjs|css|png|svg|ico|webp|jpe?g|gif|woff2?)","prototypes/[a-z0-9-]+/[\\w-][\\w.-]*\\.js","uploads/[^/]+","api/(?:board|questions|done|links|working|thread|notes|plan|try/main/log)"].join("|")+")$");function U({method:t="GET",pathname:e,routes:i}){const c=t==="GET"||t==="HEAD";if(x.has(e)||R.test(e))return c?"pass":"view-only";if(j.has(e))return c?"home":"other";const s=/^\/([^/]+)(\/.*)?$/.exec(e);if(!s||!i.has(s[1]))return"other";const l=s[2]||"/";return l===`/${s[1]}`||l.startsWith(`/${s[1]}/`)?"view-only":c&&D.test(l)?"pass":"view-only"}u(U,"shareReach");function B(t){const e=String(t||"").split("/")[1]||"";if(!e||e==="_hub"||e.includes("."))return null;try{return decodeURIComponent(e)}catch{return null}}u(B,"routeOfPath");function F(t,e,i){const c=(t?.sites||[]).filter(s=>e.has(s.route)).map(({count:s,ctx:l,...p})=>p);return{code:t?.code??null,total:0,start:c[0]?.route??null,sites:c,starting:[],shared:{by:i||null}}}u(F,"sharedSidebar");const O=60*6e4,v=20,A=6e4;function H({file:t,now:e=Date.now}={}){const i=w(t,{}),c=new Map,s=new Map,l=new Map;let p=[];const S=u(()=>{try{b(t,i)}catch{}},"save");return{visit(n,o,r){const a=i[n]||={name:null,at:{}};let f=!1;if(o&&a.name!==o&&(a.name=o,f=!0),r){l.set(n,r);const h=new Date(e()).toISOString();a.at[r]=h;const d=`${n} ${r}`;e()-(c.get(d)??-1/0)<A||(c.set(d,e()),f=!0)}f&&S()},watching(n){return s.set(n,(s.get(n)||0)+1),()=>{const o=s.get(n)-1;o>0?s.set(n,o):s.delete(n)}},refuse(n,o,r){p=[{login:n,name:o||null,route:r||null,at:new Date(e()).toISOString()},...p.filter(a=>a.login!==n)].slice(0,v)},people(n,o){return o.map(r=>({login:r,name:i[r]?.name||null,now:s.has(r)&&l.get(r)===n,at:i[r]?.at?.[n]||null}))},refusals(n,o){const r=e()-O;return p.filter(a=>Date.parse(a.at)>=r&&(a.route===n||a.route===null)&&!o.includes(a.login)).map(({login:a,name:f,at:h})=>({login:a,name:f,at:h}))}}}u(H,"shareTracker");export{B as routeOfPath,y as shareOf,U as shareReach,H as shareTracker,M as sharedRoutes,F as sharedSidebar,g as validLogin};
package/hub/slack.mjs CHANGED
@@ -1,2 +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};
1
+ var v=Object.defineProperty;var n=(r,e)=>v(r,"name",{value:e,configurable:!0});import u from"node:fs";import d from"node:path";import p from"node:os";import{withFileLock as x}from"./locks.mjs";import{readSecret as $,writeSecret as f}from"./secrets.mjs";const l=["self_dm","owner_slack_user","slack_domain","timezone"],k=n(()=>d.join(p.homedir(),".claude","kickflip","slack.json"),"fileOf"),w=n(r=>{try{return JSON.parse(u.readFileSync(r,"utf8"))||{}}catch{return{}}},"read"),S=n(r=>Object.fromEntries(l.map(e=>[e,typeof r?.[e]=="string"?r[e]:""])),"identityOf");function y(r){const e=k();u.mkdirSync(d.dirname(e),{recursive:!0});const t=`${e}.${process.pid}.tmp`;return u.writeFileSync(t,JSON.stringify(r,null,2)+`
2
+ `,{mode:384}),u.chmodSync(t,384),u.renameSync(t,e),r}n(y,"save");function _(){const r=S(w(k()));if(l.some(t=>r[t]))return r;const e=S(w(d.join(p.homedir(),".claude","slack-bridge","state.json")).config);return l.some(t=>e[t])?y(e):r}n(_,"readSlack");async function I(r){for(const[e,t]of Object.entries(r)){if(!l.includes(e)||typeof t!="string")throw new Error(`Unknown Slack setting ${e}`);if(e==="self_dm"&&t&&!/^D[A-Z0-9]+$/.test(t))throw new Error("self-dm must be a DM channel id");if(e==="owner_slack_user"&&t&&!/^U[A-Z0-9]+$/.test(t))throw new Error("user must be a Slack user id");if(e==="slack_domain"&&t&&!/^[a-z0-9][a-z0-9-]*$/.test(t))throw new Error("domain must be a Slack workspace domain");if(e==="timezone"&&t)try{new Intl.DateTimeFormat("en",{timeZone:t})}catch{throw new Error("timezone must be an IANA timezone such as Area/City")}}return x(k(),()=>y({..._(),...r}))}n(I,"setSlack");function N(r=new Date){const e=_().timezone||Intl.DateTimeFormat().resolvedOptions().timeZone,t=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",hourCycle:"h23"}).formatToParts(r).map(({type:c,value:a})=>[c,a]));return{date:`${t.year}-${t.month}-${t.day}`,morning:!["Sat","Sun"].includes(t.weekday)&&Number(t.hour)>=9}}n(N,"slackDay");class m extends Error{static{n(this,"SlackError")}constructor(e,t=502){super(e),this.status=t}}const E=n(()=>process.env.KICKFLIP_SLACK_URL||"https://slack.com/api","api"),O=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive"];function g(r,{fetch:e=globalThis.fetch,checked:t=n(()=>{},"checked")}={}){async function c(a,i={}){let o;try{const s=await e(`${E()}/${a}`,{method:"POST",headers:{"content-type":"application/json; charset=utf-8",authorization:`Bearer ${r}`},body:JSON.stringify(i),signal:AbortSignal.timeout(15e3)});if(o=await s.json().catch(()=>null),!o)throw new Error(`Slack answered ${s.status}`)}catch(s){throw new m(`Could not reach Slack: ${s.message}`)}if(O.includes(o.error))throw t(!1),new m("Slack refused the token.",400);if(t(!0),!o.ok)throw new m(`Slack: ${o.error}`);return o}return n(c,"call"),{async who(){const{team:a,team_id:i,user:o,user_id:s}=await c("auth.test");return{team:a,team_id:i,user:o,user_id:s}},async people(){const a=[];let i="";do{const o=await c("users.list",{limit:200,...i?{cursor:i}:{}});for(const s of o.members)!s.deleted&&!s.is_bot&&s.id!=="USLACKBOT"&&a.push({id:s.id,name:s.profile?.real_name||s.real_name||s.name});i=o.response_metadata?.next_cursor||""}while(i);return a.sort((o,s)=>o.name.localeCompare(s.name))},openDM:n(async a=>(await c("conversations.open",{users:a})).channel.id,"openDM"),post:n(async({channel:a,text:i,thread_ts:o})=>(await c("chat.postMessage",{channel:a,text:i,unfurl_links:!1,...o?{thread_ts:o}:{}})).ts,"post"),async react({channel:a,ts:i,name:o}){try{await c("reactions.add",{channel:a,timestamp:i,name:o})}catch(s){if(s.message!=="Slack: already_reacted")throw s}}}}n(g,"slackClient");const h=n(r=>{const e=$("slack",r);return typeof e?.token=="string"&&e.token?e:null},"savedToken");function b(r){const e=h(r);return e?{set:!0,...e.refused_at?{refused:!0}:{},...e.team?{team:e.team,user:e.user}:{}}:{set:!1}}n(b,"slackStatus");const K="Slack needs Hub\u2019s Slack token; add it in Hub settings \u203A Slack first.";async function L(r,{fetch:e}={}){const t=typeof r=="string"?r.trim():"";if(!/^xoxp-[\w-]{10,250}$/.test(t))throw new m("Paste a Slack user token, which starts with xoxp-.",400);const c=new Date().toISOString();let a=!1;const i=await g(t,{fetch:e,checked:n(o=>{a=!o},"checked")}).who().catch(o=>{if(!a)throw o;return null});return f("slack",i?{token:t,...i,saved_at:c}:{token:t,saved_at:c,refused_at:c}),b()}n(L,"saveSlackToken");function U(){return f("slack",null),b()}n(U,"removeSlackToken");function D(r,e){const t=h();if(t?.token!==r||!!t.refused_at==!e)return;const{refused_at:c,...a}=t;f("slack",e?a:{...a,refused_at:new Date().toISOString()})}n(D,"markChecked");function Z({fetch:r}={}){const e=h();return e?g(e.token,{fetch:r,checked:n(t=>D(e.token,t),"checked")}):null}n(Z,"savedSlack");export{K as SLACK_NEEDS_TOKEN,m as SlackError,_ as readSlack,U as removeSlackToken,L as saveSlackToken,Z as savedSlack,I as setSlack,g as slackClient,N as slackDay,b as slackStatus};
package/hub/stream.mjs CHANGED
@@ -1,19 +1,16 @@
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
-
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}
1
+ var W=Object.defineProperty;var r=(p,m)=>W(p,"name",{value:m,configurable:!0});import A from"node:http";import B from"node:fs";import G from"node:path";function R({targets:p,watched:m=r(()=>[],"watched"),sidebar:z,retryMs:I=2e3,sidebarMs:M=15e3,pingMs:T=25e3,settleMs:j=300,log:g=r(()=>{},"log")}){const s=new Map,a=new Map,i=new Map,v=new Set;let l=null,y=null,S=[],u=new Set,d=null;const H=r(t=>{for(const e of s.keys())e.write(t)},"write"),$=r((t,e,n)=>{const o=s.get(t);t.write(`event: sidebar
2
+ data: ${o?JSON.stringify(o.view(e)):n}
6
3
 
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(`
4
+ `)},"sidebarTo"),J=r((t,e)=>`event: ${t}
5
+ data: ${JSON.stringify(e)}
9
6
 
10
- `);p>=0;p=f.indexOf(`
7
+ `,"event");async function h(t=[]){let e;try{e=await z({fresh:new Set(t)})}catch(o){g(`sidebar for the stream failed: ${o.message}`);return}const n=JSON.stringify(e);if(n!==l){l=n,y=e;for(const o of s.keys())$(o,e,n)}}r(h,"refreshSidebar");function q(t){t&&u.add(t),!d&&(d=setTimeout(()=>{d=null;const e=[...u];u=new Set,h(e)},j))}r(q,"sidebarSoon");function b(t){const e=J("change",{route:t});for(const[n,o]of s)(!o||o.routes.has(t))&&n.write(e);q(t)}r(b,"changed");function N(t,e){const n={port:e,req:null};a.set(t,n);const o=r(()=>{a.get(t)===n&&a.delete(t),n.req?.destroy()},"drop");n.req=A.get({host:"127.0.0.1",port:e,path:"/api/stream",headers:{accept:"text/event-stream"}},c=>{if(c.statusCode!==200){c.resume(),o();return}v.has(t)&&b(t),v.add(t),c.setEncoding("utf8");let f="";c.on("data",E=>{f+=E.replace(/\r\n/g,`
8
+ `);for(let w=f.indexOf(`
11
9
 
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
10
+ `);w>=0;w=f.indexOf(`
13
11
 
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
12
+ `)){const F=f.slice(0,w);f=f.slice(w+2),/^event: ?change$/m.test(F)&&b(t)}}),c.on("close",o),c.on("error",o)}),n.req.on("error",o)}r(N,"connect");function x(){let t;try{t=new Map(p().map(e=>[e.route,e.port]))}catch(e){g(`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)||N(e,n)}r(x,"reconcile");function k(){let t;try{t=new Set(m().map(e=>e.dir))}catch(e){g(`stream watched failed: ${e.message}`);return}for(const[e,n]of i)t.has(e)||(n.close(),i.delete(e));for(const e of t)if(!i.has(e))try{const n=B.watch(G.join(e,"data"),(o,c)=>{c==="watcher.json"&&q()});n.on("error",()=>{n.close(),i.delete(e)}),i.set(e,n)}catch{}}r(k,"watchWatchers");function _(){x(),k(),S=[setInterval(()=>{x(),k()},I),setInterval(()=>h(),M),setInterval(()=>H(`: ping
15
13
 
16
- `),o.add(e),o.size===1&&k(),l?h(`event: sidebar
17
- data: ${l}
14
+ `),T)]}r(_,"startHolding");function O(){for(const t of S)clearInterval(t);S=[],clearTimeout(d),d=null,u=new Set;for(const t of a.values())t.req?.destroy();a.clear();for(const t of i.values())t.close();i.clear(),v.clear(),l=null,y=null}r(O,"stopHolding");function C(t,e,n=null){e.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-store",connection:"keep-alive"}),e.write(`retry: 3000
18
15
 
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};
16
+ `),s.set(e,n),s.size===1&&_(),l?$(e,y,l):h(),t.on("close",()=>{s.delete(e),s.size||O()})}r(C,"handle");function D(){for(const t of s.keys())t.end();s.clear(),O()}return r(D,"close"),{handle:C,close:D,changed:r(t=>{s.size&&b(t)},"changed"),refresh:r(()=>{s.size&&h()},"refresh")}}r(R,"hubStream");export{R as hubStream};
package/hub/try.mjs CHANGED
@@ -1,8 +1,8 @@
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(`
1
+ var Jt=Object.defineProperty;var c=(a,f)=>Jt(a,"name",{value:f,configurable:!0});import O from"node:fs";import T from"node:path";import jt from"node:os";import ut from"node:http";import{execFile as Yt,spawn as Vt}from"node:child_process";import{createInterface as Ct}from"node:readline";import{promisify as Qt}from"node:util";import{listBoards as W,readManifest as K,readJSON as et,saveJSON as It,appendEvent as Xt,GITHUB_STATE as Zt,REPO_FETCH as Mt}from"./boards.mjs";import{boardRepo as X,githubFromOrigin as Pt}from"./board-repo.mjs";import{gitReachFault as At,remoteFromInput as qt,remoteGitEnv as te}from"./repos.mjs";import{readiness as ee}from"./readiness.mjs";import{tailscaleBin as ie}from"../shared/tailscale.mjs";import{buildScriptError as re}from"../board/build-script.mjs";import{appendThread as se,recordedWorktree as ne,setItem as oe}from"../board/store.mjs";import{cardPRs as ae,hasPR as ce,prKeyOf as le}from"../shared/card-prs.mjs";import{hubGate as de}from"../board/on-host.mjs";import{pipeUpgrade as ue,refuse as fe,refuseUpgrade as pe}from"./front-door.mjs";import{shareOf as he}from"./share.mjs";class x extends Error{static{c(this,"BuildError")}constructor(f,w=400){super(f),this.status=w}}const ft=Qt(Yt),M=c(async(a,...f)=>(await ft("git",["-C",a,...f],{encoding:"utf8",timeout:3e3})).stdout.trim(),"git"),me=/errSecInternalComponent|keychain[^\n]*\blocked\b|\blocked\b[^\n]*keychain/i,z={first:8500,last:8599},pt=c(a=>/^\d+$/.test(String(a))&&Number(a)>=z.first&&Number(a)<=z.last,"isTryPort"),we=30*6e4,_t=c(a=>T.join(a,".kickflip","build"),"scriptAt"),Dt=c(a=>O.existsSync(a),"exists"),Nt=c((a,f)=>T.join(a.dir,"data","try",`${f.split("/").at(-1)}.log`),"logFileOf");function Bt(a,f,w){const m=Nt(a,f);return O.mkdirSync(T.dirname(m),{recursive:!0}),O.writeFileSync(m,w.message+`
2
+ `,{mode:384}),O.chmodSync(m,384),m}c(Bt,"failureLog");const ye=c(a=>new Promise(f=>{const w=ut.get({host:"127.0.0.1",port:a,path:"/",timeout:1e3},m=>{m.destroy(),f(!0)});w.on("timeout",()=>w.destroy()),w.on("error",()=>f(!1))}),"probe"),Ft=c((a,f)=>{try{process.kill(-a.pid,f)}catch{}},"signalGroup");async function Rt(a,f,w){const m=await ne(a.dir,f),[v,p]=f.split("/"),k=a.waves.find(b=>b.slug===v)?.wave,u=m?.path||k?.items.find(b=>b.id===p)?.worktree;if(typeof u!="string"||!u||u.split(T.sep).includes(".."))return"";let g=m?.repo;const y=(a.github||k?.repo||"").toLowerCase();if(!g&&y){const b=[a.owner?.repo,a.dir,...Object.values(w?.sites||{}).map(C=>C.owner?.repo)];for(const C of new Set(b.filter(P=>typeof P=="string"&&T.isAbsolute(P))))try{if(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(await M(C,"remote","get-url","origin"))?.[1].toLowerCase()===y){g=await M(C,"rev-parse","--show-toplevel");break}}catch{}}if(!m?.path&&!g||m?.path&&!T.isAbsolute(u))return"";try{const b=[T.join(O.realpathSync(jt.homedir()),".claude","kickflip","worktrees")];if(typeof g=="string"&&T.isAbsolute(g))try{b.push(T.join(O.realpathSync(g),".claude","worktrees"))}catch{}const C=T.resolve(g||"/",u),P=O.realpathSync(C);return b.some(L=>C.startsWith(L+T.sep)&&P.startsWith(L+T.sep))&&O.statSync(P).isDirectory()?P:""}catch{return""}}c(Rt,"installWorktree");function ge({now:a=Date.now,answers:f=ye,log:w=console.log,waiting:m=c(async()=>null,"waiting"),event:v=Xt,gate:p=de}={}){const k=new Map,u=new Map,g=new Set,y=new Set,b=new Map,C=new Map,P=new Map,L=new Map;let G=!1,R=null,Y=null,it=null;const st=c(()=>new Date(a()).toISOString(),"stamp");function N(t){if(k.has(t.dir))return k.get(t.dir);const e=T.join(t.dir,"data","try.json"),r=et(e,{kind:null,main:null,cards:{}}),s={...pt(r.main_port)?{main_port:r.main_port}:{},kind:r.kind||null,main:r.main||null,cards:{...r.cards},...r.pull?{pull:{...r.pull,running:void 0}}:{}},i={state:s,file:e,written:JSON.stringify(r)};k.set(t.dir,i),s.main_port&&C.set(t.dir,s.main_port);const n=Object.entries(s.cards).filter(([,o])=>o.state==="running");for(const[o]of n)y.add(B(t,o));return s.kind==="web"?(s.cards=Object.fromEntries(n),s.main&&s.main.state!=="failed"&&(delete s.main.state,delete s.main.port,delete s.main.https)):s.main?.state==="running"&&(delete s.main.state,delete s.main.sha),_(t),i}c(N,"stateOf");function _(t){const e=k.get(t.dir),r=JSON.stringify(e.state);r!==e.written&&(It(e.file,e.state),e.written=r)}c(_,"persist");const B=c((t,e)=>`${t.dir}\0${e}`,"runKey"),wt=c((t,e)=>e==="main"?t.main:t.cards[e],"entryOf");function V(t,e,r){const{state:s}=N(t),i=wt(s,e);if(!i)return;const n=Object.hasOwn(r,"state")&&r.state!==i.state;Object.assign(i,r,e!=="main"&&n?{at:st()}:{}),_(t)}c(V,"update");function nt(t){const e=[...Object.values(t?.sites||{}),...Object.values(t?.closed||{}).map(r=>r.site)];for(const r of e){if(!r?.dir)continue;const s=et(T.join(r.dir,"data","try.json"),{}).main_port;pt(s)&&C.set(r.dir,Number(s))}}c(nt,"reserveMains");function Lt(t){const{board:e,key:r}=t,s=B(e,r),i=r==="main"?C.get(e.dir):b.get(s);if(i)return i;const n=new Set([...C.values(),...b.values()]);let o=z.first;for(;n.has(o)&&o<=z.last;)o++;if(o>z.last)throw new Error(`No try ports available (${z.first}\u2013${z.last}). Stop a served card and retry.`);return r==="main"?(C.set(e.dir,o),N(e).state.main_port=o,_(e)):b.set(s,o),o}c(Lt,"publicPort");const ot=c(async t=>{const e=ie();if(!e)throw new Error("Tailscale isn't installed on this host");return ft(e,t,{encoding:"utf8",timeout:1e4})},"tailscale");async function yt(t){try{await ot(["serve",`--https=${t}`,"off"])}catch(e){w(`try port ${t}: could not close port: ${(e.stderr||e.message).trim()}`)}}c(yt,"removePort");const gt=c(t=>he(et(T.join(t.dir,"board.json"),{})),"sharedWith");async function $t(t,e){const r=await p(t),s=t.headers["tailscale-user-login"];return r!=="other"||!s||!gt(e).includes(s)?r:t.method==="GET"||t.method==="HEAD"?"shared":"view-only"}c($t,"relayVerdict");function Ht(){for(const t of u.values()){if(!t.shared?.size)continue;const e=gt(t.board);for(const r of t.shared)e.includes(r.login)||(t.shared.delete(r),r.res.destroy())}}c(Ht,"endUnshared");async function Gt(t){t.https=Lt(t);const e=t.sockets=new Set,r=c(()=>{t.visited=a()},"visit"),s=c(n=>{e.add(n),n.on("data",r),n.on("close",()=>e.delete(n))},"track"),i=t.shared=new Set;if(t.relay=ut.createServer(async(n,o)=>{const h=await $t(n,t.board);if(h!=="owner"&&h!=="shared"){fe(n,o,h);return}if(h==="shared"){const d={login:n.headers["tailscale-user-login"],res:o};i.add(d),o.on("close",()=>i.delete(d))}const S=ut.request({host:"127.0.0.1",port:t.port,method:n.method,path:n.url,headers:n.headers},d=>{o.writeHead(d.statusCode,d.headers),d.on("data",r),d.pipe(o),d.on("close",()=>{d.complete||o.destroy()})});o.on("close",()=>{o.writableFinished||S.destroy()}),S.on("error",()=>{o.headersSent?o.destroy():o.writeHead(502).end()}),n.pipe(S)}),t.relay.on("connection",n=>{r(),s(n)}),t.relay.on("upgrade",async(n,o,h)=>{const S=await $t(n,t.board);if(S!=="owner"){pe(o,S==="shared"?"view-only":S);return}s(ue({req:n,socket:o,head:h,port:t.port,path:n.url}))}),await new Promise((n,o)=>{t.relay.once("error",o),t.relay.listen(0,"127.0.0.1",n)}),!t.stopped){t.exposed=!0;try{await ot(["serve","--bg",`--https=${t.https}`,`http://127.0.0.1:${t.relay.address().port}`])}catch(n){throw new Error(`Couldn't open try port ${t.https}: ${(n.stderr||n.message).trim()}`)}}}c(Gt,"openPort");async function Ut(t){if(await t.opening?.catch(()=>{}),t.exposed&&await yt(t.https),t.relay){for(const e of t.sockets)e.destroy();await new Promise(e=>t.relay.close(e))}t.keepPort||b.delete(B(t.board,t.key))}c(Ut,"closePort");function Z(t=K()){if(it)return it;nt(t);for(const e of W(t))N(e);return it=(async()=>{try{const{stdout:e}=await ot(["serve","status","--json"]),r=JSON.parse(e);for(const s of Object.keys(r?.TCP||{}))pt(s)&&![...u.values()].some(i=>i.https===Number(s))&&await yt(s)}catch(e){w(`try startup cleanup: ${(e.stderr||e.message).trim()}`)}})(),it}c(Z,"initialize");async function bt(t,e,r,s){const{board:i,key:n}=t;if(V(i,n,{state:"failed",port:void 0,https:void 0}),n==="main")return;const o=[];let h=!1;try{for await(const d of Ct({input:O.createReadStream(t.logFile),crlfDelay:1/0}))h||=me.test(d),o.push(d),o.length>5&&o.shift()}catch(d){o.push(`Could not read the build log: ${d.message}`)}const S=t.port||(N(i).state.kind||(i.waves.some(({wave:d})=>d.items.some(E=>E.install?.url))?"app":"web"))==="web"?"Serve":"Build";await se(i.dir,n,{text:[`${S} failed (exit ${e??1})`,s?.message,r&&`Stopped by ${r}.`,h&&"The login keychain must be unlocked on the Mac.",...o].filter(Boolean).join(`
3
+ `)})}c(bt,"failure");function rt(t){return t.ending||(Ft(t.child,"SIGTERM"),t.ending=new Promise(e=>{const r=c(()=>{clearTimeout(s),clearInterval(i),e()},"finish");let s=setTimeout(()=>{Ft(t.child,"SIGKILL"),s=setTimeout(r,1e3)},4e3);const i=setInterval(()=>{try{process.kill(-t.child.pid,0)}catch{r()}},20)})),t.ending}c(rt,"terminate");async function vt(t,e=!1){t.keepPort=e,t.stopped=!0,clearTimeout(t.deadline),clearInterval(t.poll),await rt(t),await t.done}c(vt,"halt");async function q(t,e=!1){await vt(t,e),V(t.board,t.key,{state:void 0,port:void 0,https:void 0,...t.ready?{}:{sha:void 0}}),t.ready||P.delete(B(t.board,t.key))}c(q,"stopRun");async function kt(t,e,r,s={}){if(!r)throw new x("This card has no valid worktree.");const i=_t(r),n=re(i);if(n)throw new x(n);if(!O.realpathSync(i).startsWith(O.realpathSync(r)+T.sep))throw new x("Build script must be inside the worktree.");const o=await M(r,"rev-parse","HEAD");if(G)throw new x("The hub is stopping. Try again after it restarts.",503);const{state:h}=N(t),S=wt(h,e),d={...e==="main"?{}:S,...s,sha:o,script:!0,state:"running",...e==="main"?{}:{at:st(),head:o}};delete d.port,delete d.https;const E=Nt(t,e);O.mkdirSync(T.dirname(E),{recursive:!0});const j=O.openSync(E,"w",384);O.fchmodSync(j,384);const $=Vt(i,[e,r],{cwd:r,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,KICKFLIP_BOARD:t.route,HOST:"127.0.0.1"}});e==="main"?h.main=d:h.cards[e]=d,_(t);const D=B(t,e),l={child:$,board:t,key:e,logFile:E,visited:a(),stopped:!1,port:null,ready:!1};u.set(D,l),P.set(D,o);let F,I;const Q=c(A=>{I||=new Error(A),rt(l)},"fail");$.on("error",A=>{F=A}),$.stdout.on("data",A=>O.writeSync(j,A)),$.stderr.on("data",A=>O.writeSync(j,A));const H=Ct({input:$.stdout,crlfDelay:1/0});return H.on("line",A=>{const tt=/^port (\d{1,5})$/.exec(A);if(!tt||l.port||l.stopped)return;const U=Number(tt[1]);if(U<1||U>65535){Q("Build script printed an invalid port.");return}l.port=U,clearTimeout(l.deadline);const ct=a()+6e4;let lt=!1;const Et=c(async()=>{if(!(lt||l.stopped||l.ready||$.exitCode!==null||$.signalCode!==null)){lt=!0;try{if(await f(U)){if(l.stopped||I||$.exitCode!==null||$.signalCode!==null||(l.opening=Gt(l),await l.opening,l.stopped||I||$.exitCode!==null||$.signalCode!==null))return;l.ready=!0,l.visited=a(),h.kind="web",V(t,e,{state:"ready",port:U,https:l.https}),clearInterval(l.poll)}else a()>=ct&&Q("Nothing answered on the build script\u2019s port within 60 seconds.")}finally{lt=!1}}},"check");l.poll=setInterval(()=>Et().catch(dt=>Q(dt.message)),250),Et().catch(dt=>Q(dt.message))}),l.deadline=setTimeout(()=>Q("No port line within 60 minutes."),60*6e4),$.once("exit",()=>{rt(l)}),l.done=new Promise(A=>$.once("close",(tt,U)=>{clearTimeout(l.deadline),clearInterval(l.poll),H.close(),O.closeSync(j),(async()=>{await rt(l),await Ut(l),l.finished=!0,!l.stopped&&(I||F||tt!==0||l.port&&!l.ready?await bt(l,tt??1,U,I||F||(l.port&&!l.ready?new Error("Build script exited before its port answered."):null)):l.ready?(e==="main"?(delete h.main.state,delete h.main.port,delete h.main.https):delete h.cards[e],_(t)):(h.kind="app",V(t,e,{state:"ready"})))})().catch(ct=>w(`build /${t.route} ${e}: ${ct.message}`)).finally(()=>{u.get(D)===l&&u.delete(D),A()})})),w(`build /${t.route} ${e}: started; log ${E}`),{status:"started"}}c(kt,"launch");async function St(t,e,r){const s=B(t,"main");if(g.has(s))throw new x("A build is already running for main.",409);g.add(s);try{u.has(s)&&await q(u.get(s),!0);const i=T.join(jt.homedir(),".claude","kickflip","try",`${t.route}-main`);return O.mkdirSync(T.dirname(i),{recursive:!0}),Dt(i)?await M(i,"checkout","--detach","--force",r.sha):(await M(e,"worktree","prune"),await M(e,"worktree","add","--detach",i,r.sha)),await kt(t,"main",i,r)}catch(i){throw i.status!==503&&(N(t).state.main={...r,state:"failed"},Bt(t,"main",i),_(t)),i}finally{g.delete(s)}}c(St,"launchMain");async function Tt(t,{manifest:e=K()}={}){if(await Z(e),nt(e),G)throw new x("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 x("Send only the board route and card key.");const{route:r,key:s}=t;if(s!=="main"&&(!/^[\w.-]+\/[\w.-]+$/.test(s)||s.split("/").some(d=>d==="."||d==="..")))throw new x("Card key must be <wave>/<id>.");const i=W(e).find(d=>d.route===r);if(!i)throw new x(`/${r} is not a board.`,404);if(s!=="main"&&!i.waves.some(({slug:d,wave:E})=>E.items.some(j=>`${d}/${j.id}`===s)))throw new x("There is no item with this card key.",404);const n=await m();if(n)throw new x(n,409);const o=B(i,s),h=u.get(o);if(g.has(o)||h&&!h.ready&&!h.finished)throw new x(`A build is already running for ${s==="main"?"main":"this card"}.`,409);if(s==="main"){const d=N(i).state.main;if(d?.state==="running")throw new x("A build is already running for main.",409);if(d?.state!=="failed"||!d.sha)throw new x("Main has no failed build to retry.",409);const{sha:E,branch:j,slug:$,at:D,script:l}=d;return St(i,X(r,e).repo,{sha:E,branch:j,slug:$,at:D,script:l})}g.add(o);const S=y.delete(o);try{u.has(o)&&await q(u.get(o),!0);const d=await Rt(i,s,e);return await kt(i,s,d)}catch(d){throw b.delete(o),S&&d.status!==503&&V(i,s,{state:void 0,sha:void 0}),d}finally{g.delete(o)}}c(Tt,"start");function xt(t,e,{manifest:r=K()}={}){const s=W(r).find(n=>n.route===t);if(!s)return null;const i=[...u.values()].find(n=>n.board.dir===s.dir&&n.key.split("/").at(-1).toLowerCase()===e.toLowerCase()&&n.ready&&!n.stopped&&n.child.exitCode===null&&n.child.signalCode===null);return i?{key:i.key,port:i.port}:null}c(xt,"lookup");async function at({manifest:t=K(),routes:e}={}){if(await Z(t),nt(t),G)return R;if(R&&e){if(!Y){const r={routes:new Set,manifest:t};r.done=R.catch(()=>{}).then(()=>(Y=null,at({manifest:r.manifest,routes:[...r.routes]}))),Y=r}Y.manifest=t;for(const r of e)Y.routes.add(r);return Y.done}return R||(R=(async()=>{const r=W(t),s=et(Zt,{}).prs||{};for(const i of[...u.values()])if(!r.some(n=>n.dir===i.board.dir)||i.key!=="main"&&i.ready&&a()-i.visited>=we){await q(i);const{state:n}=N(i.board);i.key==="main"?n.main=null:delete n.cards[i.key],_(i.board)}for(const i of r){if(G)return;if(e&&!e.includes(i.route))continue;const{state:n}=N(i),o=X(i.route,t),h=o.branch||"main",S=o.local?`refs/heads/${h}`:`refs/remotes/origin/${h}`;for(const{slug:d,wave:E}of i.waves)for(const j of E.items){const $=`${d}/${j.id}`,D=ae(j,i.github||E.repo).map(l=>s[le(l)]);if(!(["done","merged","dropped"].includes(String(j.status).toLowerCase())||D.length&&D.every(l=>["MERGED","CLOSED"].includes(l?.state))))try{const l=B(i,$),F=await Rt(i,$,t);if(F){const H=await M(F,"rev-parse","HEAD");let A=0;try{A=Number(await M(F,"rev-list","--count",`${S}..HEAD`))}catch{}Object.assign(n.cards[$]||={},{head:H,ahead:A,script:Dt(_t(F))}),_(i)}else if(!y.has(l))continue;const I=n.cards[$];if((y.has(l)||i.auto_build&&I.script&&I.ahead>0&&(I.sha||P.get(l))!==I.head&&I.state!=="running")&&!g.has(l))try{await Tt({route:i.route,key:$},{manifest:t})}catch(H){if([409,503].includes(H.status))continue;throw V(i,$,{sha:I.head}),await bt({board:i,key:$,logFile:Bt(i,$,H)},1),H}}catch(l){w(`try /${i.route} ${$}: ${l.message}`)}}try{if(!o.repo||await m())continue;const d=await M(o.repo,"rev-parse",S);let E=!1;try{await M(o.repo,"cat-file","-e",`${d}:.kickflip/build`),E=!0}catch{}if(!E){const I=u.get(B(i,"main"));I&&await q(I),n.main=null,_(i);continue}const j=n.main;if(j?.state==="running"||j?.sha===d&&(j.state==="failed"||j.state==="ready"&&(n.kind!=="web"||xt(i.route,"main",{manifest:t}))))continue;const $=B(i,"main");if(g.has($))continue;const D=await M(o.repo,"log","-1","--format=%cI",d);let l=i.github;if(!l)try{l=Pt(await M(o.repo,"remote","get-url","origin"))}catch{}const F={sha:d,branch:h,slug:l||"",at:D,script:E};await St(i,o.repo,F)}catch(d){w(`try /${i.route} main: ${d.message}`)}}})().finally(()=>{R=null}),R)}c(at,"tick");function Ot(t,e){if(L.has(t.dir))return L.get(t.dir);const r=(async()=>{const s=X(t.route,e),i=s.branch||"main",{state:n}=N(t);n.pull={...n.pull,running:!0},_(t);let o,h;try{o=await $e(s.repo,i)}catch(S){h=S.message}if(o===null?delete n.pull:n.pull={at:st(),...h?{error:h}:{}},_(t),o===null)return null;if(h)return w(`pull /${t.route}: ${h}`),{commits:0,error:h};if(o.commits){w(`pull /${t.route}: ${i} fast-forwarded ${o.commits} commit${o.commits===1?"":"s"} to ${o.to.slice(0,7)}`);try{await v(t,"main-pulled",{branch:i,...o})}catch(S){w(`pull /${t.route}: could not send main-pulled (${S.message})`)}}return{commits:o.commits}})().finally(()=>L.delete(t.dir));return L.set(t.dir,r),r}c(Ot,"pullMain");async function Wt({manifest:t=K(),routes:e}={}){await Z(t);const r=[];for(const s of W(t)){if(G)break;if(e&&!e.includes(s.route))continue;const i=X(s.route,t);!i.local||!i.repo||(await Ot(s,t))?.commits&&r.push(s.route)}return r}c(Wt,"pullMains");async function Kt(t,{manifest:e=K()}={}){if(await Z(e),G)throw new x("The hub is stopping. Try again after it restarts.",503);if(!t||Array.isArray(t)||typeof t!="object"||Object.keys(t).some(n=>n!=="route")||typeof t.route!="string")throw new x("Send only the board route.");const r=W(e).find(n=>n.route===t.route);if(!r)throw new x(`/${t.route} is not a board.`,404);const s=X(r.route,e);if(!s.local||!s.repo)throw new x("This board fetches its branch on every poll; only a local board pulls.",409);const i=await Ot(r,e);if(!i)throw new x("This board\u2019s folder has no origin to pull from.",409);return i.commits&&at({manifest:e,routes:[r.route]}).catch(n=>w(`try /${r.route} main: ${n.message}`)),i}c(Kt,"pull");async function zt(){G=!0;const t=Promise.all([...u.values()].map(e=>e.ready?q(e):vt(e)));await Promise.all([t,R,...L.values()])}return c(zt,"stop"),{start:Tt,tick:at,stop:zt,lookup:xt,initialize:Z,pull:Kt,pullMains:Wt,endUnshared:Ht}}c(ge,"createTryManager");const ht=1e4,mt=c(async(a,...f)=>(await ft("git",["-C",a,...f],{encoding:"utf8",timeout:ht,env:te()})).stdout,"originGit");async function $e(a,f,{run:w=mt}={}){const m=c(async(...p)=>(await w(...p)).trim(),"git"),v=c(p=>{throw new Error(`can\u2019t pull: ${p}`)},"refuse");try{await m(a,"config","--get","remote.origin.url")}catch{return null}try{await m(a,"fetch","--quiet","--no-tags","origin",`+refs/heads/${f}:refs/remotes/origin/${f}`)}catch(p){v(p.killed?`git fetch timed out after ${ht/1e3} s`:At(p.stderr,{repo:a}).error)}try{const p=await m(a,"rev-parse","--verify",`refs/heads/${f}^{commit}`),k=await m(a,"rev-parse","--verify",`refs/remotes/origin/${f}^{commit}`),u=c((b,C)=>m(a,"merge-base","--is-ancestor",b,C).then(()=>!0,P=>{if(P.code===1)return!1;throw P}),"isAncestor");if(p===k||await u(k,p))return{from:p,to:p,commits:0};await u(p,k)||v(`${f} has split from origin`);const g=Number(await m(a,"rev-list","--count",`${p}..${k}`)),y=(await m(a,"worktree","list","--porcelain")).split(`
4
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};
5
+ `).map(b=>b.split(`
6
+ `)).find(b=>b.includes(`branch refs/heads/${f}`))?.[0].slice(9);return y?(await m(y,"status","--porcelain","--untracked-files=no")&&v("local changes"),await m(y,"merge","--ff-only","--quiet",k)):await m(a,"update-ref",`refs/heads/${f}`,k,p),{from:p,to:k,commits:g}}catch(p){if(p.message.startsWith("can\u2019t pull: "))throw p;v(String(p.stderr||p.message).trim().split(`
7
+ `).at(-1))}}c($e,"pullBranch");async function Le({manifest:a=K(),log:f=console.log,routes:w}={}){const m=w?et(Mt,{}):{};for(const v of W(a)){if(w&&!w.includes(v.route))continue;const p=X(v.route,a);if(p.local||!p.repo)continue;const k=p.branch||"main",u=new Date().toISOString(),g=Date.now();try{await mt(p.repo,"fetch","--quiet","--no-tags","origin",`+refs/heads/${k}:refs/remotes/origin/${k}`),m[v.route]={at:u,ok:!0}}catch(y){f(`fetch /${v.route} after ${Date.now()-g} ms: ${y.message}`);let b=v.github;if(!b&&!v.remote)try{b=Pt(await M(p.repo,"remote","get-url","origin"))}catch{}m[v.route]={at:u,ok:!1,...At(y.killed?`git fetch timed out after ${ht/1e3} s`:y.stderr,{github:b||"",remote:v.remote,repo:p.repo})};continue}if(v.remote)try{await be(v,p.repo,k,f)}catch(y){f(`pushed branches /${v.route}: ${y.message}`)}}It(Mt,m)}c(Le,"fetchTryBranches");async function be(a,f,w,m){const v=a.waves.flatMap(({slug:u,wave:g})=>g.items.filter(y=>y.pushed?.branch&&!ce(y)&&!["done","merged","dropped"].includes(String(y.status).toLowerCase())).map(y=>({key:`${u}/${y.id}`,branch:y.pushed.branch})));if(!v.length)return;const p=new Map((await mt(f,"ls-remote","--heads","origin")).split(`
8
+ `).map(u=>/^([\da-f]+)\trefs\/heads\/(.+)$/.exec(u)).filter(Boolean).map(u=>[u[2],u[1]])),k=qt(a.remote)?.host||"the remote";for(const u of v){let g=p.get(u.branch);if(!g)try{g=await M(f,"rev-parse","--verify","--quiet",`refs/heads/${u.branch}^{commit}`)}catch{}let y=!1;if(g)try{await M(f,"merge-base","--is-ancestor",g,`refs/remotes/origin/${w}`),y=!0}catch{}if(!(!y&&p.has(u.branch)))try{await oe(a.dir,u.key,{status:y?"merged":"done",force:!0,text:y?`${u.branch} is merged into ${w} on ${k}, so this card is Done.`:`${u.branch} is gone from ${k}, so this card is Done.`})}catch(b){m(`pushed ${u.key}: ${b.message}`)}}}c(be,"settlePushed");const J=ge({waiting:c(()=>ee.waiting("tailscale"),"waiting")}),He=c((...a)=>J.start(...a),"startBuild"),Ge=c((...a)=>J.tick(...a),"tryTick"),Ue=c((...a)=>J.pull(...a),"pullNow"),We=c((...a)=>J.pullMains(...a),"pullMains"),Ke=c(()=>J.stop(),"stopTries"),ze=c(()=>J.endUnshared(),"endUnsharedTries"),Je=c((...a)=>J.initialize(...a),"initializeTries");export{x as BuildError,z as TRY_PORTS,ge as createTryManager,ze as endUnsharedTries,Le as fetchTryBranches,Je as initializeTries,Rt as installWorktree,pt as isTryPort,$e as pullBranch,We as pullMains,Ue as pullNow,He as startBuild,Ke as stopTries,Ge as tryTick};
package/hub/upgrade.mjs CHANGED
@@ -1 +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};
1
+ var x=Object.defineProperty;var e=(n,s)=>x(n,"name",{value:s,configurable:!0});import m from"node:fs";import h from"node:path";const b="https://registry.npmjs.org/@lovek4d%2Fkickflip/latest",A=60*6e4,v=e(n=>String(n).split("-")[0].split(".").map(Number),"parts");function p(n,s){const[a,l]=[v(n),v(s)];for(let r=0;r<3;r++)if((a[r]||0)!==(l[r]||0))return(a[r]||0)>(l[r]||0);return!1}e(p,"newer");function C({root:n,running:s,fetch:a=globalThis.fetch,run:l,log:r=e(()=>{},"log"),changed:c=e(()=>{},"changed"),pulled:w=e(()=>{},"pulled")}){const g=m.existsSync(h.join(n,".git"));let i=null,u=!1,o=null;const d=e(()=>JSON.parse(m.readFileSync(h.join(n,"package.json"),"utf8")).version,"installed");async function y(){if(!g){try{const t=await a(b,{signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new Error(`npm answered ${t.status}`);i=(await t.json()).version}catch(t){r(`kickflip update check failed: ${t.message}`)}i&&p(i,d())&&k(),c()}}e(y,"check");function f(){if(g)return null;const t=d();return p(t,s)?{state:"updated",version:t}:!i||!p(i,t)?null:u?{state:"updating",version:i}:o?{state:"failed",version:i,error:o}:{state:"available",version:i}}e(f,"state");function k(){u||(u=!0,o=null,l().then(({ok:t,error:j})=>{t?w():o=j},t=>{o=t.message}).finally(()=>{u=!1,c()}))}e(k,"pull");async function S(){if(!f()||f().state==="updated")throw Object.assign(new Error("kickflip is up to date."),{status:409});return k(),c(),f()}return e(S,"request"),{check:y,state:f,request:S}}e(C,"upgrader");export{A as CHECK_MS,b as LATEST_URL,p as newer,C as upgrader};
package/hub/usage.mjs CHANGED
@@ -1,3 +1,3 @@
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};
1
+ var N=Object.defineProperty;var a=(e,t)=>N(e,"name",{value:t,configurable:!0});import f from"node:fs";import _ from"node:os";import d from"node:path";import{audit as w,hubAudit as S}from"../shared/audit.mjs";const g=6,k=180,O={five_hour:5*36e5,seven_day:7*864e5},h=a(e=>{try{return JSON.parse(f.readFileSync(e,"utf8"))}catch{return null}},"readJson"),y=a(e=>e==null||e===""||!Number.isFinite(Number(e))?null:Number(e),"num"),j=a(e=>{if(e==null||e==="")return null;const n=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(n).getTime())?new Date(n).toISOString():null},"isoOf"),x=a((e,t)=>({used_percentage:y(e),resets_at:j(t)}),"win");function D(e){let t;try{t=f.openSync(e,"r");const n=f.fstatSync(t).size;for(const s of[256*1024,2*1024*1024]){const r=Math.max(0,n-s),c=Buffer.alloc(n-r);f.readSync(t,c,0,c.length,r);const i=c.toString("utf8").split(`
2
+ `);r>0&&i.shift();for(let u=i.length-1;u>=0;u--)if(i[u].includes("rate_limits"))try{const p=JSON.parse(i[u]),o=p?.payload?.rate_limits??p?.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}a(D,"lastRateLimits");function $(e){const t=[],n=a(s=>{try{return f.readdirSync(s).sort().reverse()}catch{return[]}},"kids");e:for(const s of n(e))for(const r of n(d.join(e,s)))for(const c of n(d.join(e,s,r))){const i=d.join(e,s,r,c);for(const u of n(i))if(/^rollout-.*\.jsonl$/.test(u))try{t.push({file:d.join(i,u),mtime:f.statSync(d.join(i,u)).mtimeMs})}catch{}if(t.length>=g*2)break e}return t.sort((s,r)=>r.mtime-s.mtime).slice(0,g)}a($,"newestRollouts");function v(e){const t=[];for(const{file:o,mtime:l}of $(e)){const m=D(o);m&&t.push({...m,mtime:l,resets:y(m.rl.primary.resets_at)})}if(!t.length)return null;const n=Math.max(...t.map(o=>o.resets??-1/0)),s=t.filter(o=>o.resets!=null&&Math.abs(o.resets-n)<=k),r=a(o=>s.reduce((l,m)=>(y(m.rl[o]?.used_percent)??-1)>(y(l?.rl[o]?.used_percent)??-1)?m:l,null),"pick");if(!s.length)return null;const c=r("primary"),i=r("secondary"),u=s.reduce((o,l)=>l.mtime>o.mtime?l:o),p=a((o,l)=>o?x(o.rl[l].used_percent,o.rl[l].resets_at):null,"w");return{five_hour:p(c,"primary"),seven_day:p(i,"secondary"),at:new Date(u.mtime).toISOString()}}a(v,"scanCodex");function b(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=j(e.at),s=a(r=>{const c=e[r];if(!c)return null;const i=x(c.used_percentage,c.resets_at);if(i.used_percentage==null)return null;const u=!n||t-Date.parse(n)>O[r]?"stale":i.resets_at&&t>=Date.parse(i.resets_at)?"reset":"live";return{...i,used_percentage:u==="reset"?0:i.used_percentage,state:u}},"window");return{at:n,five_hour:s("five_hour"),seven_day:s("seven_day")}}a(b,"readingOf");function J({home:e=_.homedir(),now:t=Date.now,cacheMs:n=6e4}={}){const s=d.join(e,".codex","sessions");let r=null,c=-1/0;return({codexShare:i="off"}={})=>{const u=t(),p=b(h(d.join(e,".claude","kickflip","usage.json"))?.claude,u);return i==="off"?{claude:p,codex:null}:(u-c>=n&&(r=v(s),c=u),{claude:p,codex:b(r||{at:null},u)})}}a(J,"usageReader");const F=95,L=a((e,t)=>e==="deaf"&&t?.percent>=F,"contextFull");function R(e,{home:t=_.homedir()}={}){if(typeof e!="string"||!/^[\w-]+$/.test(e))return null;const n=h(d.join(t,".claude","kickflip","context",`${e}.json`));return y(n?.percent)==null||!n.at?null:{percent:y(n.percent),at:n.at}}a(R,"contextReading");async function W({gate:e,home:t=_.homedir(),resume:n}){const s=d.join(t,".claude","kickflip","usage-gate-state.json"),r=h(s);e.state==="paused"&&r?.state!=="paused"&&w(S(t),{call:"usage-pause",result:"paused",reason:`Claude's ${e.window==="five_hour"?"5-hour":"weekly"} usage reached the ${e.pause_at}% line.`,inputs:{gate:e,previous:r?.state??null}}),r?.state==="paused"&&e.state==="normal"&&(w(S(t),{call:"usage-resume",result:"resumed",reason:`Claude's ${r.window==="five_hour"?"5-hour":"weekly"} usage is under the line again, so every board was told.`,inputs:{gate:e,previous:r.window}}),await n(r.window)),f.mkdirSync(d.dirname(s),{recursive:!0});const c=`${s}.${process.pid}.tmp`;f.writeFileSync(c,JSON.stringify(e)+`
3
+ `),f.renameSync(c,s)}a(W,"checkUsagePause");export{F as CONTEXT_FULL,W as checkUsagePause,L as contextFull,R as contextReading,J as usageReader};
package/hub/views.mjs CHANGED
@@ -1 +1 @@
1
- var _=Object.defineProperty;var s=(e,t)=>_(e,"name",{value:t,configurable:!0});import{clock as c,holdLine as w,sendWords as H,snoozeEnd as f}from"./schedule.mjs";import{CHOICES as T,FOREVER as k,durationEnd as V,endOf as F}from"./duration.mjs";import{siteIcon as K}from"./icons.mjs";import{codexStatus as M}from"../shared/codex.mjs";const W=s(e=>e.charAt(0).toUpperCase()+e.slice(1),"capital"),b=s((e,t)=>`${e} ${t}${e===1?"":"s"}`,"plural"),h=s(e=>{const[t,n]=e.split(":").map(Number),o=new Date;return o.setHours(t,n,0,0),c(o,o)},"timeOfDay"),B=s(e=>`checks every ${e.every===1?"minute":`${e.every} min`} while you\u2019re ${e.present?"here":"away"}${e.low?", slower while GitHub\u2019s points are low":""}`,"cadenceLine"),G=s((e,t,n)=>`${B(t)}${e.hold?`; ${w(e.hold,n)}`:""}`,"nowLine"),S=s((e,t)=>e.hold?w(e.hold,t):"pushes go out after each check","deviceLine"),Z=s(e=>`${h(e.quiet.start)} \u2013 ${h(e.quiet.end)}${e.quiet.hold?" \xB7 pushes held":""}`,"quietSummary"),Q="checks every minute while you're here, every 5 when away",X=s((e,t)=>e.count?`${e.count} push${e.count===1?"":"es"} queued; next send ${H(e.nextFlushAt,t)}.`:"No pushes queued.","queuedLine");function Y({running:e=!1,nextAt:t,last:n=null},o){if(e)return"Checking GitHub now";const l=`Next check ${c(t,o)}`;if(!n)return l;const u=n.failed.length?"could not reach GitHub for every PR":n.watched?`${b(n.watched,"PR")}, ${n.changes.length?`${n.changes.length} changed`:"no change"}`:"no PRs watched";return`${l} \xB7 last ${c(new Date(n.at),o)}, ${u}`}s(Y,"pollLine");function j(e,t,n){return{title:W(G(e,t,n)),lines:[Y(t,n),X(e,n)],count:e.count}}s(j,"pollingNow");function J(e,t){const n={port:"down \xB7 not answering",files:"down \xB7 folder missing"}[e.serves]||"down \xB7 restarting";if(e.state!=="up")return{tone:e.state==="down"?"down":"wait",word:e.state==="down"?n:e.state,lines:[]};if(!t)return{tone:"ok",word:"up",lines:[]};const o=t.filter(r=>!r.ok),l=o.filter(r=>r.state==="broken"),u=t.find(r=>r.link==="events"),a=u?.listen==="asleep"||u?.listen==="waking"?u.listen:u?.ok?"listening":"not listening",d=l.length?`degraded \xB7 ${a}`:o.length?`up \xB7 ${a} \xB7 ${o.length} settling`:`up \xB7 ${a} \xB7 every link passes`;return{tone:o.length?"wait":"ok",word:d,lines:o.map(r=>({link:r.link,detail:`${r.state==="broken"?"":"settling: "}${r.detail}`}))}}s(J,"siteHealth");const A=[{value:"always",label:"Always on",description:s(()=>"Codex implements and reviews. Work pauses when it runs out.","description")},{value:"auto",label:"Auto",description:s(e=>`Codex implements and reviews, and ${e} takes over while it's out.`,"description")},{value:"off",label:"Off",description:s(e=>`${e} implements and reviews.`,"description")}],ee=s((e,t,n)=>({usable:t.usable,tag:t.usable?null:t.reason,share:e,choices:A.map(({value:o,label:l})=>({value:o,label:l,on:o===e})),description:t.usable?A.find(o=>o.value===e).description(q[n]):t.words,fix:t.fix}),"codexView"),q={opus:"Opus",sonnet:"Sonnet",auto:"Claude"},N=[{value:"opus",label:"Opus",description:"Always Opus. Auto would give small cards to Sonnet."},{value:"auto",label:"Auto",description:"Auto: small cards get Sonnet, the rest get Opus."},{value:"sonnet",label:"Sonnet",description:"Always Sonnet. Auto would give large cards to Opus."}],te=s(e=>({model:e,builder:q[e],choices:N.map(({value:t,label:n})=>({value:t,label:n,on:t===e})),description:N.find(t=>t.value===e).description}),"claudeView");function de({now:e,st:t,poll:n,sidebar:o,rows:l,links:u=new Map,code:a={},host:d="",rules:r=[],remembered:y=new Map,integrations:p=[],codexShare:R="off",claudeModel:x="auto",codex:U=M({installed:!1}),awake:O=null}){const $=new Set(o.sites.filter(i=>i.board).map(i=>i.route)),E=!!(a.running&&a.running===a.onDisk),z=E?` \xB7 runs the code in its files (${a.onDisk})`:"",D=s(i=>({route:i.route,title:i.title,icon:K(i.route,i),href:`/${encodeURIComponent(i.route)}/`,...J(i,u.get(i.route)),remembered:y.get(i.route)||[],restart:$.has(i.route)&&i.restart===!0}),"site"),I=[["Boards",l.filter(i=>$.has(i.route))],["Pages",l.filter(i=>!$.has(i.route))]].filter(([,i])=>i.length).map(([i,L])=>({label:i,sites:L.map(D)}));return{hub:{tone:o.hub.tone,word:o.hub.word,detail:`${o.hub.detail}${z}`,restart:!E},awake:O&&g(O,e,v),groups:I,integrations:p,usage:o.usage,pause:o.pause,codex:ee(R,U,x),claude:te(x),empty:l.length===0,polling:j(t,n,e),notifications:{on:t.settings.notifications.on,text:o.notifications.text,device:S(t,e)},hold:t.hold&&t.hold.why!=="off"?{text:`Notifications ${w(t.hold,e)}`,end:t.hold.why==="snoozed"}:null,rules:r.length?b(r.length,"rule"):"None yet",sites:b(l.length,"site"),host:d,total:o.total}}s(de,"hubView");const ce="That snooze ends in the past or more than 30 days on. Pick another time.",he="That keep awake ends in the past or more than 30 days on. Pick another time.",C="until you end it",v="until you turn it off",g=s((e,t,n)=>e===k?n:`until ${c(e,t)}`,"untilWords"),P=s((e,t)=>T.map(([n,o])=>({value:n,label:o,until:g(V(e,n),e,t)})),"durationChoices"),ne=s((e,t)=>e.on?F(e.snoozed_until,t):null,"snoozedUntil");function pe({now:e,st:t,rules:n=[],route:o={atMac:!1,desktops:0},linear:l={set:!1},awake:u={until:null,unsupported:null}}){const a=t.settings,d=a.notifications,r=ne(d,e),y=t.count?` The ${t.count} queued push${t.count===1?" is":"es are"} dropped now.`:"",p=r&&`Snoozed ${g(r,e,C)}`;return{snoozed:r?{title:p,summary:r===k?"Snoozed \xB7 forever":p}:null,device:S(t,e),on:{on:d.on,sub:d.on?"On. Turn off to drop every push, urgent ones too.":"Off. Every push is dropped, urgent ones too. Needs you and the badge still update.",confirm:`Turn off notifications? Every push is dropped until you turn them back on, urgent ones too.${y} Needs you and the badge still update.`},presence:d.on?o.atMac?o.desktops?{title:"At the host",sub:"Pushes go to the host only. Prompts, faults and urgent pushes still reach the phone."}:{title:"At the host",sub:"No notifications on the host, so pushes still go to the phone."}:{title:"Away from the host",sub:"Pushes go to every device. At the host means unlocked and used in the last 3 minutes."}:null,snooze:d.on&&!r?{choices:P(e,C)}:null,awake:{unsupported:u.unsupported,on:u.until?{title:`Keeping awake ${g(u.until,e,v)}`}:null,choices:u.unsupported||u.until?null:P(e,v),summary:u.unsupported||(u.until?u.until===k?"On \xB7 forever":`On until ${c(u.until,e)}`:"Off")},weekends:{on:d.weekends_off,sub:`Pushes wait from Friday ${h(a.quiet.start)} until Monday ${h(a.quiet.end)}. Urgent ones still go.`},quiet:se(a,e),rules:n,linear:oe(l)}}s(pe,"settingsView");const m={url:"https://linear.app/settings/account/security",label:"Linear \u203A Settings \u203A Security & access \u203A Personal API keys"};function oe(e){const t=e.workspace?`${e.workspace} workspace`:"";return e.set?e.refused?{set:!0,refused:!0,title:t||"Linear key",down:"doesn\u2019t work",sub:`Linear refused the key. Make a new one in ${m.label} and paste it here.`,keys:m,summary:t?`Key doesn\u2019t work \xB7 ${t}`:"Key doesn\u2019t work"}:{set:!0,title:t,sub:"Key \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",summary:`Key set \xB7 ${t}`}:{set:!1,title:"No key",sub:`Make a personal API key in ${m.label}, then paste it here.`,keys:m,summary:"No key"}}s(oe,"linearWords");function se(e,t){const n=e.quiet,[o,l]=[h(n.start),h(n.end)],u=f(t,"tonight",e),a=[["Snooze tonight",`Until ${c(u,t)}${n.hold?`, then quiet hours hold pushes until ${c(f(u,"morning",e),t)}`:""}.`],["Snooze morning",`Until ${c(f(t,"morning",e),t)}.`],["Snooze monday",`Until ${c(f(t,"monday",e),t)}.`],["Off on weekends",e.notifications.weekends_off?`Pushes wait from Friday ${o} until Monday ${l}.`:"Off."],["Daily wake",`Every board wakes once at ${l}, when quiet hours end.`]];return{start:n.start,end:n.end,summary:Z(e),hint:Q,hold:{on:n.hold,sub:n.hold?`Pushes queued after ${o} wait until ${l}. Urgent ones still go.`:"Off. Pushes go out all night."},reads:a.map(([d,r])=>({title:d,sub:r}))}}s(se,"quietView");function fe(e){return e?e.ok?{sent:e.sent,count:e.count,ok:!0,message:`Sent ${e.count} queued push${e.count===1?"":"es"}.`}:{sent:e.sent,count:e.count,ok:!1,message:"Could not send the queue. It stays queued for the next check."}:{sent:0,count:0,ok:!0,message:"Nothing was queued."}}s(fe,"flushView");export{he as AWAKE_REFUSED,Q as QUIET_HINT,ce as SNOOZE_REFUSED,B as cadenceLine,W as capital,P as durationChoices,fe as flushView,de as hubView,G as nowLine,b as plural,Y as pollLine,Z as quietSummary,pe as settingsView,J as siteHealth};
1
+ var K=Object.defineProperty;var s=(e,t)=>K(e,"name",{value:t,configurable:!0});import{clock as d,holdLine as y,sendWords as F,snoozeEnd as m}from"./schedule.mjs";import{CHOICES as H,FOREVER as w,durationEnd as V,endOf as W}from"./duration.mjs";import{siteIcon as M}from"./icons.mjs";import{codexStatus as B}from"../shared/codex.mjs";const G=s(e=>e.charAt(0).toUpperCase()+e.slice(1),"capital"),b=s((e,t)=>`${e} ${t}${e===1?"":"s"}`,"plural"),p=s(e=>{const[t,n]=e.split(":").map(Number),o=new Date;return o.setHours(t,n,0,0),d(o,o)},"timeOfDay"),Z=s(e=>`checks every ${e.every===1?"minute":`${e.every} min`} while you\u2019re ${e.present?"here":"away"}${e.low?", slower while GitHub\u2019s points are low":""}`,"cadenceLine"),j=s((e,t,n)=>`${Z(t)}${e.hold?`; ${y(e.hold,n)}`:""}`,"nowLine"),A=s((e,t)=>e.hold?y(e.hold,t):"pushes go out after each check","deviceLine"),J=s(e=>`${p(e.quiet.start)} \u2013 ${p(e.quiet.end)}${e.quiet.hold?" \xB7 pushes held":""}`,"quietSummary"),Q="checks every minute while you're here, every 5 when away",X=s((e,t)=>e.count?`${e.count} push${e.count===1?"":"es"} queued; next send ${F(e.nextFlushAt,t)}.`:"No pushes queued.","queuedLine");function Y({running:e=!1,nextAt:t,last:n=null},o){if(e)return"Checking GitHub now";const a=`Next check ${d(t,o)}`;if(!n)return a;const u=n.failed.length?"could not reach GitHub for every PR":n.watched?`${b(n.watched,"PR")}, ${n.changes.length?`${n.changes.length} changed`:"no change"}`:"no PRs watched";return`${a} \xB7 last ${d(new Date(n.at),o)}, ${u}`}s(Y,"pollLine");function ee(e,t,n){return{title:G(j(e,t,n)),lines:[Y(t,n),X(e,n)],count:e.count}}s(ee,"pollingNow");function te(e,t){const n={port:"down \xB7 not answering",files:"down \xB7 folder missing"}[e.serves]||"down \xB7 restarting";if(e.state!=="up")return{tone:e.state==="down"?"down":"wait",word:e.state==="down"?n:e.state,lines:[]};if(!t)return{tone:"ok",word:"up",lines:[]};const o=t.filter(r=>!r.ok),a=o.filter(r=>r.state==="broken"),u=t.find(r=>r.link==="events"),l=u?.listen==="asleep"||u?.listen==="waking"?u.listen:u?.ok?"listening":"not listening",c=a.length?`degraded \xB7 ${l}`:o.length?`up \xB7 ${l} \xB7 ${o.length} settling`:`up \xB7 ${l} \xB7 every link passes`;return{tone:o.length?"wait":"ok",word:c,lines:o.map(r=>({link:r.link,detail:`${r.state==="broken"?"":"settling: "}${r.detail}`}))}}s(te,"siteHealth");const q=[{value:"always",label:"Always on",description:s(()=>"Codex implements and reviews. Work pauses when it runs out.","description")},{value:"auto",label:"Auto",description:s(e=>`Codex implements and reviews, and ${e} takes over while it's out.`,"description")},{value:"off",label:"Off",description:s(e=>`${e} implements and reviews.`,"description")}],ne=s((e,t,n)=>({usable:t.usable,tag:t.usable?null:t.reason,share:e,choices:q.map(({value:o,label:a})=>({value:o,label:a,on:o===e})),description:t.usable?q.find(o=>o.value===e).description(N[n]):t.words,fix:t.fix}),"codexView"),N={opus:"Opus",sonnet:"Sonnet",auto:"Claude"},C=[{value:"opus",label:"Opus",description:"Always Opus. Auto would give small cards to Sonnet."},{value:"auto",label:"Auto",description:"Auto: small cards get Sonnet, the rest get Opus."},{value:"sonnet",label:"Sonnet",description:"Always Sonnet. Auto would give large cards to Opus."}],oe=s(e=>({model:e,builder:N[e],choices:C.map(({value:t,label:n})=>({value:t,label:n,on:t===e})),description:C.find(t=>t.value===e).description}),"claudeView");function fe({now:e,st:t,poll:n,sidebar:o,rows:a,links:u=new Map,code:l={},host:c="",version:r,rules:h=[],remembered:f=new Map,integrations:U=[],codexShare:I="off",claudeModel:O="auto",codex:L=B({installed:!1}),awake:v=null}){const $=new Set(o.sites.filter(i=>i.board).map(i=>i.route)),E=!!(l.running&&l.running===l.onDisk),P=E?` \xB7 runs the code in its files (${l.onDisk})`:"",T=s(i=>({route:i.route,title:i.title,icon:M(i.route,i),href:`/${encodeURIComponent(i.route)}/`,...te(i,u.get(i.route)),remembered:f.get(i.route)||[],restart:$.has(i.route)&&i.restart===!0}),"site"),z=[["Boards",a.filter(i=>$.has(i.route))],["Pages",a.filter(i=>!$.has(i.route))]].filter(([,i])=>i.length).map(([i,D])=>({label:i,sites:D.map(T)}));return{hub:{tone:o.hub.tone,word:o.hub.word,detail:`${o.hub.detail}${P}`,restart:!E},awake:v&&g(v,e,S),groups:z,integrations:U,usage:o.usage,pause:o.pause,codex:ne(I,L,O),claude:oe(O),empty:a.length===0,polling:ee(t,n,e),notifications:{on:t.settings.notifications.on,text:o.notifications.text,device:A(t,e)},hold:t.hold&&t.hold.why!=="off"?{text:`Notifications ${y(t.hold,e)}`,end:t.hold.why==="snoozed"}:null,rules:h.length?b(h.length,"rule"):"None yet",sites:b(a.length,"site"),host:c,version:r,total:o.total}}s(fe,"hubView");const me="That snooze ends in the past or more than 30 days on. Pick another time.",ge="That keep awake ends in the past or more than 30 days on. Pick another time.",_="until you end it",S="until you turn it off",g=s((e,t,n)=>e===w?n:`until ${d(e,t)}`,"untilWords"),R=s((e,t)=>H.map(([n,o])=>({value:n,label:o,until:g(V(e,n),e,t)})),"durationChoices"),se=s((e,t)=>e.on?W(e.snoozed_until,t):null,"snoozedUntil");function ke({now:e,st:t,rules:n=[],linear:o={set:!1},slack:a={set:!1},awake:u={until:null,unsupported:null}}){const l=t.settings,c=l.notifications,r=se(c,e),h=t.count?` The ${t.count} queued push${t.count===1?" is":"es are"} dropped now.`:"",f=r&&`Snoozed ${g(r,e,_)}`;return{snoozed:r?{title:f,summary:r===w?"Snoozed \xB7 forever":f}:null,device:A(t,e),on:{on:c.on,sub:c.on?"On. Turn off to drop every push, urgent ones too.":"Off. Every push is dropped, urgent ones too. Needs you and the badge still update.",confirm:`Turn off notifications? Every push is dropped until you turn them back on, urgent ones too.${h} Needs you and the badge still update.`},snooze:c.on&&!r?{choices:R(e,_)}:null,awake:{unsupported:u.unsupported,on:u.until?{title:`Keeping awake ${g(u.until,e,S)}`}:null,choices:u.unsupported||u.until?null:R(e,S),summary:u.unsupported||(u.until?u.until===w?"On \xB7 forever":`On until ${d(u.until,e)}`:"Off")},weekends:{on:c.weekends_off,sub:`Pushes wait from Friday ${p(l.quiet.start)} until Monday ${p(l.quiet.end)}. Urgent ones still go.`},quiet:ae(l,e),rules:n,linear:re(o),slack:ue(a)}}s(ke,"settingsView");const ie={display_information:{name:"Kickflip"},oauth_config:{scopes:{user:["chat:write","im:write","reactions:write","users:read"]}}},x={url:`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(ie))}`,label:"a new Slack app"};function ue(e){const t=e.team?`${e.team} workspace`:"",n=`Make ${x.label}, install it to your workspace, then paste its User OAuth Token (xoxp-\u2026) here.`;return e.set?e.refused?{set:!0,refused:!0,title:t||"Slack token",down:"doesn\u2019t work",sub:`Slack refused the token. ${n}`,keys:x,summary:t?`Token doesn\u2019t work \xB7 ${t}`:"Token doesn\u2019t work"}:{set:!0,title:t,sub:`Token \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 \xB7 sends as ${e.user}`,summary:`Token set \xB7 ${t}`}:{set:!1,title:"No token",sub:n,keys:x,summary:"No token"}}s(ue,"slackWords");const k={url:"https://linear.app/settings/account/security",label:"Linear \u203A Settings \u203A Security & access \u203A Personal API keys"};function re(e){const t=e.workspace?`${e.workspace} workspace`:"";return e.set?e.refused?{set:!0,refused:!0,title:t||"Linear key",down:"doesn\u2019t work",sub:`Linear refused the key. Make a new one in ${k.label} and paste it here.`,keys:k,summary:t?`Key doesn\u2019t work \xB7 ${t}`:"Key doesn\u2019t work"}:{set:!0,title:t,sub:"Key \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",summary:`Key set \xB7 ${t}`}:{set:!1,title:"No key",sub:`Make a personal API key in ${k.label}, then paste it here.`,keys:k,summary:"No key"}}s(re,"linearWords");function ae(e,t){const n=e.quiet,[o,a]=[p(n.start),p(n.end)],u=m(t,"tonight",e),l=[["Snooze tonight",`Until ${d(u,t)}${n.hold?`, then quiet hours hold pushes until ${d(m(u,"morning",e),t)}`:""}.`],["Snooze morning",`Until ${d(m(t,"morning",e),t)}.`],["Snooze monday",`Until ${d(m(t,"monday",e),t)}.`],["Off on weekends",e.notifications.weekends_off?`Pushes wait from Friday ${o} until Monday ${a}.`:"Off."],["Daily wake",`Every board wakes once at ${a}, when quiet hours end.`]];return{start:n.start,end:n.end,summary:J(e),hint:Q,hold:{on:n.hold,sub:n.hold?`Pushes queued after ${o} wait until ${a}. Urgent ones still go.`:"Off. Pushes go out all night."},reads:l.map(([c,r])=>({title:c,sub:r}))}}s(ae,"quietView");function $e(e){return e?e.ok?{sent:e.sent,count:e.count,ok:!0,message:`Sent ${e.count} queued push${e.count===1?"":"es"}.`}:{sent:e.sent,count:e.count,ok:!1,message:"Could not send the queue. It stays queued for the next check."}:{sent:0,count:0,ok:!0,message:"Nothing was queued."}}s($e,"flushView");export{ge as AWAKE_REFUSED,Q as QUIET_HINT,me as SNOOZE_REFUSED,Z as cadenceLine,G as capital,R as durationChoices,$e as flushView,fe as hubView,j as nowLine,b as plural,Y as pollLine,J as quietSummary,ke as settingsView,te as siteHealth};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovek4d/kickflip",
3
- "version": "0.4.0",
3
+ "version": "0.5.3",
4
4
  "description": "Follow and steer Claude Code sessions from your phone.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -26,6 +26,7 @@
26
26
  "CONTEXT.md",
27
27
  "!**/*.test.mjs",
28
28
  "!board/mini-dom.mjs",
29
+ "!board/board-fixture.mjs",
29
30
  "!hub/fake-device.mjs",
30
31
  "!shared/test-helpers.mjs"
31
32
  ]
@@ -0,0 +1,4 @@
1
+ var $=Object.defineProperty;var i=(t,n)=>$(t,"name",{value:n,configurable:!0});import o from"node:fs";import x from"node:os";import f from"node:path";const l=30,m=864e5,E=i(t=>f.join(t,"data","audit.jsonl"),"boardAudit"),J=i((t=x.homedir())=>f.join(t,".claude","kickflip","audit.jsonl"),"hubAudit");function A(t){let n;try{n=o.openSync(t,"r")}catch(r){if(r.code==="ENOENT")return null;throw r}try{const r=Buffer.alloc(64),a=o.readSync(n,r,0,r.length,0);return Date.parse(r.toString("utf8",0,a).match(/^\{"at":"([^"]+)"/)?.[1])}finally{o.closeSync(n)}}i(A,"oldestAt");function k(t,{call:n,key:r,result:a,reason:c,inputs:e},{now:s=new Date,once:S=!1}={}){if(S){const u=y(t,{key:r,now:s}).findLast(N=>N.call===n);if(u?.result===a&&u.reason===c)return}const p=JSON.stringify({at:s.toISOString(),call:n,...r?{key:r}:{},result:a,reason:c,inputs:e})+`
2
+ `;o.mkdirSync(f.dirname(t),{recursive:!0});const h=s.getTime()-l*m;if(!(A(t)<h))return o.appendFileSync(t,p);const g=y(t,{now:s}).map(u=>JSON.stringify(u)+`
3
+ `).join(""),d=`${t}.${process.pid}.tmp`;o.writeFileSync(d,g+p),o.renameSync(d,t)}i(k,"audit");function y(t,{key:n,now:r=new Date}={}){let a;try{a=o.readFileSync(t,"utf8")}catch(e){if(e.code==="ENOENT")return[];throw e}const c=r.getTime()-l*m;return a.split(`
4
+ `).flatMap(e=>{try{return[JSON.parse(e)]}catch{return[]}}).filter(e=>Date.parse(e.at)>=c&&(!n||e.key===n))}i(y,"readAudit");function F(t){return t.length?t.flatMap(n=>[`${n.at} ${[n.call,n.key].filter(Boolean).join(" ")}: ${n.result}. ${n.reason}`,` inputs: ${JSON.stringify(n.inputs??{})}`]):[`No calls in the last ${l} days.`]}i(F,"auditLines");export{l as AUDIT_DAYS,k as audit,F as auditLines,E as boardAudit,J as hubAudit,y as readAudit};