ftown-bridge 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/attention-cli.d.ts +32 -0
  2. package/dist/attention-cli.js +310 -0
  3. package/dist/attention-cli.js.map +1 -0
  4. package/dist/attention-events.d.ts +2 -1
  5. package/dist/attention-events.js.map +1 -1
  6. package/dist/attention-store.d.ts +6 -3
  7. package/dist/attention-store.js +60 -2
  8. package/dist/attention-store.js.map +1 -1
  9. package/dist/brief-cli.d.ts +10 -0
  10. package/dist/brief-cli.js +163 -0
  11. package/dist/brief-cli.js.map +1 -0
  12. package/dist/command-rpc.js +18 -15
  13. package/dist/command-rpc.js.map +1 -1
  14. package/dist/coordination/attention-routing.d.ts +37 -0
  15. package/dist/coordination/attention-routing.js +154 -0
  16. package/dist/coordination/attention-routing.js.map +1 -0
  17. package/dist/coordination/contract-b.d.ts +206 -0
  18. package/dist/coordination/contract-b.js +58 -0
  19. package/dist/coordination/contract-b.js.map +1 -0
  20. package/dist/coordination/format.js +13 -0
  21. package/dist/coordination/format.js.map +1 -1
  22. package/dist/coordination/routes-brief.d.ts +10 -0
  23. package/dist/coordination/routes-brief.js +149 -0
  24. package/dist/coordination/routes-brief.js.map +1 -0
  25. package/dist/coordination/routes-worktrees.d.ts +29 -0
  26. package/dist/coordination/routes-worktrees.js +138 -0
  27. package/dist/coordination/routes-worktrees.js.map +1 -0
  28. package/dist/coordination/wiring.d.ts +11 -2
  29. package/dist/coordination/wiring.js +31 -9
  30. package/dist/coordination/wiring.js.map +1 -1
  31. package/dist/coordination-cli.js +6 -0
  32. package/dist/coordination-cli.js.map +1 -1
  33. package/dist/create-ftown-session.d.ts +8 -1
  34. package/dist/create-ftown-session.js +164 -104
  35. package/dist/create-ftown-session.js.map +1 -1
  36. package/dist/ftown-cli.js +11 -2
  37. package/dist/ftown-cli.js.map +1 -1
  38. package/dist/index.js +4 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/local-api-server.d.ts +24 -0
  41. package/dist/local-api-server.js +462 -31
  42. package/dist/local-api-server.js.map +1 -1
  43. package/dist/mail-delivery.d.ts +18 -4
  44. package/dist/mail-delivery.js +50 -8
  45. package/dist/mail-delivery.js.map +1 -1
  46. package/dist/security/bridge/permissions.js +34 -4
  47. package/dist/security/bridge/permissions.js.map +1 -1
  48. package/dist/session-controller.d.ts +17 -1
  49. package/dist/session-controller.js +93 -2
  50. package/dist/session-controller.js.map +1 -1
  51. package/dist/sessions-commands.js +65 -5
  52. package/dist/sessions-commands.js.map +1 -1
  53. package/dist/types.d.ts +5 -0
  54. package/dist/worktrees-cli.d.ts +39 -0
  55. package/dist/worktrees-cli.js +168 -0
  56. package/dist/worktrees-cli.js.map +1 -0
  57. package/dist/worktrees.d.ts +16 -0
  58. package/dist/worktrees.js +292 -0
  59. package/dist/worktrees.js.map +1 -0
  60. package/hooks/ftown-antigravity-hook.sh +12 -6
  61. package/package.json +2 -2
  62. package/skills/ftown/SKILL.md +46 -5
  63. package/skills/ftown/references/orchestrator.md +26 -27
  64. package/skills/ftown/references/sessions.md +91 -8
@@ -20,7 +20,12 @@ import { removeFtownSession } from './remove-ftown-session.js';
20
20
  import { collectSessionUsage } from './usage-collector.js';
21
21
  import { toWireSession } from './session-wire.js';
22
22
  import { CardValidationError } from './coordination/contract.js';
23
+ import { PARENT_UNAVAILABLE_NOTE, RouteError, WorktreeError, } from './coordination/contract-b.js';
24
+ import { decideRoute, deliverAttentionAnswer, formatParentQuestionMail, markArchivedWorktreeRetained, } from './coordination/attention-routing.js';
25
+ import { handleBriefRoutes } from './coordination/routes-brief.js';
26
+ import { createWorktreeRoutes } from './coordination/routes-worktrees.js';
23
27
  import { createCoordination, rootOf } from './coordination/wiring.js';
