ftown-bridge 0.30.71 → 0.30.73

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 (100) hide show
  1. package/dist/attention-cli.d.ts +1 -0
  2. package/dist/attention-cli.js +3 -1
  3. package/dist/attention-cli.js.map +1 -1
  4. package/dist/cli-client.d.ts +2 -0
  5. package/dist/cli-client.js +19 -0
  6. package/dist/cli-client.js.map +1 -1
  7. package/dist/coordination/attention-routing.d.ts +1 -0
  8. package/dist/coordination/attention-routing.js +44 -30
  9. package/dist/coordination/attention-routing.js.map +1 -1
  10. package/dist/coordination/board.d.ts +2 -0
  11. package/dist/coordination/board.js +34 -17
  12. package/dist/coordination/board.js.map +1 -1
  13. package/dist/coordination/contract-c.d.ts +1 -0
  14. package/dist/coordination/contract-c.js.map +1 -1
  15. package/dist/coordination/contract.d.ts +6 -1
  16. package/dist/coordination/contract.js +1 -1
  17. package/dist/coordination/contract.js.map +1 -1
  18. package/dist/coordination/peer-team.d.ts +44 -0
  19. package/dist/coordination/peer-team.js +77 -0
  20. package/dist/coordination/peer-team.js.map +1 -0
  21. package/dist/coordination/plan.d.ts +5 -3
  22. package/dist/coordination/plan.js +79 -49
  23. package/dist/coordination/plan.js.map +1 -1
  24. package/dist/coordination/tree-events.js +14 -4
  25. package/dist/coordination/tree-events.js.map +1 -1
  26. package/dist/coordination/wiring.d.ts +6 -1
  27. package/dist/coordination/wiring.js +30 -12
  28. package/dist/coordination/wiring.js.map +1 -1
  29. package/dist/create-ftown-session.d.ts +8 -3
  30. package/dist/create-ftown-session.js +44 -22
  31. package/dist/create-ftown-session.js.map +1 -1
  32. package/dist/harness-commands.js +11 -8
  33. package/dist/harness-commands.js.map +1 -1
  34. package/dist/index.js +75 -30
  35. package/dist/index.js.map +1 -1
  36. package/dist/local-api-server.d.ts +12 -1
  37. package/dist/local-api-server.js +251 -27
  38. package/dist/local-api-server.js.map +1 -1
  39. package/dist/mail-delivery.d.ts +1 -0
  40. package/dist/mail-delivery.js +3 -0
  41. package/dist/mail-delivery.js.map +1 -1
  42. package/dist/peer-control.d.ts +2 -2
  43. package/dist/peer-control.js +3 -1
  44. package/dist/peer-control.js.map +1 -1
  45. package/dist/peer-session-cache.d.ts +144 -1
  46. package/dist/peer-session-cache.js +61 -7
  47. package/dist/peer-session-cache.js.map +1 -1
  48. package/dist/preview-assets.d.ts +10 -0
  49. package/dist/preview-assets.js +241 -0
  50. package/dist/preview-assets.js.map +1 -0
  51. package/dist/preview-protocol.d.ts +10 -1
  52. package/dist/preview-protocol.js +3 -1
  53. package/dist/preview-protocol.js.map +1 -1
  54. package/dist/project-board-commands.d.ts +2 -0
  55. package/dist/project-board-commands.js +18 -1
  56. package/dist/project-board-commands.js.map +1 -1
  57. package/dist/project-board-store.d.ts +4 -0
  58. package/dist/project-board-store.js +53 -16
  59. package/dist/project-board-store.js.map +1 -1
  60. package/dist/project-cli.js +35 -10
  61. package/dist/project-cli.js.map +1 -1
  62. package/dist/project-directory-protocol.d.ts +3 -1
  63. package/dist/project-directory-protocol.js +3 -1
  64. package/dist/project-directory-protocol.js.map +1 -1
  65. package/dist/project-storage-move.d.ts +30 -0
  66. package/dist/project-storage-move.js +421 -0
  67. package/dist/project-storage-move.js.map +1 -0
  68. package/dist/remote-child-plan.d.ts +23 -0
  69. package/dist/remote-child-plan.js +68 -0
  70. package/dist/remote-child-plan.js.map +1 -0
  71. package/dist/security/bridge/permissions.js +9 -1
  72. package/dist/security/bridge/permissions.js.map +1 -1
  73. package/dist/security/bridge/security.js +1 -1
  74. package/dist/security/bridge/security.js.map +1 -1
  75. package/dist/session-block.d.ts +2 -0
  76. package/dist/session-block.js +7 -2
  77. package/dist/session-block.js.map +1 -1
  78. package/dist/session-board-snapshot.d.ts +1 -1
  79. package/dist/session-controller.d.ts +3 -2
  80. package/dist/session-controller.js +56 -33
  81. package/dist/session-controller.js.map +1 -1
  82. package/dist/session-handoff.d.ts +1 -0
  83. package/dist/session-handoff.js +2 -1
  84. package/dist/session-handoff.js.map +1 -1
  85. package/dist/session-parent.d.ts +13 -4
  86. package/dist/session-parent.js +51 -9
  87. package/dist/session-parent.js.map +1 -1
  88. package/dist/session-preview.d.ts +7 -2
  89. package/dist/session-preview.js +241 -141
  90. package/dist/session-preview.js.map +1 -1
  91. package/dist/sessions-commands.js +42 -32
  92. package/dist/sessions-commands.js.map +1 -1
  93. package/dist/ticket-notifications.js +5 -3
  94. package/dist/ticket-notifications.js.map +1 -1
  95. package/dist/wire-types.d.ts +1 -0
  96. package/dist/wire-types.js.map +1 -1
  97. package/package.json +7 -2
  98. package/skills/ftown/SKILL.md +6 -17
  99. package/skills/ftown/references/orchestrator.md +1 -1
  100. package/skills/ftown/references/sessions.md +27 -33
