coxpit 2.9.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -71,6 +71,7 @@ Your keys and login never touch coxpit's config or database.
71
71
  | `COXPIT_AGENT_REAL` | — | `1` = real agent CLI by default (credits!) |
72
72
  | `COXPIT_AGENT_BIN` | `claude` | agent command |
73
73
  | `COXPIT_AGENT_PERM` | `acceptEdits` | headless permission mode passed to the agent |
74
+ | `COXPIT_WEBHOOK_URL` | — | POSTs `{event:"run.settled",run:{...}}` when a run finishes — wire it to Telegram, Slack, anything |
74
75
 
75
76
  Running on the open internet? Put it behind your own front door (Tailscale, Cloudflare Access, a reverse proxy with TLS) and keep basic auth on — it exposes shells.
76
77
 
@@ -88,7 +89,7 @@ One daemon, one SQLite file, zero external services. Machines are reached over S
88
89
 
89
90
  ## Status
90
91
 
91
- `v2.0` — agent fleet (P1), compare/review + terminal (P2), and Design Mode (P3) are implemented and tested. Roadmap: richer review tooling, more agent providers, packaging (Docker/npm).
92
+ `v3.0` — fleet, compare/merge, terminal, Design Mode, run destinations (merge · export · PR), swarm (plan fan-out + integrate with conflict-resolving agents), AI review, and sessions (work/ask + notifications) — all shipped and e2e-tested. Roadmap: ROADMAP.md.
92
93
 
93
94
  ## License
94
95
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coxpit",
3
- "version": "2.9.0",
3
+ "version": "3.0.0",
4
4
  "description": "Self-hosted cockpit for running a fleet of AI coding agents across your own machines — parallel worktree runs, live board, compare & merge, web terminal, design capture.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/board.ts CHANGED
@@ -292,6 +292,7 @@ export const BOARD_HTML = /* html */ `<!doctype html>
292
292
  <header>
293
293
  <div class="brand"><span class="mark">coxpit</span><span class="sub">fleet console</span></div>
294
294
  <div class="ws"><span class="dot" id="wsdot"></span><span id="wstext">connecting</span></div>
295
+ <button class="btn-ghost sm" id="bell" title="notify when a run settles">🔕</button>
295
296
  <div class="machines" id="machines"></div>
296
297
  </header>
297
298
  <div class="layout">
@@ -382,14 +383,19 @@ export const BOARD_HTML = /* html */ `<!doctype html>
382
383
  </div>
383
384
  </div>
384
385
  <div class="modal-f" id="steerRow" style="border-top:1px solid var(--line)">
385
- <input id="steerInput" placeholder="Send follow-up instructions — continues in the same session &amp; worktree…" style="flex:1" />
386
- <button class="btn sm" id="steerSend">Steer</button>
386
+ <div class="seg" style="flex:0 0 132px" id="steerModeSeg">
387
+ <button type="button" class="seg-opt on" data-mode="work">Work</button>
388
+ <button type="button" class="seg-opt" data-mode="ask">Ask</button>
389
+ </div>
390
+ <input id="steerInput" placeholder="Next instruction — same session &amp; worktree…" style="flex:1" />
391
+ <button class="btn sm" id="steerSend">Send</button>
387
392
  </div>
388
393
  <div class="modal-f">
389
394
  <button class="btn-ghost sm" id="mTerm">Terminal</button>
390
395
  <button class="btn-ghost sm" id="mRefreshDiff">Refresh diff</button>
391
396
  <button class="btn-ghost sm" id="mCompare">Compare runs</button>
392
397
  <button class="btn-ghost sm" id="mExport">Export files…</button>
398
+ <button class="btn-ghost sm" id="mSync">Sync base</button>
393
399
  <span class="spacer"></span>
394
400
  <button class="btn-danger sm" id="mStop">Stop</button>
395
401
  <button class="btn-ghost sm" id="mCleanup">Cleanup</button>
