@lovek4d/kickflip 0.5.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 (76) hide show
  1. package/CONTEXT.md +47 -42
  2. package/README.md +1 -1
  3. package/SKILL.md +16 -16
  4. package/bin/kickflip.mjs +26 -17
  5. package/bin/wait-events.mjs +2 -2
  6. package/board/agents.mjs +2 -0
  7. package/board/bin/board.mjs +65 -18
  8. package/board/domain.mjs +7 -7
  9. package/board/finish.mjs +4 -4
  10. package/board/headless.mjs +5 -4
  11. package/board/on-host.mjs +1 -1
  12. package/board/public/app-asks.js +6 -6
  13. package/board/public/app-banner.js +7 -13
  14. package/board/public/app-cards.js +51 -27
  15. package/board/public/app-core.js +26 -8
  16. package/board/public/app-header.js +2 -1
  17. package/board/public/app-lanes.js +55 -23
  18. package/board/public/app-needs.js +129 -4
  19. package/board/public/app-reader.js +1 -1
  20. package/board/public/app-snapshot.js +6 -5
  21. package/board/public/app-threads.js +70 -59
  22. package/board/public/app.js +38 -8
  23. package/board/public/attach.js +2 -2
  24. package/board/public/dialogs.js +9 -39
  25. package/board/public/hub-kit.js +4 -2
  26. package/board/public/linear-key.js +46 -35
  27. package/board/public/new-task.js +17 -38
  28. package/board/public/prototype-kit.js +28 -3
  29. package/board/public/prototype-switcher.js +42 -107
  30. package/board/public/shell.js +7 -5
  31. package/board/public/sidebar.js +44 -5
  32. package/board/public/style.css +108 -37
  33. package/board/public/ui-cards.js +41 -30
  34. package/board/public/ui-header.js +2 -2
  35. package/board/public/ui-order.js +12 -10
  36. package/board/public/ui-questions.js +25 -38
  37. package/board/public/ui-sidebar.js +18 -12
  38. package/board/public/ui-threads.js +3 -3
  39. package/board/public/ui.js +40 -8
  40. package/board/public/view-hub-settings.js +11 -10
  41. package/board/public/view-hub.js +17 -3
  42. package/board/public/view-questions.js +142 -199
  43. package/board/public/view-settings.js +191 -72
  44. package/board/server.mjs +19 -20
  45. package/board/store.mjs +20 -15
  46. package/board/transcript.mjs +2 -0
  47. package/board/worktree.mjs +24 -20
  48. package/hooks-plugin/hooks/board-data-gate.mjs +50 -0
  49. package/hooks-plugin/hooks/hooks.json +9 -0
  50. package/hub/boards.mjs +4 -4
  51. package/hub/front-door.mjs +5 -5
  52. package/hub/github.mjs +3 -3
  53. package/hub/hub.mjs +11 -11
  54. package/hub/linear.mjs +1 -2
  55. package/hub/live.mjs +2 -2
  56. package/hub/locks.mjs +1 -1
  57. package/hub/pr-report.mjs +2 -2
  58. package/hub/presence.mjs +1 -1
  59. package/hub/push.mjs +2 -2
  60. package/hub/readiness.mjs +1 -2
  61. package/hub/review-send.mjs +1 -0
  62. package/hub/secrets.mjs +2 -0
  63. package/hub/self-restart.mjs +2 -0
  64. package/hub/sessions.mjs +2 -2
  65. package/hub/share.mjs +1 -0
  66. package/hub/slack.mjs +2 -2
  67. package/hub/stream.mjs +10 -13
  68. package/hub/try.mjs +6 -6
  69. package/hub/upgrade.mjs +1 -1
  70. package/hub/usage.mjs +3 -3
  71. package/hub/views.mjs +1 -1
  72. package/package.json +2 -1
  73. package/shared/audit.mjs +4 -0
  74. package/shared/fake-gh.mjs +17 -4
  75. package/shared/service.mjs +4 -4
  76. package/shared/usage-gate.mjs +1 -1
package/bin/kickflip.mjs CHANGED
@@ -37,7 +37,7 @@
37
37
  // --template board runs the shared board (../board/server.mjs) from the site dir,
38
38
  // writing its board.json; --items is "waves" (default) or a wave.json-format file, made with no
39
39
  // items when missing.
40
- // It then runs handshake, unless this session already answered the board's hello, and
40
+ // It then runs handshake, unless this session already answered the board's ping, and
41
41
  // asks the hub for one poll (as poll-now --keep-queue), so the board's GitHub link passes
42
42
  // without waiting for the next slot. Prints poll: "reached this board", or why not
43
43
  // --icon names a line icon from ../hub/icons.mjs and --color tints it in the
@@ -88,9 +88,9 @@
88
88
  // kickflip sessions [--json]
89
89
  // one line per board: route, session id, live (background or terminal) or not, folder
90
90
  // kickflip handshake <route>
91
- // tests a board's hub links (../hub/boards.mjs handshake): appends a `hello` event, which the
92
- // owning session's watcher answers when it prints it. The board shows a setup checklist
93
- // until the watcher answered and the hub's GitHub check reached it. Prints {route, hello}
91
+ // tests a board's hub links (../hub/boards.mjs handshake): appends a `ping` event, which the
92
+ // owning session's watcher answers when it sees it. The board shows a setup checklist
93
+ // until the watcher answered and the hub's GitHub check reached it. Prints {route, ping}
94
94
  // kickflip set <route> [--icon <key>] [--color <hex>] [--hub | --no-hub]
95
95
  // changes an existing site's icon or color without joining; '' clears one. --hub makes the board the
96
96
  // hub board, whose session runs in tmux and `hub` attaches to (`hub: true` in its entry), clearing the flag from any other
@@ -101,7 +101,8 @@
101
101
  // prints the hub's HTTPS address on the tailnet, the one to open on the phone, or with a route that
102
102
  // site's (./install.mjs tailnetUrl). Exit 1 when Tailscale isn't installed or running, or HTTPS isn't on for the tailnet,
103
103
  // 2 for a route with no site
104
- // kickflip restart <route>
104
+ // kickflip restart [route]
105
+ // restarts the site at that route; with no route, restarts the hub through its service
105
106
  // kickflip logs <route> [--lines <n>]
106
107
  // kickflip init [--dry-run] | uninstall
107
108
  // init is the first-run name for doctor --fix. It links the running package or clone, hooks plugin
@@ -112,8 +113,10 @@
112
113
  // --dry-run prints what init would move, link and start, and changes nothing.
113
114
  // uninstall stops the hub and removes its service, kickflip's status-line link and Tailscale /;
114
115
  // Claude settings and skill links are kept
115
- // kickflip update
116
- // installs @lovek4d/kickflip@latest globally with npm, then restarts the hub.
116
+ // kickflip update [--no-restart]
117
+ // installs @lovek4d/kickflip@latest globally with npm. When the version changed it prints
118
+ // "<old> > <new>" and restarts the hub; otherwise it prints "no new version available" and leaves the hub running.
119
+ // --no-restart leaves the hub running on its old code (the hub pulls this way, and offers Restart).
117
120
  // A clone refuses (exit 2); update it with git pull
118
121
  // kickflip push --kind action|prompt|fault|reminder --title <t> [--body <b>] [--url </route/path>] [--tag <tag>]
119
122
  // [--now | --urgent]
@@ -148,15 +151,20 @@
148
151
  // prints {pause_at, state, window, used, resets_at, codex: {past, window, used, resets_at}}; a read exits 0.
149
152
  // pause-at saves the line in steps of 5 (default 90, 100 Off); keep-going lifts the current Claude pause
150
153
  // until its window resets; stop restores it. Codex hands work to Opus past the same line.
154
+ // kickflip audit
155
+ // prints the hub's audit log of the last 30 days (~/.claude/kickflip/audit.jsonl): each call the hub's code
156
+ // made on its own for no one board (usage-pause, usage-resume, linear-move) as
157
+ // "<at> <call> [<ticket>]: <result>. <reason>" and the inputs it read. A board's own calls are in its
158
+ // data/audit.jsonl: board.mjs --site <route> audit (docs/adr/2026-11-05-0913-the-hub-and-each-board-keep-an-audit-log-of-the-calls-their-code-makes.md)
151
159
  // kickflip poll-now [--keep-queue]
152
160
  // asks the hub for one poll now (GitHub check, github-change events,
153
161
  // checked.json, then the queue unless --keep-queue) and prints its result
154
162
  // Exit codes: 0 ok, 1 error, 2 bad usage, 3 route owned by another session (join/leave), or its recorded session is
155
163
  // live (start/resume/hub). hub passes through claude's exit code.