@@ -1,8 +1,10 @@
1
+ import { PREVIEW_MAX_INPUTS } from './preview-protocol.js';
2
+ import { applyRemoteChildPlan, CHILD_PLAN_PATH } from './remote-child-plan.js';
1
3
  import { runProjectBoardCommand } from './project-board-commands.js';
2
4
  import { ProjectBoardChanged } from './project-board-store.js';
3
5
  import { BridgeSecurityError } from './security/bridge/errors.js';
4
6
  import { TICKET_NOTIFICATION_WIRE, TICKET_NOTIFICATION_INBOX } from './ticket-notification-protocol.js';
5
- import { boardCommandForPath, PROJECT_DIRECTORY } from './project-directory-protocol.js';
7
+ import { boardCommandForPath, PROJECT_DIRECTORY, PROJECT_MOVE } from './project-directory-protocol.js';
6
8
  import { INSTRUCTIONS_LOCAL, INSTRUCTIONS_SYNC, INSTRUCTIONS_WIRE } from './instructions-protocol.js';
7
9
  import { mergeGlobal, readRevision } from './instructions.js';
8
10
  import { peerResources } from './host-resources.js';
@@ -37,9 +39,11 @@ import { CardValidationError } from './coordination/contract.js';
37
39
  import { PARENT_UNAVAILABLE_NOTE, RouteError, WorktreeError, } from './coordination/contract-b.js';
38
40
  import { decideRoute, queueAttentionAnswer, formatParentQuestionMail, markArchivedWorktreeRetained, } from './coordination/attention-routing.js';
39
41
  import { handleBriefRoutes } from './coordination/routes-brief.js';
42
+ import { TEAM_EVENT_PATH, teamEvent } from './coordination/peer-team.js';
43
+ import { boardManagerId } from './coordination/board.js';
40
44
  import { createPlanRoutes } from './coordination/routes-plan.js';
41
45
  import { createWorktreeRoutes } from './coordination/routes-worktrees.js';
42
- import { createCoordination, rootOf } from './coordination/wiring.js';
46
+ import { createCoordination } from './coordination/wiring.js';
43
47
  import { GitWorktrees } from './worktrees.js';
44
48
  import { PeerTargetError } from './peer-control.js';
45
49
  import { MAX_LINK_SDP_CHARS } from './peer-link.js';
@@ -298,6 +302,8 @@ export class LocalApiServer extends EventEmitter {
298
302
  || (timeoutMs !== undefined && typeof timeoutMs !== 'number')) {
299
303
  return { status: 400, body: { error: 'Expected { bridge, method, path, body?, timeoutMs? }' } };
300
304
  }
305
+ if (request.path.split('?')[0] === CHILD_PLAN_PATH)
306
+ return { status: 403, body: { error: 'Bridge plan updates are internal' } };
301
307
  return await this.peerControl.http(request.bridge, request.method, request.path, request.body, timeoutMs);
302
308
  }
303
309
  }