@@ -597,6 +603,8 @@ function humanize(e){
597
603
  const kind = e.kind, payload = e.payload;
598
604
  if (kind === 'rate_limit_event') return null;
599
605
  if (kind === 'steer') return { k:'steer', t:'→ '+payload };
606
+ if (kind === 'ask') return { k:'ask', t:'? '+payload };
607
+ if (kind === 'sync') return { k:'sync', t:payload };
600
608
  if (kind === 'export'){ try{ const o=JSON.parse(payload); return { k:'export', t:o.copied+' file(s) → '+o.dest }; }catch{ return { k:'export', t:payload }; } }
601
609
  if (kind === 'pr') return { k:'pr', t:payload };
602
610
  if (kind === 'stderr') return { k:'stderr', t:payload };
@@ -786,6 +794,33 @@ $('repos').addEventListener('click', async (e)=>{
786
794
  else toast('remove: '+(j.detail||res.status), 'error');
787
795
  });
788
796
 
797
+ /* ── 완료 알림(브라우저) — 벨 토글, run 정착 시 통지 ── */
798
+ let notifyOn = false;
799
+ try { notifyOn = localStorage.getItem('coxpit.notify') === '1' && Notification.permission === 'granted'; } catch {}
800
+ function paintBell(){ $('bell').textContent = notifyOn ? '🔔' : '🔕'; }
801
+ $('bell').addEventListener('click', async ()=>{
802
+ if (!('Notification' in window)){ toast('this browser has no notification support', 'error'); return; }
803
+ if (!notifyOn){
804
+ const perm = await Notification.requestPermission();
805
+ if (perm !== 'granted'){ toast('notification permission denied', 'error'); return; }
806
+ notifyOn = true;
807
+ } else notifyOn = false;
808
+ try { localStorage.setItem('coxpit.notify', notifyOn ? '1' : '0'); } catch {}
809
+ paintBell();
810
+ toast(notifyOn ? 'will notify when runs settle' : 'notifications off', 'ok');
811
+ });
812
+ paintBell();
813
+ function notifySettleUI(ev){
814
+ if (!notifyOn) return;
815
+ const t = tasks.get(ev.taskId ?? (runs.get(ev.runId)||{}).taskId);
816
+ try {
817
+ new Notification('coxpit · r'+ev.runId+' '+ev.status, {
818
+ body: (t ? t.title+' — ' : '') + (ev.filesChanged??0)+' file(s) changed',
819
+ tag: 'coxpit-r'+ev.runId,
820
+ });
821
+ } catch {}
822
+ }
823
+
789
824
  function connectWS(){
790
825
  const proto = location.protocol==='https:'?'wss':'ws';
791
826
  const ws = new WebSocket(proto+'://'+location.host+'/ws');
@@ -801,6 +836,7 @@ function connectWS(){
801
836
  render(); flash(ev.runId ?? ev.id); paintModal();
802
837
  if (openRunId===(ev.runId??ev.id) && ['done','failed','error','stopped'].includes(ev.status)) loadDiff();
803
838
  if (cmpTaskId!=null && ['done','failed','error','stopped','merged'].includes(ev.status)) paintCompare();
839
+ if (['done','failed','error','stopped'].includes(ev.status)) notifySettleUI(ev);
804
840
  } else if (ev.type==='event'){
805
841
  const r = runs.get(ev.runId); if(!r){ hydrate(); return; }
806
842
  r.events = r.events||[]; r.events.push({ kind:ev.kind, payload:ev.payload });
@@ -913,14 +949,34 @@ $('expOk').addEventListener('click', doExport);
913
949
  $('expDest').addEventListener('keydown',(e)=>{ if(e.key==='Enter'){ e.preventDefault(); doExport(); } });
914
950
  $('expCancel').addEventListener('click', ()=>$('expOverlay').classList.remove('open'));
915
951
  $('expOverlay').addEventListener('click',(e)=>{ if(e.target===$('expOverlay')) $('expOverlay').classList.remove('open'); });
952
+ let steerMode = 'work';
953
+ document.querySelectorAll('#steerModeSeg .seg-opt').forEach(b=>{
954
+ b.addEventListener('click', ()=>{
955
+ steerMode = b.dataset.mode;
956
+ document.querySelectorAll('#steerModeSeg .seg-opt').forEach(x=>x.classList.toggle('on', x===b));
957
+ $('steerInput').placeholder = steerMode==='ask'
958
+ ? 'Ask the session — status, decisions, anything (no file changes)…'
959
+ : 'Next instruction — same session & worktree…';
960
+ });
961
+ });
916
962
  async function sendSteer(){
917
963
  if (openRunId==null) return;
918
964
  const msg = $('steerInput').value.trim(); if(!msg) return;
919
965
  const res = await fetch('/api/runs/'+openRunId+'/steer',{method:'POST',
920
- headers:{'content-type':'application/json'}, body:JSON.stringify({message:msg})});
921
- if (res.ok){ $('steerInput').value=''; toast('steering — the agent resumes in its worktree', 'ok'); }
966
+ headers:{'content-type':'application/json'}, body:JSON.stringify({message:msg, mode:steerMode})});
967
+ if (res.ok){
968
+ $('steerInput').value='';
969
+ toast(steerMode==='ask' ? 'asking — answer lands in the timeline' : 'working — same session & worktree', 'ok');
970
+ }
922
971
  else { const j = await res.json().catch(()=>({})); toast('steer: '+(j.detail||res.status), 'error'); }
923
972
  }
973
+ $('mSync').addEventListener('click', async ()=>{
974
+ if (openRunId==null) return;
975
+ const res = await fetch('/api/runs/'+openRunId+'/sync',{method:'POST'});
976
+ const j = await res.json().catch(()=>({}));
977
+ if (res.ok){ toast('base merged into session worktree', 'ok'); loadDiff(); }
978
+ else toast('sync: '+(j.detail||res.status), 'error');
979
+ });
924
980
  $('steerSend').addEventListener('click', sendSteer);
925
981
  $('steerInput').addEventListener('keydown',(e)=>{ if(e.key==='Enter') sendSteer(); });
926
982
  $('mStop').addEventListener('click', async ()=>{
package/src/config.ts CHANGED
@@ -21,6 +21,8 @@ export const config = {
21
21
  dbPath: process.env.COXPIT_DB ?? './coxpit.db',
22
22
  // 원격 머신 SSH 개인키 경로(선택). 없으면 ssh 기본 키/에이전트 사용.
23
23
  sshKey: process.env.COXPIT_SSH_KEY ?? '',
24
+ // run 정착 시 POST 할 웹훅(선택) — 텔레그램 브릿지 등 사용자 연결용.
25
+ webhookUrl: process.env.COXPIT_WEBHOOK_URL ?? '',
24
26
  agent: {
25
27
  // 기본 드라이런(모의 에이전트). 실제 CLI 실행은 켤 때만(크레딧 소모).
26
28
  real: process.env.COXPIT_AGENT_REAL === '1',
@@ -186,19 +186,35 @@ async function runAgentChild(runId: number, machine: MachineTarget, wtPath: stri
186
186
  const filesChanged = stat.ok ? parseInt(stat.stdout.trim(), 10) || 0 : 0;
187
187
 
188
188
  const wasStopped = stoppedRuns.delete(runId);
189
- await setRun(runId, {
190
- status: wasStopped ? 'stopped' : code === 0 ? 'done' : 'failed',
191
- endedAt: new Date(),
192
- filesChanged,
193
- exitSummary: wasStopped ? 'stopped by user' : lastResult ? lastResult.slice(0, 500) : `exit ${code}`,
194
- });
189
+ const status = wasStopped ? 'stopped' : code === 0 ? 'done' : 'failed';
190
+ const exitSummary = wasStopped ? 'stopped by user' : lastResult ? lastResult.slice(0, 500) : `exit ${code}`;
191
+ await setRun(runId, { status, endedAt: new Date(), filesChanged, exitSummary });
192
+ void notifySettle(runId, status, filesChanged, exitSummary);
193
+ }
194
+
195
+ /** run 정착 웹훅(선택) — COXPIT_WEBHOOK_URL 로 JSON POST. 실패는 무해. */
196
+ async function notifySettle(runId: number, status: string, filesChanged: number, exitSummary: string): Promise<void> {
197
+ if (!config.webhookUrl) return;
198
+ try {
199
+ const rr = await db.select().from(agentRuns).where(eq(agentRuns.id, runId)).limit(1);
200
+ const tr = rr[0] ? await db.select().from(tasks).where(eq(tasks.id, rr[0].taskId)).limit(1) : [];
201
+ await fetch(config.webhookUrl, {
202
+ method: 'POST',
203
+ headers: { 'content-type': 'application/json' },
204
+ body: JSON.stringify({
205
+ event: 'run.settled',
206
+ run: { id: runId, status, filesChanged, exitSummary: exitSummary.slice(0, 300), task: tr[0]?.title ?? '' },
207
+ }),
208
+ signal: AbortSignal.timeout(8000),
209
+ });
210
+ } catch { /* 웹훅 실패는 조용히 */ }
195
211
  }
196
212
 
197
213
  /**
198
214
  * 후속 지시(steer) — 정착한 run 의 세션을 --resume 으로 이어 같은 worktree 에서 계속.
199
215
  * fire-and-forget. 진행 중 run 은 거부(개입은 터미널로).
200
216
  */
201
- export async function steerRun(runId: number, message: string): Promise<{ ok: boolean; detail: string }> {
217
+ export async function steerRun(runId: number, message: string, mode: 'work' | 'ask' = 'work'): Promise<{ ok: boolean; detail: string }> {
202
218
  const ctx = await loadContext(runId);
203
219
  const rr = await db.select().from(agentRuns).where(eq(agentRuns.id, runId)).limit(1);
204
220
  const run = rr[0];
@@ -213,11 +229,16 @@ export async function steerRun(runId: number, message: string): Promise<{ ok: bo
213
229
  if (!exists.stdout.includes('yes')) return { ok: false, detail: 'worktree missing on machine' };
214
230
 
215
231
  await setRun(runId, { status: 'running', endedAt: null });
216
- await recordEvent(runId, 'steer', message.slice(0, 2000));
232
+ await recordEvent(runId, mode === 'ask' ? 'ask' : 'steer', message.slice(0, 2000));
233
+
234
+ // Ask 모드 — 세션에 질문만: 파일 수정 없이 답변만 하도록 래핑
235
+ const finalMessage = mode === 'ask'
236
+ ? `Question about your work in this session (do NOT modify any files, do NOT run write commands — answer concisely):\n${message}`
237
+ : message;
217
238
 
218
239
  const isRemote = ctx.machine.kind !== 'local' && ctx.machine.address !== '';
219
240
  const pidPrefix = isRemote ? `printf '%s' "$$" > .coxpit-agent.pid && ` : '';
220
- const resume = `${config.agent.bin} -p --resume ${shq(run.sessionId)} ${shq(message)}` +
241
+ const resume = `${config.agent.bin} -p --resume ${shq(run.sessionId)} ${shq(finalMessage)}` +
221
242
  ` --output-format stream-json --verbose --permission-mode ${config.agent.perm}`;
222
243
  const cmd = `cd ${shq(wt)} && ${pidPrefix}{ ${resume}; }`;
223
244
  void runAgentChild(runId, ctx.machine, wt, cmd);
@@ -285,6 +306,31 @@ export async function getRunDiff(runId: number): Promise<{ ok: boolean; diff: st
285
306
  return { ok: true, stat: stat.trim(), diff: diff.slice(0, 200_000) };
286
307
  }
287
308
 
309
+ /**
310
+ * base 동기화 — 오래 사는 세션의 worktree 에 base 브랜치 최신을 머지한다.
311
+ * 충돌 시 자동 abort — 그땐 steer 로 에이전트에게 머지를 맡기라고 안내.
312
+ */
313
+ export async function syncRun(runId: number): Promise<{ ok: boolean; detail: string; conflict?: boolean }> {
314
+ const ctx = await loadContext(runId);
315
+ const rr = await db.select().from(agentRuns).where(eq(agentRuns.id, runId)).limit(1);
316
+ const run = rr[0];
317
+ if (!ctx || !run || !run.worktreePath) return { ok: false, detail: 'no worktree' };
318
+ if (liveChildren.has(runId)) return { ok: false, detail: 'still running — wait for it to settle' };
319
+ const wt = shq(run.worktreePath);
320
+ const ident = `-c user.name='coxpit' -c user.email='coxpit@local'`;
321
+ // 미커밋 변경 먼저 커밋(머지 가능 상태로)
322
+ const c1 = await runShellOn(ctx.machine,
323
+ `cd ${wt} && git add -A && (git diff --cached --quiet || git ${ident} -c commit.gpgsign=false commit -m ${shq(`coxpit r${runId}: checkpoint before base sync`)})`, 20000);
324
+ if (!c1.ok) return { ok: false, detail: 'checkpoint commit failed' };
325
+ const mg = await runShellOn(ctx.machine,
326
+ `cd ${wt} && git ${ident} -c commit.gpgsign=false merge --no-edit ${shq(ctx.baseBranch)} 2>&1 || (git merge --abort 2>/dev/null; echo COXPIT_SYNC_CONFLICT)`, 30000);
327
+ if (mg.stdout.includes('COXPIT_SYNC_CONFLICT')) {
328
+ return { ok: false, conflict: true, detail: `conflict with ${ctx.baseBranch} — steer the agent: "merge ${ctx.baseBranch} and resolve conflicts"` };
329
+ }
330
+ await recordEvent(runId, 'sync', `merged ${ctx.baseBranch} into session worktree`);
331
+ return { ok: true, detail: mg.stdout.trim().split('\n').slice(-1)[0] ?? 'synced' };
332
+ }
333
+
288
334
  /**
289
335
  * 승자 run 머지 — worktree 미커밋 변경을 자동 커밋 후 run 브랜치를
290
336
  * repo 기본 브랜치에 merge. 본 repo 가 기본 브랜치+클린일 때만, 충돌 시 abort.
package/src/server.ts CHANGED
@@ -12,7 +12,7 @@ import { db } from './db';
12
12
  import { machines, repos, tasks, agentRuns, agentEvents, designCaptures } from './db/schema';
13
13
  import { BOOKMARKLET_JS } from './design';
14
14
  import { runShellOn, shq } from './exec';
15
- import { launchRun, cleanupRun, stopRun, getRunDiff, mergeRun, getRunTermInfo, steerRun, exportRun, prRun, integrateRuns, planFanout, reviewTask } from './orchestrator';
15
+ import { launchRun, cleanupRun, stopRun, getRunDiff, mergeRun, getRunTermInfo, steerRun, exportRun, prRun, integrateRuns, planFanout, reviewTask, syncRun } from './orchestrator';
16
16
  import { openTerm } from './term';
17
17
  import { addSink, removeSink, broadcast } from './hub';
18
18
  import { BOARD_HTML } from './board';
@@ -32,7 +32,7 @@ export async function buildServer(): Promise<FastifyInstance> {
32
32
  app.addHook('onRequest', authGate);
33
33
 
34
34
  // 무인증 헬스(외부 감시용)
35
- app.get('/api/health', async () => ({ ok: true, name: 'coxpit', version: '2.9.0' }));
35
+ app.get('/api/health', async () => ({ ok: true, name: 'coxpit', version: '3.0.0' }));
36
36
 
37
37
  // 플릿 보드(단일 페이지). 인증 게이트 적용됨.
38
38
  app.get('/', async (_req, reply) => reply.type('text/html').send(BOARD_HTML));
@@ -402,16 +402,26 @@ export async function buildServer(): Promise<FastifyInstance> {
402
402
  // 후속 지시(steer) — 정착한 run 을 같은 세션(--resume)·같은 worktree 로 계속.
403
403
  app.post('/api/runs/:id/steer', async (req, reply) => {
404
404
  const id = Number((req.params as { id: string }).id);
405
- const b = (req.body ?? {}) as { message?: string };
405
+ const b = (req.body ?? {}) as { message?: string; mode?: string };
406
406
  const message = (b.message ?? '').trim();
407
407
  if (!message) return reply.code(400).send({ error: 'message required' });
408
408
  const rr = await db.select().from(agentRuns).where(eq(agentRuns.id, id)).limit(1);
409
409
  if (!rr[0]) return reply.code(404).send({ error: 'not found' });
410
- const res = await steerRun(id, message);
410
+ const res = await steerRun(id, message, b.mode === 'ask' ? 'ask' : 'work');
411
411
  if (!res.ok) return reply.code(409).send(res);
412
412
  return reply.code(202).send(res);
413
413
  });
414
414
 
415
+ // base 동기화 — 오래 사는 세션 worktree 에 base 최신 머지.
416
+ app.post('/api/runs/:id/sync', async (req, reply) => {
417
+ const id = Number((req.params as { id: string }).id);
418
+ const rr = await db.select().from(agentRuns).where(eq(agentRuns.id, id)).limit(1);
419
+ if (!rr[0]) return reply.code(404).send({ error: 'not found' });
420
+ const res = await syncRun(id);
421
+ if (!res.ok) return reply.code(409).send(res);
422
+ return res;
423
+ });
424
+
415
425
  // Plan fan-out — 목표 하나 → 플래너가 태스크 분해 → 전부 자동 발사.
416
426
  // (real 플래너는 repo 를 읽고 계획하느라 1~3분 걸릴 수 있음 — 클라이언트는 대기)
417
427
  app.post('/api/plan', async (req, reply) => {
@@ -481,7 +491,7 @@ export async function buildServer(): Promise<FastifyInstance> {
481
491
  // 라이브 스트림 좌석 — 오케스트레이터가 run/event 를 여기로 broadcast.
482
492
  app.get('/ws', { websocket: true }, (socket) => {
483
493
  addSink(socket);
484
- socket.send(JSON.stringify({ type: 'hello', name: 'coxpit-fleet', version: '2.9.0' }));
494
+ socket.send(JSON.stringify({ type: 'hello', name: 'coxpit-fleet', version: '3.0.0' }));
485
495
  socket.on('close', () => removeSink(socket));
486
496
  });
487
497