156
- var xe=Object.defineProperty;var p=(e,t)=>xe(e,"name",{value:t,configurable:!0});import w from"node:fs";import u from"node:path";import L from"node:os";import ie from"node:net";import _e from"node:readline/promises";import{execFileSync as re,spawnSync as K}from"node:child_process";import{fileURLToPath as Ne}from"node:url";import{ICON_KEYS as ae}from"../hub/icons.mjs";import{liveSessions as ce}from"../hub/live.mjs";import{isBoardSite as P,writeManifest as v}from"../hub/boards.mjs";import{joinName as Te,routeFromName as F,routeRecord as g,validRoute as C}from"../hub/routes.mjs";import{defaultBranch as Ie,githubFromOrigin as Fe}from"../hub/repos.mjs";import{uninstallStatusLine as Ce,storedPath as Re,nodeBin as U,watcherCommand as Ee,tailnetUrl as Be}from"./install.mjs";import{hubService as de}from"../shared/service.mjs";import{tailscaleBin as ue}from"../shared/tailscale.mjs";import{runDoctor as De}from"./doctor.mjs";import{cloneRoot as Le}from"../shared/repos.mjs";const j=Le(),_=u.join(L.homedir(),".claude","kickflip"),Pe=u.join(_,"manifest.json"),le=u.join(_,"logs"),T=Number(process.env.KICKFLIP_HUB_PORT||4500),G=4600,Ae=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,[W,...S]=process.argv.slice(2),s=Object.assign(Object.create(null),{_:[]});for(let e=0;e<S.length;e++){const t=S[e];if(t.startsWith("--")){const n=t.slice(2);n==="fix"||n==="force"||n==="json"||n==="urgent"||n==="now"||n==="keep-queue"||n==="hub"||n==="no-hub"||n==="dry-run"||n==="watch"&&(e+1>=S.length||S[e+1].startsWith("--"))?s[n]=!0:s[n]=S[++e]}else s._.push(t)}const h=p(e=>console.log(typeof e=="string"?e:JSON.stringify(e,null,2)),"out");class I extends Error{static{p(this,"Exit")}constructor(t,n){super(t),this.code=n}}const i=p((e,t=1)=>{throw new I(e,t)},"fail");function Y(){s.icon&&!ae.includes(s.icon)&&i(`--icon takes one of: ${ae.join(", ")}`,2),s.color&&!Ae.test(s.color)&&i("--color takes a CSS hex color, such as #3b82f6",2)}p(Y,"checkLook");function Q(e){for(const t of["icon","color"])s[t]===""?delete e[t]:s[t]!==void 0&&(e[t]=s[t])}p(Q,"applyLook");const fe=p(()=>s.hub&&s["no-hub"]&&i("pass --hub or --no-hub, not both",2),"checkHub"),he=p(e=>i(`/${e} is not a board; only a board can be the hub board`,2),"notBoard");function X(e,t,n){if(s["no-hub"]&&delete n.hub,!!s.hub){P(n)||he(t);for(const[o,l]of Object.entries(e.sites))o!==t&&l?.hub&&delete l.hub;n.hub=!0}}p(X,"applyHub");function y(){try{const e=JSON.parse(w.readFileSync(Pe,"utf8"));return e.sites||={},e}catch(e){if(e.code==="ENOENT")return{version:1,sites:{}};i("manifest unreadable: "+e.message)}}p(y,"readManifest");const pe=p(e=>{try{return JSON.parse(w.readFileSync(e,"utf8"))}catch{return null}},"readJSON"),R=p(()=>import(u.join(j,"hub","sessions.mjs")),"sessionsModule");async function A(e){const{SessionError:t}=await R();try{return await e()}catch(n){throw n instanceof t&&i(n.message,n.reason==="live"?3:n.reason==="hub"?2:1),n}}p(A,"sessionCall");async function me(e){const{handshake:t}=await import(u.join(j,"hub","boards.mjs"));try{return await t(e,y())}catch(n){return i(n.message,2)}}p(me,"runHandshake");async function Je(e){for(let t=0;t<2;t++){let n;try{n=await fetch(`http://127.0.0.1:${T}/_hub/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({flush:!1}),signal:AbortSignal.timeout(5*6e4)})}catch(l){return`not run (${l.message})`}if(!n.ok)return`not run (the hub answered ${n.status})`;const o=await n.json();if(o.checked?.includes(e))return"reached this board";if(o.failed?.length)return`missed this board: ${o.failed[0]}`}return"missed this board"}p(Je,"pollFor");async function O(e){const{withManifestLock:t}=await import(u.join(j,"hub","boards.mjs"));try{return await t(e)}catch(n){throw n.code==="ELOCKED"&&i(n.message),n}}p(O,"withLock");function we(e){return new Promise(t=>{const n=ie.connect({port:e,host:"127.0.0.1"}),o=p(l=>{n.destroy(),t(l)},"done");n.setTimeout(500,()=>o(!1)),n.on("connect",()=>o(!0)),n.on("error",()=>o(!1))})}p(we,"connects");function He(e){return new Promise(t=>{const n=ie.createServer();n.once("error",()=>t(!1)),n.listen(e,"0.0.0.0",()=>n.close(()=>t(!0)))})}p(He,"bindable");async function J(e){const t=new Set([...Object.values(e.sites),...Object.values(e.closed||{}).map(n=>n.site)].map(n=>n?.port));for(let n=G;n<G+400;n++)if(!t.has(n)&&!await we(n)&&await He(n))return n;i("no free port found from "+G)}p(J,"freePort");function qe(){const e=ue();if(!e)return"";try{return(JSON.parse(re(e,["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})).Self?.DNSName||"").replace(/\.$/,"")}catch{return""}}p(qe,"tailnetHost");const Z=p(e=>{const t=qe();return t?`https://${t}/${e}/`:`http://127.0.0.1:${T}/${e}/`},"siteUrl");async function H(){try{return await(await fetch(`http://127.0.0.1:${T}/_hub/status.json`,{signal:AbortSignal.timeout(1500)})).json()}catch{return null}}p(H,"hubStatus");const ge=p(e=>{try{return w.statSync(e).isDirectory()}catch{return!1}},"isFolder"),ze=p(e=>{try{return w.realpathSync(e)}catch{return null}},"realPath");function be(e=t=>{}){(typeof s.name!="string"||!s.name.trim())&&i('join needs --name "<name>": the board or page name, which gives its route',2);const t=s.name.trim().replace(/\s+/g," "),n=F(t);return C(n)||i(`--name "${t}" needs a letter or digit for its route`,2),{route:n,title:t===n&&e(n)?.title||t}}p(be,"named");function ye(e,{title:t,items:n,tickets:o}){w.mkdirSync(u.join(e,"data"),{recursive:!0});const l=u.join(e,"board.json"),c=w.existsSync(l)?JSON.parse(w.readFileSync(l,"utf8")):{};c.title=t,c.items=Re(n||c.items||"waves"),o&&(c.tickets=o),w.writeFileSync(l,JSON.stringify(c,null,2)+`
157
- `);const r=c.items==="waves"?null:u.resolve(e,c.items);return r&&!w.existsSync(r)&&(w.mkdirSync(u.dirname(r),{recursive:!0}),w.writeFileSync(r,JSON.stringify({title:c.title,items:[]},null,2)+`
158
- `)),[U(),u.join(j,"board","server.mjs"),e]}p(ye,"boardFiles");async function V(e,t){const{startSession:n,withSessionLock:o}=await R();return o(e,async()=>{const l=await A(()=>n(e,{manifest:y(),...t}));return await O(async()=>{const c=y(),r={session:l.session,label:l.name,since:new Date().toISOString(),repo:l.repo,...l.model?{model:l.model}:{}};g(c.sites,e)?(c.sites[e].owner=r,c.sites[e].updated=r.since):c.starting={...c.starting,[e]:{...g(c.starting,e),...r}},await v(c)}),l})}p(V,"startRecorded");async function q(e){const{hubSession:t}=await R(),n=await A(()=>t({manifest:y(),repo:e}));process.exitCode=n.status}p(q,"openHub");const ke=p((e,...t)=>{const n=K("git",["-C",e,...t],{encoding:"utf8"});return n.status===0?n.stdout.trim():null},"git"),ee=p(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"canAsk");async function te(e,t="stopped at the prompt; nothing changed"){const n=_e.createInterface({input:process.stdin,output:process.stdout});try{return(await n.question(e)).trim()}catch(o){throw o.code==="ABORT_ERR"&&i(t),o}finally{n.close()}}p(te,"ask");const Se=p((e,t)=>!!(g(e.sites,t)||g(e.starting,t)||g(e.closed,t)),"taken");function Me(e){return!/^[A-Za-z0-9 ]+$/.test(e)||!C(F(e))?"A board name takes letters, digits and spaces, up to 41 characters of route.":Se(y(),F(e))?`/${F(e)} is taken; pick another name.`:null}p(Me,"nameProblem");const je="--template board --items data/wave.json";async function Ke(){const e=ke(process.cwd(),"rev-parse","--show-toplevel");e||i(`${process.cwd()} is not in a git repo; run kickflip join in the folder of the repo to add as a board`,2);const t=w.realpathSync(e);await H()||i("the hub is not running; run kickflip init to set it up, then kickflip join here again");const n=Object.entries(y().sites).find(([,f])=>P(f)&&f.owner?.repo&&ze(f.owner.repo)===t),o=await Ie(t);if(n)return Ue(...n,o);const l=u.basename(t).replace(/[^A-Za-z0-9]+/g," ").trim();let c=s.name?.trim();for(c===void 0&&!ee()&&i('join needs --name "<Board name>" when it has no terminal to ask in',2);;){c===void 0&&(c=await te(`Board name${l?` (${l})`:""}: `)||l);const f=Me(c);if(!f)break;s.name!==void 0&&i(f,2),h(f),c=void 0}const r=c.replace(/\s+/g," "),m=F(r),d=ke(t,"remote","get-url","origin"),a=d?Fe(d):null,{trustFolder:b}=await import("../hub/trust.mjs");try{b(t)}catch(f){i(`Couldn't trust this folder for Claude Code: ${f.message}`)}if(await O(async()=>{const f=y();Se(f,m)&&i(`/${m} is taken; pick another name`,2);const k=u.join(_,"sites",m),$=new Date().toISOString(),x={dir:k,port:await J(f),cmd:ye(k,{title:r,items:"data/wave.json"}),watch:["data/events.jsonl"],title:r,local:!0,...a?{github:a}:{},...o?{branch:o}:{},owner:{repo:t},created:$,updated:$};f.sites={...f.sites,[m]:x},X(f,m,x),await v(f)}),h(`Made ${r} at ${Z(m)}, working in ${t}${a?` (${a})`:""}.`),s.hub)return h("It is the hub board, so its session runs in tmux, attached here."),q(t);try{await V(m,{repo:t,prompt:je})}catch(f){throw f instanceof I&&i(`${f.message}
159
- The board is made; run kickflip join here again to start its session.`,f.code),f}h("Its session is starting in the background, and joins the board shortly.")}p(Ke,"joinFolder");async function Ue(e,t,n){const o=t.title||e;h(`This folder already has a board: ${o} (/${e}).`),n&&n!==t.branch&&(await O(async()=>{const m=y();Object.assign(g(m.sites,e),{branch:n,updated:new Date().toISOString()}),await v(m)}),h(`Its branch is now ${n}${t.branch?` (it was ${t.branch})`:""}.`)),ee()||i(t.hub===!0?"Open its session with kickflip hub.":"Run kickflip join in a terminal to restart its session, or tap Restart on its row of the Hub page.");const l=(await te("Restart its session? (Y/n) ")).toLowerCase();if(l&&!"yes".startsWith(l))return;if(!t.owner.session)return t.hub===!0?q(t.owner.repo):(await V(e,{repo:t.owner.repo,prompt:je}),h("Its session is starting in the background."));const c=await fetch(`http://127.0.0.1:${T}/_hub/restart-board`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:e}),signal:AbortSignal.timeout(5*6e4)}),r=await c.json();if(c.ok||i(r.error),h(`Restarted ${o}'s session.`),t.hub===!0)return q(t.owner.repo)}p(Ue,"restartFolderBoard");const ne=["title","description","icon","color","created","watch","filter","hub","github","remote","branch","local"],$e=["notifications","quiet","codexShare"],E="kickflip-board",Ge=/^(\.watch-cursor-.*\.json|watcher\.json)$/,B=p((e,t)=>Object.fromEntries(t.filter(n=>e[n]!==void 0).map(n=>[n,e[n]])),"pick"),z=p(e=>/^[\w@%+=:,./-]+$/.test(e)?e:`'${String(e).replace(/'/g,"'\\''")}'`,"shellQuote");function ve(e){const t=K("tar",e[0]==="-czf"?["--no-xattrs",...e]:e,{encoding:"utf8",env:{...process.env,COPYFILE_DISABLE:"1"}});t.status!==0&&i(`tar ${e[0]} failed: ${(t.stderr||t.error?.message||"").trim()}`)}p(ve,"tar");function We(e,t){const n=e.entry.title||e.route,o=Object.keys(e.settings).map(l=>({notifications:"Notifications",quiet:"Quiet hours",codexShare:"Codex share"})[l]);return`# Moving ${n} (/${e.route}) to another machine
164
+ var _e=Object.defineProperty;var h=(e,t)=>_e(e,"name",{value:t,configurable:!0});import w from"node:fs";import d from"node:path";import A from"node:os";import ie from"node:net";import Ne from"node:readline/promises";import{execFileSync as re,spawnSync as K}from"node:child_process";import{fileURLToPath as Te}from"node:url";import{ICON_KEYS as ae}from"../hub/icons.mjs";import{liveSessions as ce}from"../hub/live.mjs";import{isBoardSite as D,writeManifest as v}from"../hub/boards.mjs";import{joinName as Fe,routeFromName as I,routeRecord as g,validRoute as C}from"../hub/routes.mjs";import{defaultBranch as Ie,githubFromOrigin as Ce}from"../hub/repos.mjs";import{uninstallStatusLine as Re,storedPath as Ee,nodeBin as G,watcherCommand as Be,tailnetUrl as Le}from"./install.mjs";import{hubService as de}from"../shared/service.mjs";import{tailscaleBin as ue}from"../shared/tailscale.mjs";import{runDoctor as Ae}from"./doctor.mjs";import{cloneRoot as De}from"../shared/repos.mjs";const j=De(),_=d.join(A.homedir(),".claude","kickflip"),Pe=d.join(_,"manifest.json"),le=d.join(_,"logs"),T=Number(process.env.KICKFLIP_HUB_PORT||4500),U=4600,He=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,[W,...S]=process.argv.slice(2),s=Object.assign(Object.create(null),{_:[]});for(let e=0;e<S.length;e++){const t=S[e];if(t.startsWith("--")){const n=t.slice(2);n==="fix"||n==="force"||n==="json"||n==="urgent"||n==="now"||n==="keep-queue"||n==="hub"||n==="no-hub"||n==="dry-run"||n==="no-restart"||n==="watch"&&(e+1>=S.length||S[e+1].startsWith("--"))?s[n]=!0:s[n]=S[++e]}else s._.push(t)}const l=h(e=>console.log(typeof e=="string"?e:JSON.stringify(e,null,2)),"out");class F extends Error{static{h(this,"Exit")}constructor(t,n){super(t),this.code=n}}const i=h((e,t=1)=>{throw new F(e,t)},"fail");function Y(){s.icon&&!ae.includes(s.icon)&&i(`--icon takes one of: ${ae.join(", ")}`,2),s.color&&!He.test(s.color)&&i("--color takes a CSS hex color, such as #3b82f6",2)}h(Y,"checkLook");function Q(e){for(const t of["icon","color"])s[t]===""?delete e[t]:s[t]!==void 0&&(e[t]=s[t])}h(Q,"applyLook");const fe=h(()=>s.hub&&s["no-hub"]&&i("pass --hub or --no-hub, not both",2),"checkHub"),he=h(e=>i(`/${e} is not a board; only a board can be the hub board`,2),"notBoard");function X(e,t,n){if(s["no-hub"]&&delete n.hub,!!s.hub){D(n)||he(t);for(const[o,f]of Object.entries(e.sites))o!==t&&f?.hub&&delete f.hub;n.hub=!0}}h(X,"applyHub");function y(){try{const e=JSON.parse(w.readFileSync(Pe,"utf8"));return e.sites||={},e}catch(e){if(e.code==="ENOENT")return{version:1,sites:{}};i("manifest unreadable: "+e.message)}}h(y,"readManifest");const pe=h(e=>{try{return JSON.parse(w.readFileSync(e,"utf8"))}catch{return null}},"readJSON"),R=h(()=>import(d.join(j,"hub","sessions.mjs")),"sessionsModule");async function P(e){const{SessionError:t}=await R();try{return await e()}catch(n){throw n instanceof t&&i(n.message,n.reason==="live"?3:n.reason==="hub"?2:1),n}}h(P,"sessionCall");async function me(e){const{handshake:t}=await import(d.join(j,"hub","boards.mjs"));try{return await t(e,y())}catch(n){return i(n.message,2)}}h(me,"runHandshake");async function Je(e){for(let t=0;t<2;t++){let n;try{n=await fetch(`http://127.0.0.1:${T}/_hub/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({flush:!1}),signal:AbortSignal.timeout(5*6e4)})}catch(f){return`not run (${f.message})`}if(!n.ok)return`not run (the hub answered ${n.status})`;const o=await n.json();if(o.checked?.includes(e))return"reached this board";if(o.failed?.length)return`missed this board: ${o.failed[0]}`}return"missed this board"}h(Je,"pollFor");async function O(e){const{withManifestLock:t}=await import(d.join(j,"hub","boards.mjs"));try{return await t(e)}catch(n){throw n.code==="ELOCKED"&&i(n.message),n}}h(O,"withLock");function we(e){return new Promise(t=>{const n=ie.connect({port:e,host:"127.0.0.1"}),o=h(f=>{n.destroy(),t(f)},"done");n.setTimeout(500,()=>o(!1)),n.on("connect",()=>o(!0)),n.on("error",()=>o(!1))})}h(we,"connects");function ze(e){return new Promise(t=>{const n=ie.createServer();n.once("error",()=>t(!1)),n.listen(e,"0.0.0.0",()=>n.close(()=>t(!0)))})}h(ze,"bindable");async function H(e){const t=new Set([...Object.values(e.sites),...Object.values(e.closed||{}).map(n=>n.site)].map(n=>n?.port));for(let n=U;n<U+400;n++)if(!t.has(n)&&!await we(n)&&await ze(n))return n;i("no free port found from "+U)}h(H,"freePort");function qe(){const e=ue();if(!e)return"";try{return(JSON.parse(re(e,["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})).Self?.DNSName||"").replace(/\.$/,"")}catch{return""}}h(qe,"tailnetHost");const Z=h(e=>{const t=qe();return t?`https://${t}/${e}/`:`http://127.0.0.1:${T}/${e}/`},"siteUrl");async function J(){try{return await(await fetch(`http://127.0.0.1:${T}/_hub/status.json`,{signal:AbortSignal.timeout(1500)})).json()}catch{return null}}h(J,"hubStatus");const ge=h(e=>{try{return w.statSync(e).isDirectory()}catch{return!1}},"isFolder"),Me=h(e=>{try{return w.realpathSync(e)}catch{return null}},"realPath");function be(e=t=>{}){(typeof s.name!="string"||!s.name.trim())&&i('join needs --name "<name>": the board or page name, which gives its route',2);const t=s.name.trim().replace(/\s+/g," "),n=I(t);return C(n)||i(`--name "${t}" needs a letter or digit for its route`,2),{route:n,title:t===n&&e(n)?.title||t}}h(be,"named");function ye(e,{title:t,items:n,tickets:o}){w.mkdirSync(d.join(e,"data"),{recursive:!0});const f=d.join(e,"board.json"),c=w.existsSync(f)?JSON.parse(w.readFileSync(f,"utf8")):{};c.title=t,c.items=Ee(n||c.items||"waves"),o&&(c.tickets=o),w.writeFileSync(f,JSON.stringify(c,null,2)+`
165
+ `);const r=c.items==="waves"?null:d.resolve(e,c.items);return r&&!w.existsSync(r)&&(w.mkdirSync(d.dirname(r),{recursive:!0}),w.writeFileSync(r,JSON.stringify({title:c.title,items:[]},null,2)+`
166
+ `)),[G(),d.join(j,"board","server.mjs"),e]}h(ye,"boardFiles");async function V(e,t){const{startSession:n,withSessionLock:o}=await R();return o(e,async()=>{const f=await P(()=>n(e,{manifest:y(),...t}));return await O(async()=>{const c=y(),r={session:f.session,label:f.name,since:new Date().toISOString(),repo:f.repo,...f.model?{model:f.model}:{}};g(c.sites,e)?(c.sites[e].owner=r,c.sites[e].updated=r.since):c.starting={...c.starting,[e]:{...g(c.starting,e),...r}},await v(c)}),f})}h(V,"startRecorded");async function z(e){const{hubSession:t}=await R(),n=await P(()=>t({manifest:y(),repo:e}));process.exitCode=n.status}h(z,"openHub");const ke=h((e,...t)=>{const n=K("git",["-C",e,...t],{encoding:"utf8"});return n.status===0?n.stdout.trim():null},"git"),ee=h(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"canAsk");async function te(e,t="stopped at the prompt; nothing changed"){const n=Ne.createInterface({input:process.stdin,output:process.stdout});try{return(await n.question(e)).trim()}catch(o){throw o.code==="ABORT_ERR"&&i(t),o}finally{n.close()}}h(te,"ask");const Se=h((e,t)=>!!(g(e.sites,t)||g(e.starting,t)||g(e.closed,t)),"taken");function Ke(e){return!/^[A-Za-z0-9 ]+$/.test(e)||!C(I(e))?"A board name takes letters, digits and spaces, up to 41 characters of route.":Se(y(),I(e))?`/${I(e)} is taken; pick another name.`:null}h(Ke,"nameProblem");const je="--template board --items data/wave.json";async function Ge(){const e=ke(process.cwd(),"rev-parse","--show-toplevel");e||i(`${process.cwd()} is not in a git repo; run kickflip join in the folder of the repo to add as a board`,2);const t=w.realpathSync(e);await J()||i("the hub is not running; run kickflip init to set it up, then kickflip join here again");const n=Object.entries(y().sites).find(([,p])=>D(p)&&p.owner?.repo&&Me(p.owner.repo)===t),o=await Ie(t);if(n)return Ue(...n,o);const f=d.basename(t).replace(/[^A-Za-z0-9]+/g," ").trim();let c=s.name?.trim();for(c===void 0&&!ee()&&i('join needs --name "<Board name>" when it has no terminal to ask in',2);;){c===void 0&&(c=await te(`Board name${f?` (${f})`:""}: `)||f);const p=Ke(c);if(!p)break;s.name!==void 0&&i(p,2),l(p),c=void 0}const r=c.replace(/\s+/g," "),m=I(r),u=ke(t,"remote","get-url","origin"),a=u?Ce(u):null,{trustFolder:b}=await import("../hub/trust.mjs");try{b(t)}catch(p){i(`Couldn't trust this folder for Claude Code: ${p.message}`)}if(await O(async()=>{const p=y();Se(p,m)&&i(`/${m} is taken; pick another name`,2);const k=d.join(_,"sites",m),$=new Date().toISOString(),x={dir:k,port:await H(p),cmd:ye(k,{title:r,items:"data/wave.json"}),watch:["data/events.jsonl"],title:r,local:!0,...a?{github:a}:{},...o?{branch:o}:{},owner:{repo:t},created:$,updated:$};p.sites={...p.sites,[m]:x},X(p,m,x),await v(p)}),l(`Made ${r} at ${Z(m)}, working in ${t}${a?` (${a})`:""}.`),s.hub)return l("It is the hub board, so its session runs in tmux, attached here."),z(t);try{await V(m,{repo:t,prompt:je})}catch(p){throw p instanceof F&&i(`${p.message}
167
+ The board is made; run kickflip join here again to start its session.`,p.code),p}l("Its session is starting in the background, and joins the board shortly.")}h(Ge,"joinFolder");function $e(e){const t=de(),n=t.restart();n&&i(`${e}: ${n}; run ${t.restartCommand}`),l("restarted the hub")}h($e,"restartHub");async function Ue(e,t,n){const o=t.title||e;l(`This folder already has a board: ${o} (/${e}).`),n&&n!==t.branch&&(await O(async()=>{const m=y();Object.assign(g(m.sites,e),{branch:n,updated:new Date().toISOString()}),await v(m)}),l(`Its branch is now ${n}${t.branch?` (it was ${t.branch})`:""}.`)),ee()||i(t.hub===!0?"Open its session with kickflip hub.":"Run kickflip join in a terminal to restart its session, or tap Restart on its row of the Hub page.");const f=(await te("Restart its session? (Y/n) ")).toLowerCase();if(f&&!"yes".startsWith(f))return;if(!t.owner.session)return t.hub===!0?z(t.owner.repo):(await V(e,{repo:t.owner.repo,prompt:je}),l("Its session is starting in the background."));const c=await fetch(`http://127.0.0.1:${T}/_hub/restart-board`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:e}),signal:AbortSignal.timeout(5*6e4)}),r=await c.json();if(c.ok||i(r.error),l(`Restarted ${o}'s session.`),t.hub===!0)return z(t.owner.repo)}h(Ue,"restartFolderBoard");const ne=["title","description","icon","color","created","watch","filter","hub","github","remote","branch","local"],ve=["notifications","quiet","codexShare"],E="kickflip-board",We=/^(\.watch-cursor-.*\.json|watcher\.json)$/,B=h((e,t)=>Object.fromEntries(t.filter(n=>e[n]!==void 0).map(n=>[n,e[n]])),"pick"),q=h(e=>/^[\w@%+=:,./-]+$/.test(e)?e:`'${String(e).replace(/'/g,"'\\''")}'`,"shellQuote");function Oe(e){const t=K("tar",e[0]==="-czf"?["--no-xattrs",...e]:e,{encoding:"utf8",env:{...process.env,COPYFILE_DISABLE:"1"}});t.status!==0&&i(`tar ${e[0]} failed: ${(t.stderr||t.error?.message||"").trim()}`)}h(Oe,"tar");function Ye(e,t){const n=e.entry.title||e.route,o=Object.keys(e.settings).map(f=>({notifications:"Notifications",quiet:"Quiet hours",codexShare:"Codex share"})[f]);return`# Moving ${n} (/${e.route}) to another machine
160
168
 
161
169
  Exported from ${e.from} at ${e.exported_at}. This bundle holds the board's folder and manifest entry${o.length?`, and the hub's ${o.length>1?`${o.slice(0,-1).join(", ")} and ${o.at(-1)}`:o[0]} settings, which import writes over the new machine's`:""}.
162
170
 
@@ -174,15 +182,16 @@ The bundle carries no secret and nothing tied to the old machine. Set these up o
174
182
 
175
183
  - GitHub sign-in: \`gh auth login\`.
176
184
  - Linear API key: Hub \u2192 Linear.
177
- - Slack: Claude's Slack connector in the new session, and the hub's Slack identity with \`board.mjs slack set --self-dm <D\u2026> --user <U\u2026>\`.
185
+ - Slack user token: Hub \u2192 Slack. Digests follow the hub's Slack timezone, set with \`board.mjs slack set --timezone Area/City\`.
178
186
  - Codex: \`codex login\`, if Codex builds.
179
187
  - Notifications: open the Hub page on each phone and tap Turn on.
180
188
  - Other hub settings, such as the pause line and Rules for every board, stay on the old machine.
181
189
 
182
190
  Manifest fields left out, which the new machine sets itself: ${e.dropped.length?e.dropped.join(", "):"none"}.
183
- `}p(We,"exportReadme");async function Ye(){Y();const e=s.port===void 0?void 0:Number(s.port);e!==void 0&&!(Number.isInteger(e)&&e>0&&e<65536)&&i("--port takes a port number",2),e===T&&i(`--port ${e} is the hub's own port`,2);let t;if(s.cmd!==void 0){try{t=JSON.parse(s.cmd)}catch{t=null}(!Array.isArray(t)||!t.length||!t.every(d=>typeof d=="string"))&&i(`--cmd takes a JSON array of strings, such as '["/abs/node","/abs/server.mjs"]'`,2)}const n=s.dir===void 0?void 0:u.resolve(s.dir);n!==void 0&&!t&&e===void 0&&!ge(n)&&i(`--dir ${n} is not a folder`,2);const{route:o,title:l}=be(d=>g(y().sites,d)),c=await O(async()=>{const d=y();g(d.closed,o)&&i("That board is closed; use kickflip reopen "+o,2),g(d.starting,o)&&i(`/${o} is a board that is starting; pick another route`,2);const a=g(d.sites,o);if(a?.owner?.session)throw h({error:"owned",route:o,owner:a.owner,hint:"a session owns this route: pick another route, or that session leaves it first"}),new I("",3);const b=new Date().toISOString(),f=a?{...a}:{created:b};delete f.watch,delete f.filter;{const k=t?{cmd:t,dir:n||a?.dir||process.cwd(),port:e??(a?.cmd?a.port:void 0)??await J(d)}:e!==void 0?{port:e,...n?{dir:n}:{}}:{dir:n};for(const $ of["cmd","dir","port","cwd","env"])delete f[$];Object.assign(f,k)}return f.title=l,s.description&&(f.description=s.description),Q(f),f.updated=b,d.sites={...d.sites,[o]:f},await v(d),f}),r=c.cmd?"cmd":c.port?"port":"files",m=await H();h({route:o,url:Z(o),serves:r,...c.port?{port:c.port}:{},...c.dir?{dir:c.dir}:{},...r==="port"?{answering:await we(c.port)}:{},hub:m?"running":"NOT running: run `kickflip doctor --fix`"})}p(Ye,"joinPage");const se={async doctor(){s["dry-run"]&&!s.fix&&i("--dry-run needs --fix",2);const e=ee()&&!s.json?n=>te(n,"stopped at the prompt; the clones not yet answered are kept"):void 0,{exitCode:t}=await De({fix:!!s.fix,dryRun:!!s["dry-run"],json:!!s.json,ask:e});process.exitCode=t},async join(){if(s._.length&&i(`join takes no route: --name "<name>" gives the title and the route, as in kickflip join --name ${z(s._[0])}`,2),s.title!==void 0&&i('join takes no --title: --name "<name>" gives the title and the route',2),!s.session){const r=["port","dir","cmd"].some(d=>s[d]!==void 0),m=["watch","template","filter","label","model","repo","force","items",...r?["hub"]:[]].find(d=>s[d]!==void 0);return m&&i(`--${m} needs --session <id> (this session's id)`,2),r?Ye():Ke()}const{route:e,title:t}=be(r=>g(y().sites,r));s.template&&s.template!=="board"&&i('--template takes "board"',2),Y(),fe();const n=await O(async()=>{const r=y();g(r.closed,e)&&i("That board is closed; use kickflip reopen "+e,2);const m=new Date().toISOString(),d=g(r.sites,e);if(d?.owner?.session&&d.owner.session!==s.session&&!s.force)throw h({error:"owned",route:e,owner:d.owner,hint:"ask the user, then rerun with --force to take it over"}),new I("",3);s.hub&&s.template!=="board"&&!P({dir:"",cmd:s.cmd?JSON.parse(s.cmd):d?.cmd})&&he(e);const a=d?{...d}:{};let b=!1;if(d||(a.dir=u.resolve(s.dir||u.join(_,"sites",e)),(!w.existsSync(a.dir)||w.readdirSync(a.dir).length===0)&&!s.cmd&&!s.template&&(w.cpSync(u.join(j,"starter"),a.dir,{recursive:!0}),b=!0),a.port=s.port?Number(s.port):await J(r),a.cmd=s.cmd?JSON.parse(s.cmd):[U(),u.join(a.dir,"server.mjs")],a.watch=["data/events.jsonl"],a.created=m),s.dir&&d&&(a.dir=u.resolve(s.dir)),s.port&&d&&(a.port=Number(s.port)),s.cmd&&d&&(a.cmd=JSON.parse(s.cmd)),s.template==="board"){const N=g(r.starting,e),Oe=!d&&N?.tickets&&(!N.session||N.session===s.session)?N.tickets:void 0;a.cmd=ye(a.dir,{title:t,items:s.items,tickets:Oe}),b=!d}a.title=t,s.description&&(a.description=s.description),typeof s.watch=="string"&&(a.watch=s.watch.split(",").map(N=>N.trim()).filter(Boolean)),s.filter!==void 0&&(a.filter=s.filter||void 0),Q(a),X(r,e,a);const f=d?.owner&&d.owner.session!==s.session?d.owner:null,k=g(r.starting,e)?.session===s.session?g(r.starting,e):null,$=g(r.starting,e);!d&&($?.github||$?.remote)&&(!$.session||$.session===s.session)&&($.github?a.github=$.github:a.remote=$.remote,a.branch=$.branch);const x=d?.owner?.session===s.session?d.owner:null,D=x||k||f;a.owner={...x||{session:s.session,since:m},label:s.label||D?.label||"",repo:s.repo?u.resolve(s.repo):(a.github||a.remote)&&D?.repo||ce()?.get(s.session)?.cwd||D?.repo||process.cwd()};const oe=s.model||D?.model;oe&&(a.owner.model=oe);const M=g(r.starting,e);return M&&(r.starting[e]={...M,joined_at:M.joined_at||m}),a.updated=m,r.sites={...r.sites,[e]:a},await v(r),{route:e,created:b,previousOwner:f,site:a}}),o=await H();let l,c;if(s.template==="board"){const r=pe(u.join(n.site.dir,"data","handshake.json"));l=r?.ack&&r.hello?.session===s.session?"answered before":await me(e),c=o?await Je(e):"not run (the hub is not running)"}h({route:e,url:Z(e),dir:n.site.dir,port:n.site.port,owner:n.site.owner,createdFromStarter:n.created,previousOwner:n.previousOwner,log:u.join(le,e+".log"),watcher:Ee(e,s.session,j),hub:o?"running":"NOT running: run `kickflip doctor --fix`",...l?{handshake:l}:{},...c?{poll:c}:{}})},async handshake(){const e=s._[0];e||i("handshake needs a route",2),h(await me(e))},async leave(){const e=s._[0];e||i("leave needs a route",2),await O(async()=>{const t=y(),n=g(t.sites,e);if(n||i("no site at /"+e),n.owner?.session&&!s.session&&!s.force&&i("a session owns /"+e+"; leave needs --session <id>, or --force",2),n.owner?.session&&n.owner.session!==s.session&&!s.force)throw h({error:"owned",route:e,owner:n.owner}),new I("",3);delete t.sites[e],await v(t),h({left:e,filesKept:n.dir})})},async start(){const e=s._[0];C(e)||i("start needs a route: lowercase letters, digits and dashes",2);const t=await V(e,{repo:s.repo,model:s.model,prompt:s.prompt});h({route:t.route,session:t.session,confirmed:t.confirmed,repo:t.repo,argv:t.argv,output:t.output})},async resume(){const e=s._[0];e||i("resume needs a route",2);const{resumeSession:t}=await R();h(await A(()=>t(e,{manifest:y()})))},async close(){const{closeBoard:e}=await import("../hub/close-board.mjs");try{h(await e(s._[0],s.name))}catch(t){i(t.message,t.status?2:1)}},async reopen(){const{reopenBoard:e}=await import("../hub/close-board.mjs");try{h(await A(()=>e(s._[0])))}catch(t){throw t.status&&i(t.message,2),t}},async export(){const e=s._[0];C(e)||i("export needs a route: lowercase letters, digits and dashes",2);const t=u.resolve(s.out||`kickflip-${e}.tgz`);w.existsSync(t)&&i(`${t} already exists; pass another --out`,2);const n=g(y().sites,e)||i("no site at /"+e);P(n)||i(`/${e} is not a board; export moves a board`,2);const o=w.realpathSync(n.dir),{itemSources:l,openBoardBuilders:c}=await import("../board/store.mjs"),r=(await l(o)).find(k=>u.relative(o,k.file).startsWith(".."));r&&i(`/${e}'s cards live outside its folder (${r.file}); export moves only a board whose board.json items is a file in its folder`);const m=await c(o);m.length&&i(`a builder is open on /${e}: ${m.map(k=>`${k.key} (${k.label})`).join(", ")}; export once it is done`);const{readSettingsFile:d}=await import("../hub/push.mjs"),a=B(n,ne),b={kickflip_export:1,route:e,exported_at:new Date().toISOString(),from:L.hostname(),entry:a,owner:B(n.owner||{},["label","model"]),settings:B(d(),$e),dropped:Object.keys(n).filter(k=>!ne.includes(k))},f=w.mkdtempSync(u.join(L.tmpdir(),"kickflip-export-"));try{const k=u.join(f,E),$=u.join(o,"data");w.cpSync(o,u.join(k,"site"),{recursive:!0,filter:p(x=>!(u.dirname(x)===$&&Ge.test(u.basename(x))),"filter")}),w.writeFileSync(u.join(k,"export.json"),JSON.stringify(b,null,2)+`
184
- `),w.writeFileSync(u.join(k,"README.md"),We(b,u.basename(t))),ve(["-czf",t,"-C",f,E])}finally{w.rmSync(f,{recursive:!0,force:!0})}h({route:e,file:t,entry:Object.keys(a),dropped:b.dropped,settings:Object.keys(b.settings)})},async import(){s._[0]||i("import needs the file kickflip export wrote",2);const e=u.resolve(s._[0]);w.existsSync(e)||i(`no file at ${e}`,2),w.mkdirSync(_,{recursive:!0});const t=w.mkdtempSync(u.join(_,".import-"));try{ve(["-xzf",e,"-C",t]);const n=pe(u.join(t,E,"export.json"));(n?.kickflip_export!==1||!C(n.route)||!ge(u.join(t,E,"site")))&&i(`${e} is not a kickflip export`,2);const{route:o}=n,l=u.join(_,"sites",o),c=await O(async()=>{const a=y();(g(a.sites,o)||g(a.closed,o)||g(a.starting,o))&&i(`/${o} already exists on this host; import never replaces a board`),w.existsSync(l)&&i(`${l} already exists; import never replaces a board's folder`);const b=B(n.entry||{},ne);b.hub&&Object.values(a.sites).some(k=>k?.hub)&&delete b.hub;const f={...b,dir:l,port:await J(a),cmd:[U(),u.join(j,"board","server.mjs"),l],updated:new Date().toISOString()};return w.mkdirSync(u.dirname(l),{recursive:!0}),w.renameSync(u.join(t,E,"site"),l),a.sites={...a.sites,[o]:f},await v(a),f}),r=B(n.settings||{},$e);if(Object.keys(r).length){const{readSettingsFile:a,writeSettingsFile:b}=await import("../hub/push.mjs");b({...a(),...r})}const{label:m,model:d}=n.owner||{};h({route:o,dir:l,port:c.port,settings:Object.keys(r),hub:c.hub===!0,join:`kickflip join --name ${z(Te(o,c.title))} --session <this session's id> --watch --template board${m?` --label ${z(m)}`:""}${d?` --model ${z(d)}`:""} --force`})}finally{w.rmSync(t,{recursive:!0,force:!0})}},async sessions(){const{sessionOf:e}=await R(),{listBoards:t}=await import(u.join(j,"hub","boards.mjs")),n=y(),o=ce(),c=[...t(n).map(r=>r.route),...Object.keys(n.starting||{}).filter(r=>!g(n.sites,r))].map(r=>{const m=e(n,r),d=m&&o?.get(m.session),a=m?o?d?d.kind==="bg"?"background":"terminal":null:"unknown":null;return{route:r,session:m?.session||null,live:a,repo:m?.repo||null,starting:!g(n.sites,r)}});if(s.json)return h(c);if(!c.length)return h("no boards");for(const r of c)h(`/${r.route} ${r.session||"no session"} ${r.live==="unknown"?"live unknown (ps gave no answer)":r.live?`live (${r.live})`:"not live"} ${r.repo||"no folder"}${r.starting?" (starting: not joined yet)":""}`)},async hub(){await q(s.repo)},async set(){const e=s._[0];e||i("set needs a route",2),s.icon===void 0&&s.color===void 0&&!s.hub&&!s["no-hub"]&&i("set needs --icon, --color, --hub or --no-hub",2),Y(),fe(),await O(async()=>{const t=y(),n=g(t.sites,e)||i("no site at /"+e);Q(n),X(t,e,n),n.updated=new Date().toISOString(),await v(t),h({route:e,icon:n.icon??null,color:n.color??null,hub:n.hub===!0})})},async restart(){const e=s._[0];await O(async()=>{const t=y();g(t.sites,e)||i("no site at /"+e),t.sites[e].restart_at=Date.now(),await v(t)}),h(`restarting /${e}; the hub picks it up within 2 seconds`)},async url(){const e=s._[0];e&&!g(y().sites,e)&&i("no site at /"+e,2);try{h(Be(e))}catch(t){i(t.message)}},async logs(){const e=s._[0],t=u.join(le,e+".log");w.existsSync(t)||i("no log yet for /"+e);const n=Number(s.lines||40);h(w.readFileSync(t,"utf8").split(`
191
+ `}h(Ye,"exportReadme");async function Qe(){Y();const e=s.port===void 0?void 0:Number(s.port);e!==void 0&&!(Number.isInteger(e)&&e>0&&e<65536)&&i("--port takes a port number",2),e===T&&i(`--port ${e} is the hub's own port`,2);let t;if(s.cmd!==void 0){try{t=JSON.parse(s.cmd)}catch{t=null}(!Array.isArray(t)||!t.length||!t.every(u=>typeof u=="string"))&&i(`--cmd takes a JSON array of strings, such as '["/abs/node","/abs/server.mjs"]'`,2)}const n=s.dir===void 0?void 0:d.resolve(s.dir);n!==void 0&&!t&&e===void 0&&!ge(n)&&i(`--dir ${n} is not a folder`,2);const{route:o,title:f}=be(u=>g(y().sites,u)),c=await O(async()=>{const u=y();g(u.closed,o)&&i("That board is closed; use kickflip reopen "+o,2),g(u.starting,o)&&i(`/${o} is a board that is starting; pick another route`,2);const a=g(u.sites,o);if(a?.owner?.session)throw l({error:"owned",route:o,owner:a.owner,hint:"a session owns this route: pick another route, or that session leaves it first"}),new F("",3);const b=new Date().toISOString(),p=a?{...a}:{created:b};delete p.watch,delete p.filter;{const k=t?{cmd:t,dir:n||a?.dir||process.cwd(),port:e??(a?.cmd?a.port:void 0)??await H(u)}:e!==void 0?{port:e,...n?{dir:n}:{}}:{dir:n};for(const $ of["cmd","dir","port","cwd","env"])delete p[$];Object.assign(p,k)}return p.title=f,s.description&&(p.description=s.description),Q(p),p.updated=b,u.sites={...u.sites,[o]:p},await v(u),p}),r=c.cmd?"cmd":c.port?"port":"files",m=await J();l({route:o,url:Z(o),serves:r,...c.port?{port:c.port}:{},...c.dir?{dir:c.dir}:{},...r==="port"?{answering:await we(c.port)}:{},hub:m?"running":"NOT running: run `kickflip doctor --fix`"})}h(Qe,"joinPage");const se={async doctor(){s["dry-run"]&&!s.fix&&i("--dry-run needs --fix",2);const e=ee()&&!s.json?n=>te(n,"stopped at the prompt; the clones not yet answered are kept"):void 0,{exitCode:t}=await Ae({fix:!!s.fix,dryRun:!!s["dry-run"],json:!!s.json,ask:e});process.exitCode=t},async join(){if(s._.length&&i(`join takes no route: --name "<name>" gives the title and the route, as in kickflip join --name ${q(s._[0])}`,2),s.title!==void 0&&i('join takes no --title: --name "<name>" gives the title and the route',2),!s.session){const r=["port","dir","cmd"].some(u=>s[u]!==void 0),m=["watch","template","filter","label","model","repo","force","items",...r?["hub"]:[]].find(u=>s[u]!==void 0);return m&&i(`--${m} needs --session <id> (this session's id)`,2),r?Qe():Ge()}const{route:e,title:t}=be(r=>g(y().sites,r));s.template&&s.template!=="board"&&i('--template takes "board"',2),Y(),fe();const n=await O(async()=>{const r=y();g(r.closed,e)&&i("That board is closed; use kickflip reopen "+e,2);const m=new Date().toISOString(),u=g(r.sites,e);if(u?.owner?.session&&u.owner.session!==s.session&&!s.force)throw l({error:"owned",route:e,owner:u.owner,hint:"ask the user, then rerun with --force to take it over"}),new F("",3);s.hub&&s.template!=="board"&&!D({dir:"",cmd:s.cmd?JSON.parse(s.cmd):u?.cmd})&&he(e);const a=u?{...u}:{};let b=!1;if(u||(a.dir=d.resolve(s.dir||d.join(_,"sites",e)),(!w.existsSync(a.dir)||w.readdirSync(a.dir).length===0)&&!s.cmd&&!s.template&&(w.cpSync(d.join(j,"starter"),a.dir,{recursive:!0}),b=!0),a.port=s.port?Number(s.port):await H(r),a.cmd=s.cmd?JSON.parse(s.cmd):[G(),d.join(a.dir,"server.mjs")],a.watch=["data/events.jsonl"],a.created=m),s.dir&&u&&(a.dir=d.resolve(s.dir)),s.port&&u&&(a.port=Number(s.port)),s.cmd&&u&&(a.cmd=JSON.parse(s.cmd)),s.template==="board"){const N=g(r.starting,e),xe=!u&&N?.tickets&&(!N.session||N.session===s.session)?N.tickets:void 0;a.cmd=ye(a.dir,{title:t,items:s.items,tickets:xe}),b=!u}a.title=t,s.description&&(a.description=s.description),typeof s.watch=="string"&&(a.watch=s.watch.split(",").map(N=>N.trim()).filter(Boolean)),s.filter!==void 0&&(a.filter=s.filter||void 0),Q(a),X(r,e,a);const p=u?.owner&&u.owner.session!==s.session?u.owner:null,k=g(r.starting,e)?.session===s.session?g(r.starting,e):null,$=g(r.starting,e);!u&&($?.github||$?.remote)&&(!$.session||$.session===s.session)&&($.github?a.github=$.github:a.remote=$.remote,a.branch=$.branch);const x=u?.owner?.session===s.session?u.owner:null,L=x||k||p;a.owner={...x||{session:s.session,since:m},label:s.label||L?.label||"",repo:s.repo?d.resolve(s.repo):(a.github||a.remote)&&L?.repo||ce()?.get(s.session)?.cwd||L?.repo||process.cwd()};const oe=s.model||L?.model;oe&&(a.owner.model=oe);const M=g(r.starting,e);return M&&(r.starting[e]={...M,joined_at:M.joined_at||m}),a.updated=m,r.sites={...r.sites,[e]:a},await v(r),{route:e,created:b,previousOwner:p,site:a}}),o=await J();let f,c;if(s.template==="board"){const r=pe(d.join(n.site.dir,"data","handshake.json"));f=r?.ack&&(r.ping||r.hello)?.session===s.session?"answered before":await me(e),c=o?await Je(e):"not run (the hub is not running)"}l({route:e,url:Z(e),dir:n.site.dir,port:n.site.port,owner:n.site.owner,createdFromStarter:n.created,previousOwner:n.previousOwner,log:d.join(le,e+".log"),watcher:Be(e,s.session,j),hub:o?"running":"NOT running: run `kickflip doctor --fix`",...f?{handshake:f}:{},...c?{poll:c}:{}})},async handshake(){const e=s._[0];e||i("handshake needs a route",2),l(await me(e))},async leave(){const e=s._[0];e||i("leave needs a route",2),await O(async()=>{const t=y(),n=g(t.sites,e);if(n||i("no site at /"+e),n.owner?.session&&!s.session&&!s.force&&i("a session owns /"+e+"; leave needs --session <id>, or --force",2),n.owner?.session&&n.owner.session!==s.session&&!s.force)throw l({error:"owned",route:e,owner:n.owner}),new F("",3);delete t.sites[e],await v(t),l({left:e,filesKept:n.dir})})},async start(){const e=s._[0];C(e)||i("start needs a route: lowercase letters, digits and dashes",2);const t=await V(e,{repo:s.repo,model:s.model,prompt:s.prompt});l({route:t.route,session:t.session,confirmed:t.confirmed,repo:t.repo,argv:t.argv,output:t.output})},async resume(){const e=s._[0];e||i("resume needs a route",2);const{resumeSession:t}=await R();l(await P(()=>t(e,{manifest:y()})))},async close(){const{closeBoard:e}=await import("../hub/close-board.mjs");try{l(await e(s._[0],s.name))}catch(t){i(t.message,t.status?2:1)}},async reopen(){const{reopenBoard:e}=await import("../hub/close-board.mjs");try{l(await P(()=>e(s._[0])))}catch(t){throw t.status&&i(t.message,2),t}},async export(){const e=s._[0];C(e)||i("export needs a route: lowercase letters, digits and dashes",2);const t=d.resolve(s.out||`kickflip-${e}.tgz`);w.existsSync(t)&&i(`${t} already exists; pass another --out`,2);const n=g(y().sites,e)||i("no site at /"+e);D(n)||i(`/${e} is not a board; export moves a board`,2);const o=w.realpathSync(n.dir),{itemSources:f,openBoardBuilders:c}=await import("../board/store.mjs"),r=(await f(o)).find(k=>d.relative(o,k.file).startsWith(".."));r&&i(`/${e}'s cards live outside its folder (${r.file}); export moves only a board whose board.json items is a file in its folder`);const m=await c(o);m.length&&i(`a builder is open on /${e}: ${m.map(k=>`${k.key} (${k.label})`).join(", ")}; export once it is done`);const{readSettingsFile:u}=await import("../hub/push.mjs"),a=B(n,ne),b={kickflip_export:1,route:e,exported_at:new Date().toISOString(),from:A.hostname(),entry:a,owner:B(n.owner||{},["label","model"]),settings:B(u(),ve),dropped:Object.keys(n).filter(k=>!ne.includes(k))},p=w.mkdtempSync(d.join(A.tmpdir(),"kickflip-export-"));try{const k=d.join(p,E),$=d.join(o,"data");w.cpSync(o,d.join(k,"site"),{recursive:!0,filter:h(x=>!(d.dirname(x)===$&&We.test(d.basename(x))),"filter")}),w.writeFileSync(d.join(k,"export.json"),JSON.stringify(b,null,2)+`
192
+ `),w.writeFileSync(d.join(k,"README.md"),Ye(b,d.basename(t))),Oe(["-czf",t,"-C",p,E])}finally{w.rmSync(p,{recursive:!0,force:!0})}l({route:e,file:t,entry:Object.keys(a),dropped:b.dropped,settings:Object.keys(b.settings)})},async import(){s._[0]||i("import needs the file kickflip export wrote",2);const e=d.resolve(s._[0]);w.existsSync(e)||i(`no file at ${e}`,2),w.mkdirSync(_,{recursive:!0});const t=w.mkdtempSync(d.join(_,".import-"));try{Oe(["-xzf",e,"-C",t]);const n=pe(d.join(t,E,"export.json"));(n?.kickflip_export!==1||!C(n.route)||!ge(d.join(t,E,"site")))&&i(`${e} is not a kickflip export`,2);const{route:o}=n,f=d.join(_,"sites",o),c=await O(async()=>{const a=y();(g(a.sites,o)||g(a.closed,o)||g(a.starting,o))&&i(`/${o} already exists on this host; import never replaces a board`),w.existsSync(f)&&i(`${f} already exists; import never replaces a board's folder`);const b=B(n.entry||{},ne);b.hub&&Object.values(a.sites).some(k=>k?.hub)&&delete b.hub;const p={...b,dir:f,port:await H(a),cmd:[G(),d.join(j,"board","server.mjs"),f],updated:new Date().toISOString()};return w.mkdirSync(d.dirname(f),{recursive:!0}),w.renameSync(d.join(t,E,"site"),f),a.sites={...a.sites,[o]:p},await v(a),p}),r=B(n.settings||{},ve);if(Object.keys(r).length){const{readSettingsFile:a,writeSettingsFile:b}=await import("../hub/push.mjs");b({...a(),...r})}const{label:m,model:u}=n.owner||{};l({route:o,dir:f,port:c.port,settings:Object.keys(r),hub:c.hub===!0,join:`kickflip join --name ${q(Fe(o,c.title))} --session <this session's id> --watch --template board${m?` --label ${q(m)}`:""}${u?` --model ${q(u)}`:""} --force`})}finally{w.rmSync(t,{recursive:!0,force:!0})}},async sessions(){const{sessionOf:e}=await R(),{listBoards:t}=await import(d.join(j,"hub","boards.mjs")),n=y(),o=ce(),c=[...t(n).map(r=>r.route),...Object.keys(n.starting||{}).filter(r=>!g(n.sites,r))].map(r=>{const m=e(n,r),u=m&&o?.get(m.session),a=m?o?u?u.kind==="bg"?"background":"terminal":null:"unknown":null;return{route:r,session:m?.session||null,live:a,repo:m?.repo||null,starting:!g(n.sites,r)}});if(s.json)return l(c);if(!c.length)return l("no boards");for(const r of c)l(`/${r.route} ${r.session||"no session"} ${r.live==="unknown"?"live unknown (ps gave no answer)":r.live?`live (${r.live})`:"not live"} ${r.repo||"no folder"}${r.starting?" (starting: not joined yet)":""}`)},async hub(){await z(s.repo)},async set(){const e=s._[0];e||i("set needs a route",2),s.icon===void 0&&s.color===void 0&&!s.hub&&!s["no-hub"]&&i("set needs --icon, --color, --hub or --no-hub",2),Y(),fe(),await O(async()=>{const t=y(),n=g(t.sites,e)||i("no site at /"+e);Q(n),X(t,e,n),n.updated=new Date().toISOString(),await v(t),l({route:e,icon:n.icon??null,color:n.color??null,hub:n.hub===!0})})},async restart(){const e=s._[0];if(!e)return $e("the hub did not restart");await O(async()=>{const t=y();g(t.sites,e)||i("no site at /"+e),t.sites[e].restart_at=Date.now(),await v(t)}),l(`restarting /${e}; the hub picks it up within 2 seconds`)},async url(){const e=s._[0];e&&!g(y().sites,e)&&i("no site at /"+e,2);try{l(Le(e))}catch(t){i(t.message)}},async logs(){const e=s._[0],t=d.join(le,e+".log");w.existsSync(t)||i("no log yet for /"+e);const n=Number(s.lines||40);l(w.readFileSync(t,"utf8").split(`
185
193
  `).slice(-n-1).join(`
186
- `))},async init(){s.fix=!0,await se.doctor()},async update(){w.existsSync(u.join(j,".git"))&&i(`${j} is a clone; update it with git pull`,2);const e=K("npm",["i","-g","@lovek4d/kickflip@latest"],{stdio:"inherit"});e.status!==0&&i(`npm update failed${e.error?": "+e.error.message:""}`);const t=de(),n=t.restart();n&&i(`update finished but the hub did not restart: ${n}; run ${t.restartCommand}`),h("updated kickflip and restarted the hub")},async uninstall(){Ce()&&h(`removed ${u.join(L.homedir(),".claude","statusline.sh")}`);const e=de();e.remove();const t=ue();if(t)try{re(t,["serve","--https=443","--set-path=/","off"],{stdio:"ignore"})}catch{}h(`hub stopped and removed from ${e.manager??"the host"}${t?"; tailscale / unmapped":""}. The manifest and sites are kept in ${_}`)},async push(){const{deliver:e,pushKindError:t}=await import(u.join(j,"hub","push.mjs")),n=t(s.kind);n&&i(n,2),s.title||i("push needs --title",2),s.url&&!s.url.startsWith("/")&&i("--url is a path on the hub, such as /<route>/page.html",2);const{sendWords:o,holdLine:l}=await import(u.join(j,"hub","schedule.mjs"));s.now&&s.urgent&&i("pass --now or --urgent, not both",2);const c=await e({title:s.title,body:s.body||"",url:s.url||"/",tag:s.tag},{kind:s.kind,urgent:!!s.urgent,immediate:!!s.now});if(c.noDevice&&i("no device has turned on notifications; open Hub \u2192 Notifications (/_hub/#notifications) in the Home Screen app and tap Turn on",3),c.dropped)return h("dropped (notifications are off on the Hub page)");if(c.queued){const{count:r,replaced:m,nextFlushAt:d,hold:a,sendFailed:b}=c.queued,f=s.now?a?`${l(a)}; `:b?"no device took it now; ":"":"";h(`queued (${f}${r} in queue${m?"; replaced the queued push with this tag":""}); next send ${o(d)}${d instanceof Date?` (${d.toISOString()})`:""}`),await H()||h("warning: the hub is not running, so the queue goes out only once it runs");return}h(c.sent),c.sent.some(r=>r.status>=200&&r.status<300)||i("every push was refused",1),h(s.urgent?"sent (urgent)":"sent")},async quiet(){const{readSettings:e}=await import(u.join(j,"hub","push.mjs")),{hold:t}=await import(u.join(j,"hub","schedule.mjs")),n=e(),o=t(new Date,n);h({quiet:n.quiet,held:o!==null,held_until:o?o.until instanceof Date?o.until.toISOString():o.until:null,held_why:o?.why??null,notifications:n.notifications})},async notifications(){const{setNotifications:e,readSettings:t}=await import(u.join(j,"hub","push.mjs")),[n,o]=s._,c=n===void 0?null:n==="on"||n==="off"?{on:n==="on"}:n==="weekends"?{weekends_off:p((m,d)=>m==="on"?!0:m==="off"?!1:i(`${d} takes on or off`,2),"onOff")(o,"weekends")}:n==="snooze"?{snooze:o||i("snooze takes a length: <n>m, <n>h, <n>d, <n>w, tonight, morning, monday, forever or a date and time",2)}:n==="unsnooze"?{snooze:"off"}:i("notifications takes on, off, snooze <length>, unsnooze, or weekends on|off",2);if(!c)return h(t().notifications);let r;try{r=await e(c)}catch(m){throw m.status===400&&i(m.message,2),m}h(r.dropped?{...r.notifications,dropped:r.dropped}:r.notifications)},async"codex-share"(){(S.length>1||S.length&&s._.length!==1)&&i("codex-share takes auto, always, or off",2);const{readCodexShare:t,setCodexShare:n}=await import(u.join(j,"hub","push.mjs"));if(!S.length)return h(t());try{h(n(S[0]))}catch(o){throw o.status===400&&i(o.message,2),o.status===409&&i(o.message),o}},async"usage-gate"(){const{readUsageGate:e,setPauseAt:t,setKeepGoing:n}=await import("../shared/usage-gate.mjs");try{S.length&&(S[0]==="pause-at"&&S.length===2?t(S[1]):S[0]==="keep-going"&&S.length===1?n("on"):S[0]==="stop"&&S.length===1?n("off"):i("usage-gate takes pause-at <50..100>, keep-going, or stop",2)),h(e())}catch(o){throw o.status&&i(o.message,o.status===400?2:1),o}},async"poll-now"(){let e;try{e=await fetch(`http://127.0.0.1:${T}/_hub/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({flush:!s["keep-queue"]}),signal:AbortSignal.timeout(10*6e4)})}catch(t){i("the hub is not running: "+t.message)}e.ok||i(`the hub answered ${e.status}: ${(await e.text()).slice(0,200)}`),h(await e.json())}};if(!se[W]){const e=w.readFileSync(Ne(import.meta.url),"utf8").split(`
187
- `).slice(1);h(e.slice(0,e.findIndex(t=>!t.startsWith("//"))).map(t=>t.replace(/^\/\/ ?/,"")).join(`
188
- `)),process.exit(W?2:0)}try{await se[W]()}catch(e){if(!(e instanceof I))throw e;e.message&&console.error("kickflip: "+e.message),process.exit(e.code)}
194
+ `))},async init(){s.fix=!0,await se.doctor()},async update(){w.existsSync(d.join(j,".git"))&&i(`${j} is a clone; update it with git pull`,2);const e=h(()=>JSON.parse(w.readFileSync(d.join(j,"package.json"),"utf8")).version,"installedVersion"),t=e(),n=K("npm",["i","-g","@lovek4d/kickflip@latest"],{stdio:"inherit"});n.status!==0&&i(`npm update failed${n.error?": "+n.error.message:""}`);const o=e();if(o===t)return l("no new version available");l(`${t} > ${o}`),!s["no-restart"]&&$e("update finished but the hub did not restart")},async uninstall(){Re()&&l(`removed ${d.join(A.homedir(),".claude","statusline.sh")}`);const e=de();e.remove();const t=ue();if(t)try{re(t,["serve","--https=443","--set-path=/","off"],{stdio:"ignore"})}catch{}l(`hub stopped and removed from ${e.manager??"the host"}${t?"; tailscale / unmapped":""}. The manifest and sites are kept in ${_}`)},async push(){const{deliver:e,pushKindError:t}=await import(d.join(j,"hub","push.mjs")),n=t(s.kind);n&&i(n,2),s.title||i("push needs --title",2),s.url&&!s.url.startsWith("/")&&i("--url is a path on the hub, such as /<route>/page.html",2);const{sendWords:o,holdLine:f}=await import(d.join(j,"hub","schedule.mjs"));s.now&&s.urgent&&i("pass --now or --urgent, not both",2);const c=await e({title:s.title,body:s.body||"",url:s.url||"/",tag:s.tag},{kind:s.kind,urgent:!!s.urgent,immediate:!!s.now});if(c.noDevice&&i("no device has turned on notifications; open Hub \u2192 Notifications (/_hub/#notifications) in the Home Screen app and tap Turn on",3),c.dropped)return l("dropped (notifications are off on the Hub page)");if(c.queued){const{count:r,replaced:m,nextFlushAt:u,hold:a,sendFailed:b}=c.queued,p=s.now?a?`${f(a)}; `:b?"no device took it now; ":"":"";l(`queued (${p}${r} in queue${m?"; replaced the queued push with this tag":""}); next send ${o(u)}${u instanceof Date?` (${u.toISOString()})`:""}`),await J()||l("warning: the hub is not running, so the queue goes out only once it runs");return}l(c.sent),c.sent.some(r=>r.status>=200&&r.status<300)||i("every push was refused",1),l(s.urgent?"sent (urgent)":"sent")},async quiet(){const{readSettings:e}=await import(d.join(j,"hub","push.mjs")),{hold:t}=await import(d.join(j,"hub","schedule.mjs")),n=e(),o=t(new Date,n);l({quiet:n.quiet,held:o!==null,held_until:o?o.until instanceof Date?o.until.toISOString():o.until:null,held_why:o?.why??null,notifications:n.notifications})},async notifications(){const{setNotifications:e,readSettings:t}=await import(d.join(j,"hub","push.mjs")),[n,o]=s._,c=n===void 0?null:n==="on"||n==="off"?{on:n==="on"}:n==="weekends"?{weekends_off:h((m,u)=>m==="on"?!0:m==="off"?!1:i(`${u} takes on or off`,2),"onOff")(o,"weekends")}:n==="snooze"?{snooze:o||i("snooze takes a length: <n>m, <n>h, <n>d, <n>w, tonight, morning, monday, forever or a date and time",2)}:n==="unsnooze"?{snooze:"off"}:i("notifications takes on, off, snooze <length>, unsnooze, or weekends on|off",2);if(!c)return l(t().notifications);let r;try{r=await e(c)}catch(m){throw m.status===400&&i(m.message,2),m}l(r.dropped?{...r.notifications,dropped:r.dropped}:r.notifications)},async"codex-share"(){(S.length>1||S.length&&s._.length!==1)&&i("codex-share takes auto, always, or off",2);const{readCodexShare:t,setCodexShare:n}=await import(d.join(j,"hub","push.mjs"));if(!S.length)return l(t());try{l(n(S[0]))}catch(o){throw o.status===400&&i(o.message,2),o.status===409&&i(o.message),o}},async"usage-gate"(){const{readUsageGate:e,setPauseAt:t,setKeepGoing:n}=await import("../shared/usage-gate.mjs");try{S.length&&(S[0]==="pause-at"&&S.length===2?t(S[1]):S[0]==="keep-going"&&S.length===1?n("on"):S[0]==="stop"&&S.length===1?n("off"):i("usage-gate takes pause-at <50..100>, keep-going, or stop",2)),l(e())}catch(o){throw o.status&&i(o.message,o.status===400?2:1),o}},async audit(){S.length&&i("audit takes no arguments",2);const{readAudit:e,auditLines:t,hubAudit:n}=await import("../shared/audit.mjs");l(t(e(n())).join(`
195
+ `))},async"poll-now"(){let e;try{e=await fetch(`http://127.0.0.1:${T}/_hub/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({flush:!s["keep-queue"]}),signal:AbortSignal.timeout(10*6e4)})}catch(t){i("the hub is not running: "+t.message)}e.ok||i(`the hub answered ${e.status}: ${(await e.text()).slice(0,200)}`),l(await e.json())}};if(!se[W]){const e=w.readFileSync(Te(import.meta.url),"utf8").split(`
196
+ `).slice(1);l(e.slice(0,e.findIndex(t=>!t.startsWith("//"))).map(t=>t.replace(/^\/\/ ?/,"")).join(`
197
+ `)),process.exit(W?2:0)}try{await se[W]()}catch(e){if(!(e instanceof F))throw e;e.message&&console.error("kickflip: "+e.message),process.exit(e.code)}
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- var q=Object.defineProperty;var s=(e,o)=>q(e,"name",{value:o,configurable:!0});import c from"node:fs";import f from"node:path";import L from"node:os";import{routeRecord as m}from"../hub/routes.mjs";import{readHubRules as P,rulesOf as D,ruleLines as G}from"../hub/rules.mjs";import{boardAt as H,linksOf as U,hubLink as W,stopPreviousWatcher as _}from"../hub/boards.mjs";import{parentOf as J,sessionGone as K}from"../hub/live.mjs";import{ackHello as Q,cardName as B,markWorking as C,settingsLines as M,settingsOf as z,WORKING_KINDS as V}from"../board/store.mjs";import{readUsageGate as E,heldUsageEvent as X}from"../shared/usage-gate.mjs";const[O,g]=process.argv.slice(2);(!O||!g)&&(console.error("usage: wait-events.mjs <route> <session-id>"),process.exit(2));const Y=f.join(L.homedir(),".claude","kickflip","manifest.json");function A(){try{return m(JSON.parse(c.readFileSync(Y,"utf8")).sites,O)||null}catch{return}}s(A,"site");function v(e){const o=e.filter?new RegExp(e.filter):null,t=Object.create(null);for(const l of e.watch||["data/events.jsonl"]){let r=[];try{r=c.readFileSync(f.resolve(e.dir,l),"utf8").split(`
3
- `).filter(Boolean)}catch{}t[l]=o?r.filter(i=>o.test(i)):r}return t}s(v,"matching");const Z=`quiet The owner doesn't read this session's terminal. Answer a prompt typed in it in full. A wake, a task notification or a builder's result is not one: write no text of your own, since board.mjs and this watcher print one line for each thing done. Talk and questions go on the board, never AskUserQuestion; only a failure the board can't show, such as the hub being down, gets one line here. Each message to the owner stands alone in its card's thread: name cards by label (#96), and a pointer such as "above" or "here" must make sense in that thread, never point into this session.`,I={ask:s(e=>`new task ${e.id} received`,"ask"),"owner-answer":s(e=>`answer received to question ${e.data?.id}`,"owner-answer"),hello:s(e=>`hello ${e.id} from the hub answered`,"hello"),"overnight-triage":s(e=>`Overnight triage ${e.data?.date} asked: ${e.data?.cards?.length} cards wait on your answers`,"overnight-triage"),"pr-review":s(e=>`review asked on PR #${e.data?.pr}: the board was idle`,"pr-review"),"orchestrator-waits":s(e=>`waiting on you now: ${(e.data?.added||[]).join(", ")}`,"orchestrator-waits"),"review-answer":s(e=>`${e.data?.answer==="skip"?"skip":"post"} answered on the review of PR #${e.data?.pr}`,"review-answer")},R={"item-message":s(e=>`message received from ${e}'s thread`,"item-message"),"card-merge":s(e=>`merge asked on ${e}`,"card-merge"),"card-done":s(e=>`${e} marked done`,"card-done"),"card-bump":s(e=>`${e} bumped`,"card-bump"),"ask-bump":s(e=>`${e} bumped`,"ask-bump"),"ask-edited":s(e=>`${e} edited`,"ask-edited"),"ask-done":s(e=>`${e} marked done`,"ask-done"),"ask-withdrawn":s(e=>`${e} deleted`,"ask-withdrawn"),"card-hold":s((e,o)=>`${e} ${o.data?.hold?"held":"resumed"}`,"card-hold"),"card-unblocked":s(e=>`${e} unblocked`,"card-unblocked"),"prototype-request":s(e=>`prototype asked on ${e}`,"prototype-request"),"reask-request":s(e=>`question asked again on ${e}`,"reask-request"),"builder-ask":s((e,o)=>`${o.data?.ask} from ${e}'s builder: ${o.data?.text}`,"builder-ask"),"owner-check-broken":s((e,o)=>`${e}'s owner-step check can't run: ${o.data?.error}`,"owner-check-broken")};async function ee(e,o){let t;try{t=JSON.parse(o)}catch{return null}if(typeof t?.kind!="string")return null;const l=typeof t.data?.key=="string"?t.data.key:t.kind.startsWith("ask-")&&typeof t.data?.id=="string"?`ask:${t.data.id}`:null,r=l&&await B(e,l).catch(()=>l);return m(I,t.kind)?I[t.kind](t):r&&m(R,t.kind)?R[t.kind](r,t):r?`${t.kind} on ${r}`:`${t.kind} received`}s(ee,"plainLine");function te(e){let o=[];try{o=JSON.parse(c.readFileSync(f.resolve(e,"data","orchestrator-waits.json"),"utf8")).waits||[]}catch{}return o.map(t=>`waits ${t.kind} ${t.ref} ${t.key} since ${t.since}${t.picked?`, picked up ${t.picked}`:""}: ${t.next}`)}s(te,"waitLines");const k=A();k||(console.log("site-removed"),process.exit(0));const w=f.resolve(k.dir,"data",`.watch-cursor-${g}.json`),S=f.resolve(k.dir,"data","watcher.json"),j=[process.ppid,J(process.ppid)],T=s(()=>{j[1]??=J(j[0]),K(g,j)&&process.exit(0)},"orphaned");_(k.dir,O,g);try{c.mkdirSync(f.dirname(w),{recursive:!0}),c.writeFileSync(S,JSON.stringify({pid:process.pid,since:new Date().toISOString()}))}catch{}process.on("exit",()=>{try{const e=JSON.parse(c.readFileSync(S,"utf8"));e.pid===process.pid&&c.writeFileSync(S,JSON.stringify({...e,exited_at:new Date().toISOString()}))}catch{}});let p;try{p=JSON.parse(c.readFileSync(w,"utf8"))}catch{}for(p||(p=Object.fromEntries(Object.entries(v(k)).map(([e,o])=>[e,o.length])),c.mkdirSync(f.dirname(w),{recursive:!0}),c.writeFileSync(w,JSON.stringify(p)));;){await new Promise(r=>setTimeout(r,2e3));const e=A();if(e===void 0)continue;e===null&&(console.log("site-removed"),process.exit(0)),e.owner?.session&&e.owner.session!==g&&(console.log("handed-over "+JSON.stringify(e.owner)),process.exit(0)),T();const o=s(r=>Object.fromEntries(Object.entries(r).map(([i,$])=>[i,[...m(p.$usageHeld,i)||[],...$.slice(m(p,i)||0)]])),"pending"),t=s((r,i)=>i.state!=="paused"||!X(r),"eligible"),l=E();if(Object.values(o(v(e))).some(r=>r.some(i=>t(i,l)))){await new Promise(n=>setTimeout(n,2e3)),T();const r=v(e),i=E(),$=o(r);if(!Object.values($).some(n=>n.some(a=>t(a,i))))continue;const b=Object.create(null),N=[],x=[];for(const[n,a]of Object.entries($)){b[n]=a.filter(h=>!t(h,i));for(const h of a.filter(y=>t(y,i))){console.log(`event ${n} ${h}`);const y=await ee(e.dir,h);y&&console.log(y);try{const u=JSON.parse(h);V.includes(u.kind)&&typeof u.id=="string"&&N.push(u.id),u.kind==="hello"&&typeof u.id=="string"&&x.push(u.id)}catch{}}}let d=null;try{d=JSON.parse(c.readFileSync(f.resolve(e.dir,"board.json"),"utf8"))}catch(n){n.code!=="ENOENT"&&(d={})}if(d&&await C(e.dir,N).catch(n=>console.log(`working marks not written (${n.message})`)),d)for(const n of x)await Q(e.dir,n).catch(a=>console.log(`hello ${n} not answered (${a.message})`));if(d)for(const n of te(e.dir))console.log(n);if(d)for(const n of G(P(),D(d)))console.log(`rule ${n}`);if(d)for(const n of M(z(d)))console.log(n);d&&console.log(Z),i.state==="paused"&&console.log(`usage paused ${i.resets_at} ${i.window} ${i.used}%`);try{const n=d&&H(e.dir);if(n)for(const a of[...U(n,{listen:"listening"}),W()])a.ok||console.log(`link ${a.link} ${a.detail}`)}catch(n){console.log(`link registry could not check the links (${n.message})`)}const F=Object.fromEntries(Object.entries(r).map(([n,a])=>[n,a.length]));Object.values(b).some(n=>n.length)&&(F.$usageHeld=b),c.writeFileSync(w,JSON.stringify(F)),process.exit(0)}}
2
+ var U=Object.defineProperty;var t=(e,i)=>U(e,"name",{value:i,configurable:!0});import l from"node:fs";import h from"node:path";import W from"node:os";import{routeRecord as g}from"../hub/routes.mjs";import{readHubRules as C,rulesOf as K,ruleLines as Q}from"../hub/rules.mjs";import{boardAt as B,linksOf as M,hubLink as Y,stopPreviousWatcher as z}from"../hub/boards.mjs";import{parentOf as R,sessionGone as V}from"../hub/live.mjs";import{ackPing as X,cardName as Z,markWorking as ee,settingsLines as te,settingsOf as ne,WORKING_KINDS as se}from"../board/store.mjs";import{readUsageGate as I,heldUsageEvent as ie}from"../shared/usage-gate.mjs";const[v,$]=process.argv.slice(2);(!v||!$)&&(console.error("usage: wait-events.mjs <route> <session-id>"),process.exit(2));const re=h.join(W.homedir(),".claude","kickflip","manifest.json");function P(){try{return g(JSON.parse(l.readFileSync(re,"utf8")).sites,v)||null}catch{return}}t(P,"site");function S(e){const i=e.filter?new RegExp(e.filter):null,s=Object.create(null);for(const c of e.watch||["data/events.jsonl"]){let u=[];try{u=l.readFileSync(h.resolve(e.dir,c),"utf8").split(`
3
+ `).filter(Boolean)}catch{}s[c]=i?u.filter(m=>i.test(m)):u}return s}t(S,"matching");const oe=`quiet The owner doesn't read this session's terminal. Answer a prompt typed in it in full. A wake, a task notification or a builder's result is not one: write no text of your own, since board.mjs and this watcher print one line for each thing done. Talk and questions go on the board, never AskUserQuestion; only a failure the board can't show, such as the hub being down, gets one line here. Each message to the owner stands alone in its card's thread: name cards by label (#96), and a pointer such as "above" or "here" must make sense in that thread, never point into this session.`,ae=["main-pulled","settings","ask-done","reviewers-removed","reviewers-added","repo-changed","ping","hello"],ce=t(e=>{try{return JSON.parse(e).kind}catch{return null}},"kindOf"),j=t(e=>ae.includes(ce(e)),"recordOnly");function A(e){try{return JSON.parse(l.readFileSync(h.resolve(e.dir,"board.json"),"utf8"))}catch(i){return i.code==="ENOENT"?null:{}}}t(A,"boardOf");async function L(e,i){for(const s of i){let c;try{c=JSON.parse(s)}catch{continue}(c.kind==="ping"||c.kind==="hello")&&typeof c.id=="string"&&await X(e,c.id).catch(u=>console.log(`ping ${c.id} not answered (${u.message})`))}}t(L,"ackPings");const T={ask:t(e=>`new task ${e.id} received`,"ask"),"owner-answer":t(e=>`answer received to question ${e.data?.id}`,"owner-answer"),ping:t(e=>`ping ${e.id} from the hub answered`,"ping"),hello:t(e=>`ping ${e.id} from the hub answered`,"hello"),"overnight-triage":t(e=>`Overnight triage ${e.data?.date} asked: ${e.data?.cards?.length} cards wait on your answers`,"overnight-triage"),"pr-review":t(e=>`review asked on PR #${e.data?.pr}: the board was idle`,"pr-review"),"orchestrator-waits":t(e=>`waiting on you now: ${(e.data?.added||[]).join(", ")}`,"orchestrator-waits"),"review-answer":t(e=>`${e.data?.answer==="skip"?"skip":"post"} answered on the review of PR #${e.data?.pr}`,"review-answer")},D={"item-message":t((e,i)=>i.data?.intent==="build"?`Implement asked on ${e}: fold the message into its notes, then item set --state ready starts the build`:`message received from ${e}'s thread`,"item-message"),"card-merge":t(e=>`merge asked on ${e}`,"card-merge"),"card-done":t(e=>`${e} marked done`,"card-done"),"card-bump":t(e=>`${e} bumped`,"card-bump"),"ask-bump":t(e=>`${e} bumped`,"ask-bump"),"ask-edited":t(e=>`${e} edited`,"ask-edited"),"ask-done":t(e=>`${e} marked done`,"ask-done"),"ask-withdrawn":t(e=>`${e} deleted`,"ask-withdrawn"),"card-hold":t((e,i)=>`${e} ${i.data?.hold?"held":"resumed"}`,"card-hold"),"card-unblocked":t(e=>`${e} unblocked`,"card-unblocked"),"prototype-request":t(e=>`prototype asked on ${e}`,"prototype-request"),"reask-request":t(e=>`question asked again on ${e}`,"reask-request"),"builder-ask":t((e,i)=>`${i.data?.ask} from ${e}'s builder: ${i.data?.text}`,"builder-ask"),"owner-check-broken":t((e,i)=>`${e}'s owner-step check can't run: ${i.data?.error}`,"owner-check-broken"),"card-added":t(e=>`${e} added by an agent: link it and file it`,"card-added")};async function de(e,i){let s;try{s=JSON.parse(i)}catch{return null}if(typeof s?.kind!="string")return null;const c=typeof s.data?.key=="string"?s.data.key:s.kind.startsWith("ask-")&&typeof s.data?.id=="string"?`ask:${s.data.id}`:null,u=c&&await Z(e,c).catch(()=>c);return g(T,s.kind)?T[s.kind](s):u&&g(D,s.kind)?D[s.kind](u,s):u?`${s.kind} on ${u}`:`${s.kind} received`}t(de,"plainLine");function le(e){let i=[];try{i=JSON.parse(l.readFileSync(h.resolve(e,"data","orchestrator-waits.json"),"utf8")).waits||[]}catch{}return i.map(s=>`waits ${s.kind} ${s.ref} ${s.key} since ${s.since}${s.picked?`, picked up ${s.picked}`:""}: ${s.next}`)}t(le,"waitLines");const b=P();b||(console.log("site-removed"),process.exit(0));const w=h.resolve(b.dir,"data",`.watch-cursor-${$}.json`),N=h.resolve(b.dir,"data","watcher.json"),E=[process.ppid,R(process.ppid)],_=t(()=>{E[1]??=R(E[0]),V($,E)&&process.exit(0)},"orphaned");z(b.dir,v,$);try{l.mkdirSync(h.dirname(w),{recursive:!0}),l.writeFileSync(N,JSON.stringify({pid:process.pid,since:new Date().toISOString()}))}catch{}process.on("exit",()=>{try{const e=JSON.parse(l.readFileSync(N,"utf8"));e.pid===process.pid&&l.writeFileSync(N,JSON.stringify({...e,exited_at:new Date().toISOString()}))}catch{}});let d;try{d=JSON.parse(l.readFileSync(w,"utf8"))}catch{}for(d||(d=Object.fromEntries(Object.entries(S(b)).map(([e,i])=>[e,i.length])),l.mkdirSync(h.dirname(w),{recursive:!0}),l.writeFileSync(w,JSON.stringify(d)));;){await new Promise(n=>setTimeout(n,2e3));const e=P();if(e===void 0)continue;e===null&&(console.log("site-removed"),process.exit(0)),e.owner?.session&&e.owner.session!==$&&(console.log("handed-over "+JSON.stringify(e.owner)),process.exit(0)),_();const i=t(n=>Object.fromEntries(Object.entries(n).map(([o,r])=>[o,[...g(d.$quietHeld,o)||[],...g(d.$usageHeld,o)||[],...r.slice(g(d,o)||0)]])),"pending"),s=t((n,o)=>o.state!=="paused"||!ie(n),"eligible"),c=t((n,o)=>Object.values(n).some(r=>r.some(a=>s(a,o)&&!j(a))),"wakes"),u=I(),m=S(e);if(!c(i(m),u)){const n=Object.fromEntries(Object.entries(m).map(([r,a])=>[r,a.slice(g(d,r)||0).filter(j)])),o=Object.fromEntries(Object.entries(m).map(([r,a])=>[r,a.slice(g(d,r)||0).filter(p=>!j(p))]));if(Object.values(n).some(r=>r.length)){A(e)&&await L(e.dir,Object.values(n).flat());const r=t((a,p)=>Object.fromEntries(Object.keys(m).map(O=>[O,[...g(a,O)||[],...p[O]]])),"append");d={...Object.fromEntries(Object.entries(m).map(([a,p])=>[a,p.length])),$quietHeld:r(d.$quietHeld,n),$usageHeld:r(d.$usageHeld,o)},Object.values(d.$usageHeld).some(a=>a.length)||delete d.$usageHeld,l.writeFileSync(w,JSON.stringify(d))}continue}await new Promise(n=>setTimeout(n,2e3)),_();const J=S(e),k=I(),F=i(J);if(!c(F,k))continue;const y=Object.create(null),x=[],G=new Set(Object.values(d.$quietHeld||{}).flat()),H=[];for(const[n,o]of Object.entries(F)){y[n]=o.filter(r=>!s(r,k));for(const r of o.filter(a=>s(a,k))){G.has(r)||H.push(r),console.log(`event ${n} ${r}`);const a=await de(e.dir,r);a&&console.log(a);try{const p=JSON.parse(r);se.includes(p.kind)&&typeof p.id=="string"&&x.push(p.id)}catch{}}}const f=A(e);if(f&&await ee(e.dir,x).catch(n=>console.log(`working marks not written (${n.message})`)),f&&await L(e.dir,H),f)for(const n of le(e.dir))console.log(n);if(f)for(const n of Q(C(),K(f)))console.log(`rule ${n}`);if(f)for(const n of te(ne(f)))console.log(n);f&&console.log(oe),k.state==="paused"&&console.log(`usage paused ${k.resets_at} ${k.window} ${k.used}%`);try{const n=f&&B(e.dir);if(n)for(const o of[...M(n,{listen:"listening"}),Y()])o.ok||console.log(`link ${o.link} ${o.detail}`)}catch(n){console.log(`link registry could not check the links (${n.message})`)}const q=Object.fromEntries(Object.entries(J).map(([n,o])=>[n,o.length]));Object.values(y).some(n=>n.length)&&(q.$usageHeld=y),l.writeFileSync(w,JSON.stringify(q)),process.exit(0)}
@@ -0,0 +1,2 @@
1
+ var g=Object.defineProperty;var t=(e,n)=>g(e,"name",{value:n,configurable:!0});import a from"node:fs";import y from"node:path";import{spawn as v,execFileSync as h}from"node:child_process";import{claudeBin as w,inherited as _}from"../hub/sessions.mjs";function I(e){try{return y.resolve(e,h("git",["-C",e,"rev-parse","--git-common-dir"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim())}catch{return null}}t(I,"gitCommonDir");const A={claude:{bin:w,args:t(({prompt:e,model:n="opus"})=>["-p",e,"--permission-mode","auto","--model",n,"--output-format","stream-json","--verbose"],"args"),session:t(e=>{try{const n=JSON.parse(e);return n.type==="system"&&n.subtype==="init"?n.session_id??null:null}catch{return null}},"session")},codex:{bin:t(()=>process.env.KICKFLIP_CODEX||"codex","bin"),args:t(({prompt:e,cwd:n,site:c})=>["exec","--color","never","--cd",n,"--sandbox","workspace-write",...[c,I(n)].filter(Boolean).flatMap(u=>["--add-dir",u]),"-c","sandbox_workspace_write.network_access=true",e],"args"),session:t(e=>e.match(/^session id: (\S+)/)?.[1]??null,"session")}},O=15e3;function T(e,n,c,u){return new Promise(x=>{let o=!1;const l=t(i=>{o||(o=!0,clearInterval(f),clearTimeout(r),e.off("exit",p),x(i))},"finish"),s=t(()=>{const i=a.readFileSync(n,"utf8").slice(c);for(const m of i.split(`
2
+ `)){const S=u(m);if(S)return l(S)}},"scan"),f=setInterval(s,100),r=setTimeout(()=>l(null),O),p=t(()=>{s(),l(null)},"exited");e.once("exit",p)})}t(T,"sessionOf");function F({kind:e,model:n,cwd:c,site:u,prompt:x,log:o,bin:l}){const s=A[e];if(!s)throw new Error(`no agent of kind ${e}`);const f=l??s.bin();a.mkdirSync(y.dirname(o),{recursive:!0});const r=a.openSync(o,"a"),p=a.fstatSync(r).size,i=Object.fromEntries(Object.entries(process.env).filter(([m])=>!_(m)));return y.isAbsolute(f)&&(i.PATH=`${y.dirname(f)}:${i.PATH||""}`),new Promise((m,S)=>{const d=v(f,s.args({prompt:x,model:n,cwd:c,site:u}),{cwd:c,env:i,detached:!0,stdio:["ignore",r,r]});d.once("spawn",async()=>{a.closeSync(r);const b=await T(d,o,p,s.session);d.unref(),m({pid:d.pid,sessionId:b,log:o})}),d.once("error",b=>{a.closeSync(r),S(b)})})}t(F,"launchAgent");export{F as launchAgent};