28
+ import { GitWorktrees } from './worktrees.js';
24
29
  function jsonResponse(res, status, data) {
25
30
  res.writeHead(status, { 'Content-Type': 'application/json' });
26
31
  res.end(JSON.stringify(data));
@@ -254,8 +259,10 @@ export class LocalApiServer extends EventEmitter {
254
259
  });
255
260
  await this.security.revalidate(message.principal);
256
261
  void this.handleApiRoute(request, response, new URL(route.path, 'http://localhost').pathname, new URL(route.path, 'http://localhost')).catch(error => {
257
- if (error instanceof BadRequestError)
262
+ if (error instanceof BadRequestError || error instanceof WorktreeError)
258
263
  jsonResponse(response, 400, { error: error.message });
264
+ else if (error instanceof RouteError)
265
+ jsonResponse(response, error.status, { error: error.message });
259
266
  else if (error instanceof AttentionError)
260
267
  jsonResponse(response, error.status, { error: error.message, code: error.code });
261
268
  else
@@ -269,10 +276,32 @@ export class LocalApiServer extends EventEmitter {
269
276
  coordination = null;
270
277
  defaultCoordination = null;
271
278
  mailStore = null;
279
+ attentionPushHandler;
280
+ /** In-flight parent-routed creates. Pushes are held, then dropped only for that item id. */
281
+ parentPushAttempt = 0;
282
+ parentPushAttempts = new Map();
283
+ heldAttentionPushes = [];
272
284
  recoveryEpoch = 0;
273
285
  recoveryStartedAt = -1;
274
286
  recoveryStopped = false;
275
287
  runnerReadyListener = null;
288
+ worktreeRoutes = createWorktreeRoutes({
289
+ listLive: async () => (this.store ? this.store.listSessions() : []),
290
+ listArchived: async () => this.store
291
+ ? (await this.store.listArchived()).map((record) => {
292
+ const sanitized = { ...record };
293
+ delete sanitized.env;
294
+ delete sanitized.previewSource;
295
+ return sanitized;
296
+ })
297
+ : [],
298
+ worktrees: new GitWorktrees(),
299
+ markRetained: async (sessionId, reason) => {
300
+ if (!this.store)
301
+ return;
302
+ await markArchivedWorktreeRetained((id) => this.store.sessionDir(id), sessionId, reason);
303
+ },
304
+ });
276
305
  setBrowserAccess(access) {
277
306
  this.browserAccess = access;
278
307
  }
@@ -282,6 +311,306 @@ export class LocalApiServer extends EventEmitter {
282
311
  setAttentionStore(store) {
283
312
  this.attention = store;
284
313
  this.defaultCoordination = null;
314
+ // onNotification is a private constructor parameter. It is still an own
315
+ // instance property at runtime; the cast is the only way to wrap it.
316
+ const internal = store;
317
+ const original = internal.onNotification;
318
+ this.attentionPushHandler = original;
319
+ if (original) {
320
+ internal.onNotification = (sessionId, notice) => {
321
+ const attempts = this.parentPushAttempts.get(sessionId);
322
+ if (attempts && attempts.size > 0) {
323
+ this.heldAttentionPushes.push({
324
+ sessionId,
325
+ notice,
326
+ owners: new Set(attempts),
327
+ dropped: false,
328
+ });
329
+ return;
330
+ }
331
+ original(sessionId, notice);
332
+ };
333
+ }
334
+ }
335
+ /** Dashboard notice + push for an item that is reaching the human now. */
336
+ publishHumanAttention(sessionId, item) {
337
+ if (item.type === 'ask_user' || item.prompt?.channel === 'hook') {
338
+ this.emit('event', {
339
+ sessionId,
340
+ eventName: 'PreToolUse',
341
+ source: 'api',
342
+ data: {
343
+ hook_event_name: 'PreToolUse',
344
+ attentionId: item.id,
345
+ attentionSequence: item.sequence,
346
+ attentionCreatedAt: item.createdAt,
347
+ ...(item.prompt ? { attentionPrompt: item.prompt } : {}),
348
+ },
349
+ });
350
+ }
351
+ else {
352
+ this.emit('event', {
353
+ sessionId,
354
+ eventName: 'Notification',
355
+ source: 'api',
356
+ data: {
357
+ notification_type: 'agent_needs_input',
358
+ title: item.title,
359
+ message: item.message,
360
+ notification_id: item.id,
361
+ attentionId: item.id,
362
+ attentionSequence: item.sequence,
363
+ attentionCreatedAt: item.createdAt,
364
+ ...(item.prompt ? { attentionPrompt: item.prompt } : {}),
365
+ },
366
+ });
367
+ }
368
+ try {
369
+ this.attentionPushHandler?.(sessionId, {
370
+ kind: 'question',
371
+ eventKey: `question:${item.id}`,
372
+ title: item.title,
373
+ message: item.message,
374
+ occurredAt: item.escalatedAt ?? item.createdAt,
375
+ });
376
+ }
377
+ catch {
378
+ // Optional push delivery cannot fail escalation.
379
+ }
380
+ }
381
+ readCallerSessionId(req) {
382
+ const callerHeader = req.headers['x-ftown-session-id'];
383
+ return typeof callerHeader === 'string' && callerHeader.trim()
384
+ ? callerHeader.trim()
385
+ : undefined;
386
+ }
387
+ readAttentionTarget(body) {
388
+ if (!Object.prototype.hasOwnProperty.call(body, 'to'))
389
+ return undefined;
390
+ if (body.to === 'human')
391
+ return 'human';
392
+ throw new BadRequestError("Invalid attention target");
393
+ }
394
+ async resolveAttentionRouting(child, to) {
395
+ if (!this.store || !child.parentSessionId) {
396
+ return { route: 'human', parent: null };
397
+ }
398
+ const parent = await this.store.loadSession(child.parentSessionId);
399
+ const parentRunning = !!parent &&
400
+ (typeof this.runner?.isRunning === 'function'
401
+ ? this.runner.isRunning(parent.id)
402
+ : parent.status === 'running');
403
+ const route = decideRoute(child, parent, parentRunning, to);
404
+ return { route, parent };
405
+ }
406
+ /** Hold pushes for this session until the created item id is known. */
407
+ beginParentPushHold(sessionId) {
408
+ const attempt = ++this.parentPushAttempt;
409
+ let attempts = this.parentPushAttempts.get(sessionId);
410
+ if (!attempts) {
411
+ attempts = new Set();
412
+ this.parentPushAttempts.set(sessionId, attempts);
413
+ }
414
+ attempts.add(attempt);
415
+ return attempt;
416
+ }
417
+ /** Drop only `question:<suppressItemId>`. Every other held notice is delivered. */
418
+ finishParentPushHold(sessionId, attempt, suppressItemId) {
419
+ const attempts = this.parentPushAttempts.get(sessionId);
420
+ attempts?.delete(attempt);
421
+ if (attempts && attempts.size === 0)
422
+ this.parentPushAttempts.delete(sessionId);
423
+ const suppressKey = suppressItemId ? `question:${suppressItemId}` : undefined;
424
+ for (let index = this.heldAttentionPushes.length - 1; index >= 0; index--) {
425
+ const held = this.heldAttentionPushes[index];
426
+ if (!held.owners.has(attempt))
427
+ continue;
428
+ held.owners.delete(attempt);
429
+ if (suppressKey && held.notice.eventKey === suppressKey)
430
+ held.dropped = true;
431
+ if (held.owners.size === 0) {
432
+ this.heldAttentionPushes.splice(index, 1);
433
+ if (!held.dropped) {
434
+ try {
435
+ this.attentionPushHandler?.(held.sessionId, held.notice);
436
+ }
437
+ catch { /* Optional push delivery cannot fail the request. */ }
438
+ }
439
+ }
440
+ }
441
+ }
442
+ /** Apply a parent route only when the item was just created. Repeats keep their stored route. */
443
+ async applyParentRoute(session, item, created, route, parent) {
444
+ if (created && route === 'parent' && parent && this.attention) {
445
+ const routed = await this.attention.setRoute(session.id, item.id, {
446
+ route: 'parent',
447
+ routedTo: parent.id,
448
+ });
449
+ if (!routed)
450
+ return { item, skipNotice: false };
451
+ const fallback = await this.sendParentQuestionMail(session, parent, routed);
452
+ // The create push is the parent's to swallow. A mail failure publishes its own.
453
+ return { item: fallback ?? routed, skipNotice: true, suppressPushId: item.id };
454
+ }
455
+ if (!created && item.route === 'parent')
456
+ return { item, skipNotice: true };
457
+ return { item, skipNotice: false };
458
+ }
459
+ /** Mail the parent. On failure, route the item to the human and publish now. Returns that item. */
460
+ async sendParentQuestionMail(child, parent, item) {
461
+ let failed = false;
462
+ try {
463
+ const accepted = await this.acceptSessionMail(parent, {
464
+ from: child.id,
465
+ fromName: child.name,
466
+ type: 'escalation',
467
+ threadId: item.id,
468
+ body: formatParentQuestionMail(child, item),
469
+ });
470
+ if (!accepted.ok) {
471
+ console.error('[Bridge] Failed to mail parent question:', accepted.error);
472
+ failed = true;
473
+ }
474
+ }
475
+ catch (err) {
476
+ console.error('[Bridge] Failed to mail parent question:', err instanceof Error ? err.message : err);
477
+ failed = true;
478
+ }
479
+ if (!failed || !this.attention)
480
+ return undefined;
481
+ const updated = await this.attention.setRoute(child.id, item.id, {
482
+ route: 'human',
483
+ escalatedAt: new Date().toISOString(),
484
+ escalationNote: PARENT_UNAVAILABLE_NOTE,
485
+ }, 'parent');
486
+ if (updated && !updated.resolvedAt && updated.route === 'human') {
487
+ this.publishHumanAttention(child.id, updated);
488
+ return updated;
489
+ }
490
+ try {
491
+ return await this.attention.waitForItem(child.id, item.id, 0);
492
+ }
493
+ catch {
494
+ return item;
495
+ }
496
+ }
497
+ /** Caller must be the child's parent. Returns the parent session, or null after writing 403. */
498
+ async loadParentCaller(req, res, child) {
499
+ const caller = this.readCallerSessionId(req);
500
+ if (!this.store || !child.parentSessionId || caller !== child.parentSessionId) {
501
+ jsonResponse(res, 403, { error: 'Only the parent session can do this', code: 'forbidden' });
502
+ return null;
503
+ }
504
+ const parent = await this.store.loadSession(child.parentSessionId);
505
+ if (!parent || parent.id !== child.parentSessionId) {
506
+ jsonResponse(res, 403, { error: 'Only the parent session can do this', code: 'forbidden' });
507
+ return null;
508
+ }
509
+ return parent;
510
+ }
511
+ async dispatchCoordinationRoutes(req, res, path, url) {
512
+ if (!this.store)
513
+ return false;
514
+ const store = this.store;
515
+ let responded = false;
516
+ const ctx = {
517
+ req,
518
+ res,
519
+ method: req.method ?? 'GET',
520
+ path,
521
+ query: url.searchParams,
522
+ callerSessionId: this.readCallerSessionId(req),
523
+ parseBody: () => parseBody(req),
524
+ json: (status, body) => {
525
+ responded = true;
526
+ jsonResponse(res, status, body);
527
+ },
528
+ loadSession: (id) => store.loadSession(id),
529
+ saveSession: (session) => store.saveSession(session),
530
+ publishSession: (session) => {
531
+ if (this.centrifugo && this.userId) {
532
+ void this.centrifugo.publishSessionUpdate(this.userId, session);
533
+ }
534
+ },
535
+ };
536
+ try {
537
+ if (await handleBriefRoutes(ctx))
538
+ return true;
539
+ if (await this.worktreeRoutes(ctx))
540
+ return true;
541
+ return false;
542
+ }
543
+ catch (error) {
544
+ if (error instanceof RouteError) {
545
+ if (!responded && !res.headersSent)
546
+ ctx.json(error.status, { error: error.message });
547
+ return true;
548
+ }
549
+ throw error;
550
+ }
551
+ }
552
+ async handleParentAttentionAction(req, res, childId, eventId, action) {
553
+ if (req.method !== 'POST') {
554
+ jsonResponse(res, 405, { error: 'Method not allowed' });
555
+ return;
556
+ }
557
+ if (!this.store) {
558
+ jsonResponse(res, 503, { error: 'Server not ready' });
559
+ return;
560
+ }
561
+ const child = await this.store.loadSession(childId);
562
+ if (!child) {
563
+ jsonResponse(res, 404, { error: 'Session not found', code: 'unknown_session' });
564
+ return;
565
+ }
566
+ if (!this.attention) {
567
+ jsonResponse(res, 503, { error: 'Attention store not ready', code: 'attention_not_ready' });
568
+ return;
569
+ }
570
+ const parent = await this.loadParentCaller(req, res, child);
571
+ if (!parent)
572
+ return;
573
+ if (action === 'answer') {
574
+ const body = await parseBody(req);
575
+ if (!body || typeof body !== 'object' || Array.isArray(body)
576
+ || Object.keys(body).some((key) => key !== 'answers')) {
577
+ throw new BadRequestError('Invalid attention answer');
578
+ }
579
+ const { item, waiterLive } = await this.attention.answer(child.id, eventId, body.answers, undefined, { kind: 'session', sessionId: parent.id, name: parent.name });
580
+ await deliverAttentionAnswer({
581
+ child,
582
+ item,
583
+ waiterLive,
584
+ sender: { from: parent.id, fromName: parent.name },
585
+ acceptMail: (session, mailBody) => this.acceptSessionMail(session, mailBody),
586
+ });
587
+ jsonResponse(res, 200, { event: item });
588
+ return;
589
+ }
590
+ const body = await parseBody(req);
591
+ if (!body || typeof body !== 'object' || Array.isArray(body)
592
+ || Object.keys(body).some((key) => key !== 'note')) {
593
+ throw new BadRequestError('Invalid escalation');
594
+ }
595
+ if (body.note !== undefined && (typeof body.note !== 'string' || body.note.length > 500)) {
596
+ throw new BadRequestError('Invalid escalation note');
597
+ }
598
+ const current = await this.attention.waitForItem(child.id, eventId, 0);
599
+ if (current.resolvedAt || current.route !== 'parent') {
600
+ jsonResponse(res, 409, { error: 'Attention request is already with the human', code: 'attention_conflict' });
601
+ return;
602
+ }
603
+ const updated = await this.attention.setRoute(child.id, eventId, {
604
+ route: 'human',
605
+ escalatedAt: new Date().toISOString(),
606
+ ...(typeof body.note === 'string' ? { escalationNote: body.note } : {}),
607
+ }, 'parent');
608
+ if (!updated || updated.resolvedAt || updated.route !== 'human') {
609
+ jsonResponse(res, 409, { error: 'Attention request is already with the human', code: 'attention_conflict' });
610
+ return;
611
+ }
612
+ this.publishHumanAttention(child.id, updated);
613
+ jsonResponse(res, 200, { event: updated });
285
614
  }
286
615
  setCoordination(coordination) {
287
616
  this.coordination = coordination;
@@ -307,6 +636,8 @@ export class LocalApiServer extends EventEmitter {
307
636
  list: async (id) => this.attention
308
637
  ? this.attention.list(id)
309
638
  : { activity: { state: 'unknown' }, openCount: 0 },
639
+ listRouted: async (childId) => this.attention ? this.attention.listRouted(childId) : [],
640
+ setRoute: async (sessionId, eventId, fields, expectRoute) => this.attention ? this.attention.setRoute(sessionId, eventId, fields, expectRoute) : undefined,
310
641
  },
311
642
  prStatus: async () => null,
312
643
  mail: {
@@ -325,6 +656,9 @@ export class LocalApiServer extends EventEmitter {
325
656
  }
326
657
  },
327
658
  now: Date.now,
659
+ onAttentionEscalated: (sessionId, item) => {
660
+ this.publishHumanAttention(sessionId, item);
661
+ },
328
662
  });
329
663
  return this.defaultCoordination;
330
664
  }
@@ -427,6 +761,11 @@ export class LocalApiServer extends EventEmitter {
427
761
  publishSessionUpdate: (session) => centrifugo.publishSessionUpdate(userId, session),
428
762
  removeSession: (id, options) => removeFtownSession({ store, runner, centrifugo, userId }, id, options),
429
763
  collectUsage: (session) => collectSessionUsage(session),
764
+ onSessionEnding: async (session) => {
765
+ const coordination = this.getCoordination();
766
+ if (coordination)
767
+ await coordination.onSessionExit(session.id, session);
768
+ },
430
769
  ...(this.sessionDeps ? { sessionFactory: this.sessionDeps } : {}),
431
770
  });
432
771
  return this.sessionController;
@@ -612,7 +951,17 @@ export class LocalApiServer extends EventEmitter {
612
951
  if (caller?.shellType)
613
952
  body.shellType = caller.shellType;
614
953
  }
615
- const input = parseCreateSessionBody(body, useCallerAsParent ? callerSessionId : undefined);
954
+ let input;
955
+ try {
956
+ input = parseCreateSessionBody(body, useCallerAsParent ? callerSessionId : undefined);
957
+ }
958
+ catch (err) {
959
+ if (err instanceof WorktreeError) {
960
+ jsonResponse(res, 400, { error: err.message });
961
+ return;
962
+ }
963
+ throw err;
964
+ }
616
965
  if (!input.command && !input.shellType && !input.prompt) {
617
966
  jsonResponse(res, 400, {
618
967
  error: 'Provide shellType, prompt, and/or command',
@@ -629,6 +978,10 @@ export class LocalApiServer extends EventEmitter {
629
978
  jsonResponse(res, 201, { session: toWireSession(session) });
630
979
  }
631
980
  catch (err) {
981
+ if (err instanceof WorktreeError) {
982
+ jsonResponse(res, 400, { error: err.message });
983
+ return;
984
+ }
632
985
  if (err instanceof ProviderAuthMissingError) {
633
986
  const r = providerAuthMissingResponse(err);
634
987
  jsonResponse(res, r.status, r.body);
@@ -674,6 +1027,13 @@ export class LocalApiServer extends EventEmitter {
674
1027
  jsonResponse(res, 200, { sessionId });
675
1028
  return;
676
1029
  }
1030
+ if (await this.dispatchCoordinationRoutes(req, res, path, url))
1031
+ return;
1032
+ const parentAttentionMatch = path.match(/^\/api\/sessions\/([a-zA-Z0-9_-]+)\/attention\/([A-Za-z0-9_-]{1,100})\/(answer|escalate)$/);
1033
+ if (parentAttentionMatch) {
1034
+ await this.handleParentAttentionAction(req, res, parentAttentionMatch[1], parentAttentionMatch[2], parentAttentionMatch[3]);
1035
+ return;
1036
+ }
677
1037
  const attentionMatch = path.match(/^\/api\/sessions\/([a-zA-Z0-9_-]+)\/attention(?:\/([A-Za-z0-9_-]+))?$/);
678
1038
  if (attentionMatch) {
679
1039
  const id = attentionMatch[1];
@@ -688,6 +1048,28 @@ export class LocalApiServer extends EventEmitter {
688
1048
  }
689
1049
  const attentionSub = attentionMatch[2];
690
1050
  const attentionAction = attentionSub === 'ack' || attentionSub === 'resolve' ? attentionSub : undefined;
1051
+ if (attentionSub === 'routed') {
1052
+ if (req.method !== 'GET') {
1053
+ jsonResponse(res, 405, { error: 'Method not allowed' });
1054
+ return;
1055
+ }
1056
+ const caller = this.readCallerSessionId(req);
1057
+ if (caller !== id) {
1058
+ jsonResponse(res, 403, { error: 'Only the parent session can do this', code: 'forbidden' });
1059
+ return;
1060
+ }
1061
+ const sessions = await this.store.listSessions();
1062
+ const items = [];
1063
+ for (const child of sessions) {
1064
+ if (child.parentSessionId !== id || child.id === id)
1065
+ continue;
1066
+ const routed = await this.attention.listRouted(child.id);
1067
+ for (const event of routed)
1068
+ items.push({ sessionId: child.id, sessionName: child.name, event });
1069
+ }
1070
+ jsonResponse(res, 200, { items });
1071
+ return;
1072
+ }
691
1073
  if (attentionSub === 'ask') {
692
1074
  if (req.method !== 'POST') {
693
1075
  jsonResponse(res, 405, { error: 'Method not allowed' });
@@ -699,26 +1081,43 @@ export class LocalApiServer extends EventEmitter {
699
1081
  }
700
1082
  const body = await parseBody(req);
701
1083
  if (!body || typeof body !== 'object' || Array.isArray(body)
702
- || Object.keys(body).some((key) => !['toolName', 'toolUseId', 'toolInput'].includes(key)))
1084
+ || Object.keys(body).some((key) => !['toolName', 'toolUseId', 'toolInput', 'to'].includes(key)))
703
1085
  throw new BadRequestError('Invalid ask arguments');
704
1086
  if (typeof body.toolName !== 'string' || !body.toolName.trim() || body.toolName.length > 200)
705
1087
  throw new BadRequestError('Invalid toolName');
706
1088
  if (typeof body.toolUseId !== 'string' || !body.toolUseId.trim() || body.toolUseId.length > 200)
707
1089
  throw new BadRequestError('Invalid toolUseId');
1090
+ const to = this.readAttentionTarget(body);
1091
+ const { route, parent } = await this.resolveAttentionRouting(session, to);
708
1092
  const toolData = { tool_name: body.toolName, tool_use_id: body.toolUseId, tool_input: body.toolInput };
709
- const { item, created } = await this.attention.recordDetailed(id, 'PreToolUse', toolData);
710
- // When ftown's ordinary (async) PreToolUse hook is missing or late, this is the only signal the UI gets.
711
- // Same stamped payload as /hook; deduped asks publish nothing, and the agent is not marked busy.
712
- if (item && created) {
713
- this.emit('event', { sessionId: id, eventName: 'PreToolUse', source: 'api', data: {
714
- hook_event_name: 'PreToolUse', ...toolData,
715
- attentionId: item.id, attentionSequence: item.sequence, attentionCreatedAt: item.createdAt,
716
- } });
717
- if (session.parentSessionId) {
718
- await this.getCoordination()?.emit(session, 'attention', item.title, item.id);
1093
+ const hold = route === 'parent' ? this.beginParentPushHold(id) : undefined;
1094
+ let suppressItemId;
1095
+ try {
1096
+ const { item, created } = await this.attention.recordDetailed(id, 'PreToolUse', toolData);
1097
+ // When ftown's ordinary (async) PreToolUse hook is missing or late, this is the only signal the UI gets.
1098
+ // Same stamped payload as /hook; deduped asks publish nothing, and the agent is not marked busy.
1099
+ // Only a newly created parent-routed item skips that notice and the push.
1100
+ let responseItem = item;
1101
+ if (item && created) {
1102
+ const applied = await this.applyParentRoute(session, item, created, route, parent);
1103
+ responseItem = applied.item;
1104
+ suppressItemId = applied.suppressPushId;
1105
+ if (!applied.skipNotice) {
1106
+ this.emit('event', { sessionId: id, eventName: 'PreToolUse', source: 'api', data: {
1107
+ hook_event_name: 'PreToolUse', ...toolData,
1108
+ attentionId: applied.item.id, attentionSequence: applied.item.sequence, attentionCreatedAt: applied.item.createdAt,
1109
+ } });
1110
+ }
1111
+ if (session.parentSessionId) {
1112
+ await this.getCoordination()?.emit(session, 'attention', applied.item.title, applied.item.id);
1113
+ }
719
1114
  }
1115
+ jsonResponse(res, 200, { event: responseItem && responseItem.prompt ? responseItem : null });
1116
+ }
1117
+ finally {
1118
+ if (hold !== undefined)
1119
+ this.finishParentPushHold(id, hold, suppressItemId);
720
1120
  }
721
- jsonResponse(res, 200, { event: item && item.prompt ? item : null });
722
1121
  return;
723
1122
  }
724
1123
  if (attentionSub && !attentionAction) {
@@ -754,12 +1153,13 @@ export class LocalApiServer extends EventEmitter {
754
1153
  }
755
1154
  const body = await parseBody(req);
756
1155
  if (!body || typeof body !== 'object' || Array.isArray(body)
757
- || Object.keys(body).some((key) => !['title', 'message', 'questions'].includes(key)))
1156
+ || Object.keys(body).some((key) => !['title', 'message', 'questions', 'to'].includes(key)))
758
1157
  throw new BadRequestError('Invalid attention arguments');
759
1158
  if (typeof body.message !== 'string' || !body.message.trim() || body.message.trim().length > 2000)
760
1159
  throw new BadRequestError('Invalid attention message');
761
1160
  if (body.title !== undefined && (typeof body.title !== 'string' || !body.title.trim() || body.title.trim().length > 200))
762
1161
  throw new BadRequestError('Invalid attention title');
1162
+ const to = this.readAttentionTarget(body);
763
1163
  const title = sanitizeAttentionText(typeof body.title === 'string' ? body.title : 'Session needs your input', 200);
764
1164
  const message = sanitizeAttentionText(body.message, 2000);
765
1165
  if (!title || !message)
@@ -773,20 +1173,37 @@ export class LocalApiServer extends EventEmitter {
773
1173
  }
774
1174
  prompt = parsed.value;
775
1175
  }
776
- const event = await this.attention.record(id, 'Notification', { notification_type: 'agent_needs_input', title, message }, prompt ? { prompt } : undefined);
777
- if (!event)
778
- throw new AttentionError('attention_storage_error', 'Attention history could not be persisted', 500);
779
- // Durable commit precedes publication; the live stream carries only
780
- // the sanitized request and its exact committed record identifier.
781
- this.emit('event', { sessionId: id, eventName: 'Notification', source: 'api', data: {
782
- notification_type: 'agent_needs_input', title: event.title, message: event.message, notification_id: event.id,
783
- attentionId: event.id, attentionSequence: event.sequence, attentionCreatedAt: event.createdAt,
784
- ...(event.prompt ? { attentionPrompt: event.prompt } : {}),
785
- } });
786
- if (session.parentSessionId) {
787
- await this.getCoordination()?.emit(session, 'attention', event.title, event.id);
1176
+ const { route, parent } = await this.resolveAttentionRouting(session, to);
1177
+ const hold = route === 'parent' ? this.beginParentPushHold(id) : undefined;
1178
+ let suppressItemId;
1179
+ try {
1180
+ const event = await this.attention.record(id, 'Notification', { notification_type: 'agent_needs_input', title, message }, prompt ? { prompt } : undefined);
1181
+ if (!event)
1182
+ throw new AttentionError('attention_storage_error', 'Attention history could not be persisted', 500);
1183
+ // record() only reports the item. A newly created row starts at one occurrence;
1184
+ // a repeat increments it and must keep the route it already has.
1185
+ const applied = await this.applyParentRoute(session, event, event.occurrences === 1, route, parent);
1186
+ suppressItemId = applied.suppressPushId;
1187
+ // Durable commit precedes publication; the live stream carries only
1188
+ // the sanitized request and its exact committed record identifier.
1189
+ // A new parent-routed item skips the dashboard notice. A repeat keeps
1190
+ // its stored route, so a human-routed repeat still publishes.
1191
+ if (!applied.skipNotice) {
1192
+ this.emit('event', { sessionId: id, eventName: 'Notification', source: 'api', data: {
1193
+ notification_type: 'agent_needs_input', title: applied.item.title, message: applied.item.message, notification_id: applied.item.id,
1194
+ attentionId: applied.item.id, attentionSequence: applied.item.sequence, attentionCreatedAt: applied.item.createdAt,
1195
+ ...(applied.item.prompt ? { attentionPrompt: applied.item.prompt } : {}),
1196
+ } });
1197
+ }
1198
+ if (session.parentSessionId) {
1199
+ await this.getCoordination()?.emit(session, 'attention', applied.item.title, applied.item.id);
1200
+ }
1201
+ jsonResponse(res, 200, { event: applied.item });
1202
+ }
1203
+ finally {
1204
+ if (hold !== undefined)
1205
+ this.finishParentPushHold(id, hold, suppressItemId);
788
1206
  }
789
- jsonResponse(res, 200, { event });
790
1207
  return;
791
1208
  }
792
1209
  if (!attentionSub && req.method === 'GET') {
@@ -1207,9 +1624,23 @@ export class LocalApiServer extends EventEmitter {
1207
1624
  jsonResponse(res, 404, { error: 'Session not found' });
1208
1625
  return;
1209
1626
  }
1210
- await controller.remove(sessionId);
1627
+ const worktreeValues = url.searchParams.getAll('worktree');
1628
+ if (worktreeValues.length > 1)
1629
+ throw new BadRequestError('Invalid worktree mode');
1630
+ let worktreeMode = 'auto';
1631
+ if (worktreeValues.length === 1) {
1632
+ const mode = worktreeValues[0];
1633
+ if (mode !== 'keep' && mode !== 'force')
1634
+ throw new BadRequestError('Invalid worktree mode');
1635
+ worktreeMode = mode;
1636
+ }
1637
+ const removed = await controller.remove(sessionId, undefined, worktreeMode);
1211
1638
  this.mail.markSessionEnded(sessionId);
1212
- jsonResponse(res, 200, { removed: true, sessionId });
1639
+ jsonResponse(res, 200, {
1640
+ removed: true,
1641
+ sessionId,
1642
+ ...(removed.worktreeOutcome ? { worktreeOutcome: removed.worktreeOutcome } : {}),
1643
+ });
1213
1644
  return;
1214
1645
  }
1215
1646
  // POST /api/sessions/:id/revive — recreate a removed session from its tombstone
@@ -1717,7 +2148,7 @@ export class LocalApiServer extends EventEmitter {
1717
2148
  committedAttention = await this.attention.record(ftownSessionId, hookEventName, rest, isPromptSubmit ? { promptOrigin: injected ? 'injected' : 'human' } : undefined);
1718
2149
  }
1719
2150
  if (hookEventName === 'UserPromptSubmit' || hookEventName === 'PreToolUse' || hookEventName === 'PostToolUse')
1720
- this.mail.markAgentBusy(ftownSessionId);
2151
+ this.mail.markAgentBusy(ftownSessionId, hookEventName);
1721
2152
  else if (hookEventName === 'Stop')
1722
2153
  this.mail.markAgentIdle(ftownSessionId);
1723
2154
  else if (hookEventName === 'SessionEnd') {