ftown-bridge 0.30.70 → 0.30.72

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