@@ -377,6 +383,74 @@ export class LocalApiServer extends EventEmitter {
377
383
  if (route.kind !== 'http')
378
384
  throw new Error('Invalid application route');
379
385
  const routePath = route.path.split('?')[0];
386
+ if (routePath === '/api/team-questions') {
387
+ const owner = message.principal.endpoint.kind === 'bridge'
388
+ && this.security.peerBridges().find(peer => peer.endpoint.id === message.principal.endpoint.id)?.bridgeId;
389
+ if (!owner)
390
+ return { status: 403, body: { error: 'permission_denied' } };
391
+ if (!this.store || !this.attention)
392
+ return { status: 503, body: { error: 'Attention unavailable' } };
393
+ const parentId = new URL(route.path, 'http://localhost').searchParams.get('parent');
394
+ if (!parentId || !/^[A-Za-z0-9_-]{1,200}$/.test(parentId))
395
+ return { status: 400, body: { error: 'Invalid parent' } };
396
+ await this.security.revalidate(message.principal);
397
+ const children = (await this.store.listSessions()).filter(s => s.parentBridgeId === owner && s.parentSessionId === parentId);
398
+ const items = await Promise.all(children.map(async (child) => (await this.attention.listRouted(child.id))
399
+ .filter(item => item.routedTo === parentId).map(event => ({ sessionId: child.id, sessionName: child.name, bridgeId: child.bridgeId, event }))));
400
+ return { status: 200, body: applicationJson({ items: items.flat() }) };
401
+ }
402
+ if (routePath === TEAM_EVENT_PATH) {
403
+ const peer = message.principal.endpoint.kind === 'bridge'
404
+ && this.security.peerBridges().find(row => row.endpoint.id === message.principal.endpoint.id);
405
+ if (!peer)
406
+ return { status: 403, body: { error: 'permission_denied' } };
407
+ const parsed = teamEvent.safeParse(message.application.data?.body);
408
+ if (!parsed.success)
409
+ return { status: 400, body: { error: 'Invalid team event' } };
410
+ const { manager, deliveryId, event } = parsed.data;
411
+ const coordination = this.getCoordination();
412
+ if (!this.store || !this.peerControl || !coordination)
413
+ return { status: 503, body: { error: 'Coordination unavailable' } };
414
+ const parent = await this.store.loadSession(manager);
415
+ if (!parent || parent.bridgeId !== this.security.bridgeId)
416
+ return { status: 410, body: { error: 'Manager retired' } };
417
+ const response = await this.peerControl.http(peer.bridgeId, 'GET', '/api/sessions/' + event.sessionId, undefined, 6_000);
418
+ let child = response.body?.session;
419
+ if (response.status === 404) {
420
+ const archived = await this.peerControl.http(peer.bridgeId, 'GET', '/api/archive?sessionId=' + event.sessionId, undefined, 6_000);
421
+ if (archived.status !== 200)
422
+ return { status: 503, body: { error: 'Child archive unavailable' } };
423
+ child = archived.body?.archived?.filter(row => row.id === event.sessionId).at(-1);
424
+ }
425
+ else if (response.status !== 200)
426
+ return { status: 503, body: { error: 'Child unavailable' } };
427
+ if (child?.id !== event.sessionId || child.bridgeId !== peer.bridgeId
428
+ || child.parentSessionId !== manager || child.parentBridgeId !== parent.bridgeId)
429
+ return { status: 410, body: { error: 'Relationship changed' } };
430
+ await this.security.revalidate(message.principal);
431
+ await coordination.events.append(manager, { ...event, sessionName: child.name, deliveryId });
432
+ this.onTeamChanged?.(manager);
433
+ return { status: 200, body: { ok: true } };
434
+ }
435
+ if (routePath === CHILD_PLAN_PATH) {
436
+ await this.security.revalidate(message.principal);
437
+ const peer = message.principal.endpoint.kind === 'bridge'
438
+ && this.security.peerBridges().find(peer => peer.endpoint.id === message.principal.endpoint.id);
439
+ if (!peer)
440
+ return { status: 403, body: { error: 'permission_denied' } };
441
+ const plans = this.getCoordination()?.plan;
442
+ if (!plans || !this.peerControl)
443
+ return { status: 503, body: { error: 'Plan tracking unavailable' } };
444
+ const data = message.application.data;
445
+ try {
446
+ return { status: 200, body: applicationJson(await applyRemoteChildPlan(this.peerControl, plans, this.security.bridgeId, peer.bridgeId, data?.body, () => this.security.revalidate(message.principal))) };
447
+ }
448
+ catch (error) {
449
+ if (error instanceof BridgeSecurityError)
450
+ throw error;
451
+ return { status: 400, body: { error: 'Invalid child plan operation' } };
452
+ }
453
+ }
380
454
  const boardCommand = boardCommandForPath(route.path);
381
455
  if (route.method === 'POST' && boardCommand) {
382
456
  const endpoint = message.principal.endpoint;
@@ -389,7 +463,7 @@ export class LocalApiServer extends EventEmitter {
389
463
  return { status: 400, body: { error: 'Invalid project board payload' } };
390
464
  try {
391
465
  const data = await runProjectBoardCommand(this.boardCommands, boardCommand, { ...body, bridgeId: this.security.bridgeId }, message.principal);
392
- if ((boardCommand === 'mutate_project_board' || boardCommand === 'get_project_board' || boardCommand === 'mutate_project_discussion') && typeof body.projectId === 'string') {
466
+ if ((boardCommand === 'mutate_project_board' || boardCommand === 'get_project_board' || boardCommand === 'mutate_project_discussion') && body.action !== 'move_project' && typeof body.projectId === 'string') {
393
467
  void this.boardCommands.deliverProject(body.projectId);
394
468
  }
395
469
  return { status: 200, body: applicationJson(data) };
@@ -428,6 +502,21 @@ export class LocalApiServer extends EventEmitter {
428
502
  return { status: 400, body: { error: 'Could not store ticket notification' } };
429
503
  }
430
504
  }
505
+ if (routePath === PROJECT_MOVE) {
506
+ const peer = this.security.peerBridges().find(p => p.endpoint.id === message.principal.endpoint.id);
507
+ if (!peer || message.principal.endpoint.kind !== 'bridge')
508
+ return { status: 403, body: { error: 'permission_denied' } };
509
+ if (!this.boardCommands?.ready() || !this.boardCommands.storageMoves)
510
+ return { status: 503, body: { error: 'Storage moves unavailable' } };
511
+ await this.security.revalidate(message.principal);
512
+ try {
513
+ const body = message.application.data.body;
514
+ return { status: 200, body: this.boardCommands.storageMoves.receive(peer.bridgeId, body) };
515
+ }
516
+ catch (error) {
517
+ return { status: 409, body: { error: error instanceof Error ? error.message.slice(0, 300) : 'Project move failed' } };
518
+ }
519
+ }
431
520
  if (routePath === PROJECT_DIRECTORY) {
432
521
  const { endpoint } = message.principal;
433
522
  if (endpoint.kind !== 'bridge' || !this.security.peerBridges().some(peer => peer.endpoint.id === endpoint.id))
@@ -435,7 +524,7 @@ export class LocalApiServer extends EventEmitter {
435
524
  await this.security.revalidate(message.principal);
436
525
  if (!this.localProjects)
437
526
  return { status: 503, body: { error: 'Project directory unavailable' } };
438
- const projects = this.localProjects().map(({ id, bridgeId, name }) => ({ id, bridgeId, name }));
527
+ const projects = this.localProjects().map(({ id, bridgeId, name, homeRevision }) => ({ id, bridgeId, name, ...(homeRevision ? { homeRevision } : {}) }));
439
528
  return { status: 200, body: applicationJson({ projects }) };
440
529
  }
441
530
  if (routePath === INSTRUCTIONS_LOCAL || routePath === INSTRUCTIONS_WIRE || routePath === INSTRUCTIONS_SYNC)
@@ -444,7 +533,7 @@ export class LocalApiServer extends EventEmitter {
444
533
  await this.security.revalidate(message.principal);
445
534
  if (!this.hostResources)
446
535
  return { status: 503, body: { error: 'Host resources unavailable' } };
447
- return { status: 200, body: applicationJson({ bridgeId: this.security.bridgeId, resources: await this.hostResources() }) };
536
+ return { status: 200, body: applicationJson({ bridgeId: this.security.bridgeId, nestedSessions: true, resources: await this.hostResources() }) };
448
537
  }
449
538
  if (routePath === TRANSFER_LOCAL || routePath === TRANSFER_WIRE)
450
539
  return this.dispatchTransfer(message, routePath);
@@ -665,17 +754,85 @@ export class LocalApiServer extends EventEmitter {
665
754
  return 'human';
666
755
  throw new BadRequestError("Invalid attention target");
667
756
  }
757
+ async remoteResultSender(id, manager) {
758
+ const principal = sessionRequestPrincipal.getStore();
759
+ if (!principal || principal.endpoint.kind !== 'bridge' || !this.peerControl || !/^[A-Za-z0-9_-]{1,200}$/.test(id))
760
+ return null;
761
+ const owner = this.security?.peerBridges().find(peer => peer.endpoint.id === principal.endpoint.id)?.bridgeId;
762
+ if (!owner)
763
+ return null;
764
+ const result = await this.peerControl.http(owner, 'GET', '/api/sessions/' + id, undefined, 6_000);
765
+ const child = result.body?.session;
766
+ await this.security.revalidate(principal);
767
+ return result.status === 200 && child?.id === id && child.bridgeId === owner
768
+ && child.parentSessionId === manager.id && child.parentBridgeId === manager.bridgeId ? child : null;
769
+ }
770
+ /** Look up the current manager at the owner explicitly named by the child. */
771
+ async loadManager(child) {
772
+ if (!child.parentSessionId || !this.store)
773
+ return null;
774
+ const owner = child.parentBridgeId ?? child.bridgeId;
775
+ if (owner === child.bridgeId) {
776
+ const parent = await this.store.loadSession(child.parentSessionId);
777
+ return parent?.bridgeId === owner ? parent : null;
778
+ }
779
+ const actor = sessionRequestPrincipal.getStore();
780
+ if (!this.peerControl || (actor && !this.security?.permitsPeerLookup(actor)))
781
+ return null;
782
+ try {
783
+ const reply = await this.peerControl.http(owner, 'GET', '/api/sessions/' + encodeURIComponent(child.parentSessionId), undefined, 6_000);
784
+ if (actor)
785
+ await this.security.revalidate(actor);
786
+ const parent = reply.body?.session;
787
+ return reply.status === 200 && parent?.id === child.parentSessionId && parent.bridgeId === owner && typeof parent.name === 'string' ? parent : null;
788
+ }
789
+ catch {
790
+ return null;
791
+ }
792
+ }
793
+ async mailManager(parent, body) {
794
+ if (!this.securityInfo || parent.bridgeId === this.securityInfo.bridgeId)
795
+ return this.acceptSessionMail(parent, body);
796
+ if (!this.peerControl)
797
+ return { ok: false, error: 'Manager bridge unavailable' };
798
+ try {
799
+ const result = await this.peerControl.http(parent.bridgeId, 'POST', '/api/sessions/' + encodeURIComponent(parent.id) + '/inbox', body);
800
+ return result.status === 201 ? { ok: true } : { ok: false, error: 'Manager inbox unavailable' };
801
+ }
802
+ catch {
803
+ return { ok: false, error: 'Manager bridge unavailable' };
804
+ }
805
+ }
806
+ async managerCanAnswer(child) {
807
+ return (await this.resolveAttentionRouting(child)).route === 'parent';
808
+ }
809
+ async remoteResultReported(child) {
810
+ if (!child.parentBridgeId || !child.parentSessionId || !this.peerControl)
811
+ return false;
812
+ const result = await this.peerControl.http(child.parentBridgeId, 'GET', '/api/sessions/' + encodeURIComponent(child.parentSessionId) + '/inbox?peek=1&resultFrom=' + encodeURIComponent(child.id));
813
+ return result.status === 200 && result.body?.reported === true;
814
+ }
668
815
  async resolveAttentionRouting(child, to) {
669
- if (!this.store || !child.parentSessionId) {
816
+ if (to === 'human')
670
817
  return { route: 'human', parent: null };
818
+ const parent = await this.loadManager(child);
819
+ let parentRunning = !!parent && parent.status === 'running';
820
+ if (parentRunning && parent) {
821
+ if (parent.bridgeId === child.bridgeId) {
822
+ if (typeof this.runner?.isRunning === 'function')
823
+ parentRunning = this.runner.isRunning(parent.id);
824
+ }
825
+ else {
826
+ try {
827
+ const reply = await this.peerControl.http(parent.bridgeId, 'GET', '/api/sessions/' + encodeURIComponent(parent.id) + '/running', undefined, 6_000);
828
+ parentRunning = reply.status === 200 && reply.body?.running === true;
829
+ }
830
+ catch {
831
+ parentRunning = false;
832
+ }
833
+ }
671
834
  }
672
- const parent = await this.store.loadSession(child.parentSessionId);
673
- const parentRunning = !!parent &&
674
- (typeof this.runner?.isRunning === 'function'
675
- ? this.runner.isRunning(parent.id)
676
- : parent.status === 'running');
677
- const route = decideRoute(child, parent, parentRunning, to);
678
- return { route, parent };
835
+ return { route: decideRoute(child, parent, parentRunning, to), parent };
679
836
  }
680
837
  /** Hold pushes for this session until the created item id is known. */
681
838
  beginParentPushHold(sessionId) {
@@ -734,11 +891,12 @@ export class LocalApiServer extends EventEmitter {
734
891
  async sendParentQuestionMail(child, parent, item) {
735
892
  let failed = false;
736
893
  try {
737
- const accepted = await this.acceptSessionMail(parent, {
894
+ const accepted = await this.mailManager(parent, {
738
895
  from: child.id,
739
896
  fromName: child.name,
740
897
  type: 'escalation',
741
898
  threadId: item.id,
899
+ idempotencyKey: 'parent-question:' + child.id + ':' + item.id,
742
900
  body: formatParentQuestionMail(child, item),
743
901
  });
744
902
  if (!accepted.ok) {
@@ -768,15 +926,30 @@ export class LocalApiServer extends EventEmitter {
768
926
  return item;
769
927
  }
770
928
  }
929
+ peerParent(child, claimed) {
930
+ const actor = sessionRequestPrincipal.getStore();
931
+ if (actor?.endpoint.kind !== 'bridge' || !child.parentSessionId || child.parentSessionId !== claimed)
932
+ return undefined;
933
+ const owner = this.security?.peerBridges().find(peer => peer.endpoint.id === actor.endpoint.id)?.bridgeId;
934
+ return owner && owner === child.parentBridgeId && owner !== child.bridgeId ? child.parentSessionId : undefined;
935
+ }
771
936
  /** Caller must be the child's parent. Returns the parent session, or null after writing 403. */
772
- async loadParentCaller(req, res, child) {
937
+ async loadParentCaller(req, res, child, claimed) {
938
+ const actor = sessionRequestPrincipal.getStore();
939
+ if (actor?.endpoint.kind === 'bridge') {
940
+ const id = this.peerParent(child, claimed);
941
+ if (id)
942
+ return { id, name: id };
943
+ jsonResponse(res, 403, { error: 'Only the parent session can do this', code: 'forbidden' });
944
+ return null;
945
+ }
773
946
  const caller = this.readCallerSessionId(req);
774
947
  if (!this.store || !child.parentSessionId || caller !== child.parentSessionId) {
775
948
  jsonResponse(res, 403, { error: 'Only the parent session can do this', code: 'forbidden' });
776
949
  return null;
777
950
  }
778
951
  const parent = await this.store.loadSession(child.parentSessionId);
779
- if (!parent || parent.id !== child.parentSessionId) {
952
+ if (!parent || parent.id !== child.parentSessionId || parent.bridgeId !== (child.parentBridgeId ?? child.bridgeId)) {
780
953
  jsonResponse(res, 403, { error: 'Only the parent session can do this', code: 'forbidden' });
781
954
  return null;
782
955
  }
@@ -846,11 +1019,15 @@ export class LocalApiServer extends EventEmitter {
846
1019
  jsonResponse(res, 503, { error: 'Attention store not ready', code: 'attention_not_ready' });
847
1020
  return;
848
1021
  }
849
- const parent = await this.loadParentCaller(req, res, child);
1022
+ const body = await parseBody(req);
1023
+ if (!body || typeof body !== 'object' || Array.isArray(body))
1024
+ throw new BadRequestError('Invalid parent action');
1025
+ const parent = await this.loadParentCaller(req, res, child, body.parentSessionId);
850
1026
  if (!parent)
851
1027
  return;
1028
+ if (sessionRequestPrincipal.getStore()?.endpoint.kind === 'bridge')
1029
+ delete body.parentSessionId;
852
1030
  if (action === 'answer') {
853
- const body = await parseBody(req);
854
1031
  if (!body || typeof body !== 'object' || Array.isArray(body)
855
1032
  || Object.keys(body).some((key) => key !== 'answers')) {
856
1033
  throw new BadRequestError('Invalid attention answer');
@@ -862,7 +1039,6 @@ export class LocalApiServer extends EventEmitter {
862
1039
  jsonResponse(res, 200, { event: item });
863
1040
  return;
864
1041
  }
865
- const body = await parseBody(req);
866
1042
  if (!body || typeof body !== 'object' || Array.isArray(body)
867
1043
  || Object.keys(body).some((key) => key !== 'note')) {
868
1044
  throw new BadRequestError('Invalid escalation');
@@ -887,7 +1063,9 @@ export class LocalApiServer extends EventEmitter {
887
1063
  this.publishHumanAttention(child.id, updated);
888
1064
  jsonResponse(res, 200, { event: updated });
889
1065
  }
890
- setCoordination(coordination) {
1066
+ onTeamChanged;
1067
+ setCoordination(coordination, onTeamChanged) {
1068
+ this.onTeamChanged = onTeamChanged;
891
1069
  this.coordination = coordination;
892
1070
  this.defaultCoordination = null;
893
1071
  if (typeof this.mail.setDigestProvider === 'function') {
@@ -1204,6 +1382,7 @@ export class LocalApiServer extends EventEmitter {
1204
1382
  }
1205
1383
  // GET /api/sessions
1206
1384
  if (path === '/api/sessions' && req.method === 'GET') {
1385
+ const pendingParents = this.sessionDeps?.hierarchyWrites?.pendingParents() ?? [];
1207
1386
  const sessions = await (this.getSessionController()?.list() ?? this.store.listSessions());
1208
1387
  if (url.searchParams.get('boardAttention') === '1' && this.attention) {
1209
1388
  const rows = [];
@@ -1218,7 +1397,7 @@ export class LocalApiServer extends EventEmitter {
1218
1397
  jsonResponse(res, 200, { sessions: rows });
1219
1398
  }
1220
1399
  else
1221
- jsonResponse(res, 200, { sessions: sessions.map(toWireSession) });
1400
+ jsonResponse(res, 200, { sessions: sessions.map(toWireSession), ...(pendingParents.length ? { pendingParents } : {}) });
1222
1401
  return;
1223
1402
  }
1224
1403
  // POST /api/sessions — create a new agent session (same as UI create_session)
@@ -1295,7 +1474,11 @@ export class LocalApiServer extends EventEmitter {
1295
1474
  // env is stripped: it can carry API keys and only revive (server-side)
1296
1475
  // needs it.
1297
1476
  if (path === '/api/archive' && req.method === 'GET') {
1298
- const archived = (await this.store.listArchived()).map((record) => {
1477
+ const sessionId = url.searchParams.get('sessionId');
1478
+ if (sessionId && !/^[A-Za-z0-9_-]{1,200}$/.test(sessionId))
1479
+ throw new BadRequestError('Invalid session ID');
1480
+ const records = await this.store.listArchived();
1481
+ const archived = (sessionId ? records.filter(row => row.id === sessionId).slice(-1) : records).map((record) => {
1299
1482
  const sanitized = { ...record };
1300
1483
  delete sanitized.env;
1301
1484
  delete sanitized.previewSource;
@@ -1360,7 +1543,24 @@ export class LocalApiServer extends EventEmitter {
1360
1543
  for (const event of routed)
1361
1544
  items.push({ sessionId: child.id, sessionName: child.name, event });
1362
1545
  }
1363
- jsonResponse(res, 200, { items });
1546
+ const principal = sessionRequestPrincipal.getStore();
1547
+ const unavailable = [];
1548
+ if (principal?.endpoint.kind === 'local-cli' && this.peerControl) {
1549
+ const peers = await this.peerControl.list();
1550
+ await Promise.all(peers.map(async (peer) => {
1551
+ try {
1552
+ const result = await this.peerControl.http(peer.bridgeId, 'GET', '/api/team-questions?parent=' + encodeURIComponent(id), undefined, 6_000);
1553
+ const body = result.body;
1554
+ if (result.status !== 200 || !Array.isArray(body?.items))
1555
+ throw new Error();
1556
+ items.push(...body.items.filter(row => row.event?.routedTo === id && row.event.route === 'parent'));
1557
+ }
1558
+ catch {
1559
+ unavailable.push(peer.bridgeId);
1560
+ }
1561
+ }));
1562
+ }
1563
+ jsonResponse(res, 200, { items, ...(unavailable.length ? { unavailable } : {}) });
1364
1564
  return;
1365
1565
  }
1366
1566
  if (attentionSub === 'ask') {
@@ -1594,6 +1794,10 @@ export class LocalApiServer extends EventEmitter {
1594
1794
  throw new BadRequestError('Card update must be an object');
1595
1795
  }
1596
1796
  const rawBody = body;
1797
+ const peer = sessionRequestPrincipal.getStore()?.endpoint.kind === 'bridge';
1798
+ const claimed = rawBody.parentSessionId;
1799
+ if (peer)
1800
+ delete rawBody.parentSessionId;
1597
1801
  const keys = Object.keys(rawBody);
1598
1802
  if (keys.length === 0)
1599
1803
  throw new BadRequestError('Empty card update');
@@ -1616,7 +1820,8 @@ export class LocalApiServer extends EventEmitter {
1616
1820
  jsonResponse(res, 404, { error: 'Session not found' });
1617
1821
  return;
1618
1822
  }
1619
- const callerId = this.readCallerSessionId(req);
1823
+ const callerId = peer ? this.peerParent(targetSession, claimed)
1824
+ : !targetSession.parentBridgeId || targetSession.parentBridgeId === targetSession.bridgeId ? this.readCallerSessionId(req) : undefined;
1620
1825
  const forcedByParent = force &&
1621
1826
  Boolean(callerId && targetSession.parentSessionId && callerId === targetSession.parentSessionId);
1622
1827
  if (targetSession.requireGreenPr && patch.state === 'done' && !forcedByParent) {
@@ -1798,7 +2003,8 @@ export class LocalApiServer extends EventEmitter {
1798
2003
  jsonResponse(res, 404, { error: 'Session not found' });
1799
2004
  return;
1800
2005
  }
1801
- const rootId = rootOf(session);
2006
+ const known = await this.rememberedPeerSessions?.();
2007
+ const rootId = boardManagerId(session, await this.store.listSessions(), known?.some(s => s.parentSessionId === session.id && s.parentBridgeId === session.bridgeId));
1802
2008
  if (waitSeconds && waitSeconds > 0) {
1803
2009
  const controller = new AbortController();
1804
2010
  const cancel = () => controller.abort();
@@ -1868,7 +2074,7 @@ export class LocalApiServer extends EventEmitter {
1868
2074
  }
1869
2075
  const body = await parseBody(req);
1870
2076
  if (req.method === 'PUT') {
1871
- if (Object.keys(body).some((key) => key !== 'paths' && key !== 'mode') || !('paths' in body) || !Array.isArray(body.paths) || body.paths.length < 1 || body.paths.length > 12 || body.paths.some((entry) => typeof entry !== 'string' || entry.length === 0)) {
2077
+ if (Object.keys(body).some((key) => key !== 'paths' && key !== 'mode') || !('paths' in body) || !Array.isArray(body.paths) || body.paths.length < 1 || body.paths.length > PREVIEW_MAX_INPUTS || body.paths.some((entry) => typeof entry !== 'string' || entry.length === 0)) {
1872
2078
  jsonResponse(res, 400, { error: 'Invalid preview request' });
1873
2079
  return;
1874
2080
  }
@@ -1984,12 +2190,13 @@ export class LocalApiServer extends EventEmitter {
1984
2190
  // GET /api/sessions/:id
1985
2191
  if (sessionMatch && req.method === 'GET') {
1986
2192
  const sessionId = sessionMatch[1];
2193
+ const moving = this.sessionDeps?.hierarchyWrites?.isMoving(sessionId);
1987
2194
  const session = await (this.getSessionController()?.get(sessionId) ?? this.store.loadSession(sessionId));
1988
2195
  if (!session) {
1989
2196
  jsonResponse(res, 404, { error: 'Session not found' });
1990
2197
  return;
1991
2198
  }
1992
- jsonResponse(res, 200, { session: toWireSession(session), capabilities: {
2199
+ jsonResponse(res, 200, { session: toWireSession(session), ...(moving || this.sessionDeps?.hierarchyWrites?.isMoving(sessionId) ? { hierarchyChanging: true } : {}), capabilities: {
1993
2200
  ...(this.attention ? { attention: { version: 1, request: true, prompt: true } } : {}),
1994
2201
  sessionMetadata: { pullRequest: true, preview: true },
1995
2202
  } });
@@ -2422,6 +2629,16 @@ export class LocalApiServer extends EventEmitter {
2422
2629
  || !child.parentSessionId || child.parentSessionId === child.id || !/^[A-Za-z0-9_-]{1,200}$/.test(child.parentSessionId))
2423
2630
  return;
2424
2631
  const parentId = child.parentSessionId;
2632
+ if (child.parentBridgeId && child.parentBridgeId !== bridgeId) {
2633
+ if (!await this.managerCanAnswer(child))
2634
+ return;
2635
+ const current = await store.loadSession(child.id);
2636
+ if (!isCurrent() || current?.status !== 'running' || current.parentSessionId !== parentId
2637
+ || current.parentBridgeId !== child.parentBridgeId || !runner.isRunning(current.id))
2638
+ return;
2639
+ await this.getCoordination()?.emit(current, 'idle', (sanitizeAttentionText(current.name, 200) || 'Session') + ' idle for 2m');
2640
+ return;
2641
+ }
2425
2642
  const parent = await store.loadSession(parentId);
2426
2643
  if (!parent || parent.id !== parentId || parent.bridgeId !== bridgeId || parent.status !== 'running' || parent.shellType === 'shell')
2427
2644
  return;
@@ -2531,6 +2748,13 @@ export class LocalApiServer extends EventEmitter {
2531
2748
  jsonResponse(res, 404, { error: 'Session not found' });
2532
2749
  return;
2533
2750
  }
2751
+ const resultFrom = url.searchParams.get('resultFrom');
2752
+ if (resultFrom !== null) {
2753
+ if (url.searchParams.get('peek') !== '1' || !/^[A-Za-z0-9_-]{1,200}$/.test(resultFrom))
2754
+ throw new BadRequestError('Invalid result query');
2755
+ jsonResponse(res, 200, { reported: await this.mail.hasResultFrom(sessionId, resultFrom) });
2756
+ return;
2757
+ }
2534
2758
  try {
2535
2759
  const registration = parseNativeWakeRegistration(url.searchParams);
2536
2760
  if (registration)