@staix/agent-hub 0.52.0 → 0.54.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 (196) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +4 -3
  3. package/docs/addons/open-code-review.md +3 -6
  4. package/docs/agent-notes/README.md +1 -1
  5. package/docs/agent-notes/adapters.md +5 -4
  6. package/docs/agent-notes/budget.md +2 -2
  7. package/docs/agent-notes/bus.md +1 -0
  8. package/docs/agent-notes/daemon.md +6 -5
  9. package/docs/agent-notes/models.md +1 -1
  10. package/docs/agent-notes/tasks.md +3 -3
  11. package/docs/agent-notes/tests.md +4 -4
  12. package/docs/contracts/companion-cli-v2.json +90 -0
  13. package/docs/contracts/companion-cli-v3.json +348 -0
  14. package/docs/design/adapters.md +1 -1
  15. package/docs/design/agent-hub-architecture.md +8 -5
  16. package/docs/design/bus.md +1 -1
  17. package/docs/design/cli-output-inventory.md +4 -2
  18. package/docs/design/execution-reference.md +1 -1
  19. package/docs/design/guidance-experiments.md +1 -0
  20. package/docs/design/guidance-probes.md +1 -0
  21. package/docs/design/model-routes.md +20 -5
  22. package/docs/design/roadmap.md +6 -4
  23. package/docs/design/task-board.md +21 -2
  24. package/docs/dogfood.md +13 -6
  25. package/docs/events.md +1 -1
  26. package/docs/memory.md +2 -2
  27. package/docs/operations.md +158 -50
  28. package/docs/quickstart.md +14 -2
  29. package/docs/security.md +17 -9
  30. package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
  31. package/docs/specs/2026-09-19-multi-project-design.md +1 -1
  32. package/docs/specs/2026-09-20-upgrade-recovery-design.md +24 -0
  33. package/docs/specs/2026-12-04-arev-adoption-design.md +84 -0
  34. package/docs/specs/mcp-endpoint.md +15 -4
  35. package/docs/specs/relay-contract.md +38 -0
  36. package/docs/verification/2026-12-04-host-shared-receipts.md +43 -0
  37. package/docs/verification/2026-12-05-0.53.0.md +101 -0
  38. package/docs/verification/2026-12-05-agy-1.5.24.md +55 -0
  39. package/docs/verification/2026-12-05-claude-implementer-2.1.337.md +43 -0
  40. package/docs/verification/2026-12-06-0.54.0.md +76 -0
  41. package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
  42. package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
  43. package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
  44. package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
  45. package/docs/verified.json +38 -29
  46. package/package.json +9 -3
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/.mcp.json +1 -1
  49. package/plugins/agent-hub/compat.json +9 -5
  50. package/plugins/agent-hub/kimi-hook.js +892 -874
  51. package/plugins/agent-hub/relay-launcher.js +24 -0
  52. package/plugins/agent-hub/server.js +27271 -25146
  53. package/src/adapters/acp-session-model.ts +1 -1
  54. package/src/adapters/acp.ts +5 -4
  55. package/src/adapters/agy/definition.ts +1 -1
  56. package/src/adapters/agy/hooks.ts +1 -1
  57. package/src/adapters/channel-peer.ts +3 -1
  58. package/src/adapters/claude-channel-evidence.ts +26 -1
  59. package/src/adapters/claude-channel.ts +27 -30
  60. package/src/adapters/claude-connection-policy.ts +62 -0
  61. package/src/adapters/claude-relay.ts +255 -0
  62. package/src/adapters/codex-review-isolation.ts +1 -2
  63. package/src/adapters/compat.ts +28 -18
  64. package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
  65. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  66. package/src/adapters/definitions/native-context.ts +1 -2
  67. package/src/adapters/definitions/native-factories.ts +4 -1
  68. package/src/adapters/definitions/native-quota.ts +1 -1
  69. package/src/adapters/definitions/native-recovery.ts +3 -1
  70. package/src/adapters/external-modules.ts +2 -2
  71. package/src/adapters/kimi-review.ts +1 -1
  72. package/src/adapters/kimi-tui-facts.ts +1 -1
  73. package/src/adapters/local-worker.ts +3 -3
  74. package/src/adapters/native-capabilities.ts +1 -1
  75. package/src/adapters/pi.ts +26 -7
  76. package/src/adapters/registry-types.ts +2 -0
  77. package/src/adapters/relay-launcher.ts +27 -0
  78. package/src/adapters/reviewer-mcp.ts +1 -1
  79. package/src/cli/agents.ts +20 -8
  80. package/src/cli/agy-mcp.ts +1 -1
  81. package/src/cli/claude-profile-hook.ts +1 -1
  82. package/src/cli/command-table.ts +1 -0
  83. package/src/cli/commands/agents.ts +18 -1
  84. package/src/cli/commands/doctor.ts +18 -4
  85. package/src/cli/commands/launch-line.ts +32 -0
  86. package/src/cli/commands/status.ts +14 -3
  87. package/src/cli/help.ts +7 -4
  88. package/src/cli/identity.ts +1 -1
  89. package/src/cli/init-roles.ts +1 -1
  90. package/src/cli/init-settings.ts +1 -1
  91. package/src/cli/launch-line-plan.ts +82 -0
  92. package/src/cli/launch-line-project.ts +13 -0
  93. package/src/cli/main.ts +10 -9
  94. package/src/cli/pi-steps-warning.ts +14 -0
  95. package/src/cli/recovery-package.ts +60 -6
  96. package/src/cli/reset.ts +1 -1
  97. package/src/cli/shell-quote.ts +1 -3
  98. package/src/cli/upgrade-interactive.ts +7 -2
  99. package/src/cli/upgrade-keep-plan.ts +47 -0
  100. package/src/cli/upgrade-restore-state.ts +1 -1
  101. package/src/cli/upgrade-runtime.ts +119 -18
  102. package/src/cli/upgrade.ts +17 -2
  103. package/src/hub/accounts.ts +8 -4
  104. package/src/hub/action-class.ts +1 -3
  105. package/src/hub/adec-triage.ts +105 -0
  106. package/src/hub/autonomy.ts +1 -1
  107. package/src/hub/board.ts +3 -27
  108. package/src/hub/bus.ts +39 -6
  109. package/src/hub/capabilities.ts +1 -1
  110. package/src/hub/channel-project-base.ts +46 -0
  111. package/src/hub/channel-project.ts +21 -46
  112. package/src/hub/config-apply.ts +1 -1
  113. package/src/hub/config-edit.ts +1 -1
  114. package/src/hub/config-tier.ts +1 -1
  115. package/src/hub/config.ts +2 -2
  116. package/src/hub/confirmation-matrix.ts +1 -1
  117. package/src/hub/control/board-messages.ts +415 -0
  118. package/src/hub/control/dashboard-messages.ts +221 -0
  119. package/src/hub/control/delivery-messages.ts +356 -0
  120. package/src/hub/control/dispatch.ts +114 -0
  121. package/src/hub/control/hub-tool-helpers.ts +243 -0
  122. package/src/hub/control/hub-tools.ts +147 -0
  123. package/src/hub/control/native-messages.ts +665 -0
  124. package/src/hub/control/operations-messages.ts +269 -0
  125. package/src/hub/control/peer-messages.ts +126 -0
  126. package/src/hub/control/recovery-messages.ts +391 -0
  127. package/src/hub/control/recovery-operation.ts +480 -0
  128. package/src/hub/control/scope.ts +460 -0
  129. package/src/hub/control/sdlc-messages.ts +373 -0
  130. package/src/hub/control/task-ops-more.ts +245 -0
  131. package/src/hub/control/task-ops.ts +553 -0
  132. package/src/hub/control/ui-actions.ts +241 -0
  133. package/src/hub/control-write-trace.ts +1 -4
  134. package/src/hub/daemon.ts +485 -4324
  135. package/src/hub/delivery-hints.ts +2 -0
  136. package/src/hub/delivery-journal.ts +17 -6
  137. package/src/hub/events.ts +2 -1
  138. package/src/hub/execution-reference.ts +1 -1
  139. package/src/hub/host.ts +41 -9
  140. package/src/hub/hub-tools.ts +3 -4
  141. package/src/hub/invocations.ts +1 -1
  142. package/src/hub/lifecycle.ts +4 -3
  143. package/src/hub/mcp-endpoint-serve.ts +4 -3
  144. package/src/hub/mcp-endpoint.ts +15 -6
  145. package/src/hub/memory-profile-check.ts +1 -1
  146. package/src/hub/no-writes.ts +1 -1
  147. package/src/hub/peers.ts +2 -0
  148. package/src/hub/pi-exit-policy.ts +27 -0
  149. package/src/hub/progress.ts +1 -1
  150. package/src/hub/project-runtime-state.ts +17 -4
  151. package/src/hub/project-runtime.ts +3 -1
  152. package/src/hub/protocol-window.ts +1 -1
  153. package/src/hub/recovery-continuity.ts +3 -3
  154. package/src/hub/recovery-kept-roster.ts +50 -0
  155. package/src/hub/review-anchor.ts +13 -181
  156. package/src/hub/review-brief.ts +78 -28
  157. package/src/hub/review-findings.ts +15 -193
  158. package/src/hub/review-ledger.ts +162 -0
  159. package/src/hub/review-material.ts +3 -3
  160. package/src/hub/reviewer-pool.ts +4 -2
  161. package/src/hub/roadmap-issue-states.ts +65 -14
  162. package/src/hub/roadmap-sync.ts +39 -14
  163. package/src/hub/routing.ts +9 -0
  164. package/src/hub/runtime-capture-prune.ts +8 -2
  165. package/src/hub/runtime-package-assets.ts +3 -0
  166. package/src/hub/sdlc-release-policy.ts +1 -2
  167. package/src/hub/settings.ts +1 -1
  168. package/src/hub/spec-ack-tool.ts +4 -0
  169. package/src/hub/spec-report-history.ts +36 -0
  170. package/src/hub/specs.ts +1 -4
  171. package/src/hub/supervision.ts +33 -6
  172. package/src/hub/tasks-audit.ts +390 -0
  173. package/src/hub/tasks-backlog.ts +522 -0
  174. package/src/hub/tasks-handoff.ts +208 -0
  175. package/src/hub/tasks-release.ts +257 -0
  176. package/src/hub/tasks-roadmap.ts +17 -3
  177. package/src/hub/tasks-specs.ts +672 -0
  178. package/src/hub/tasks-types.ts +334 -0
  179. package/src/hub/tasks.ts +286 -1961
  180. package/src/hub/upgrade-session-contract.ts +11 -0
  181. package/src/local/probe-sandbox.ts +1 -2
  182. package/src/local/probe-workspace.ts +1 -1
  183. package/src/models/route/config.ts +4 -4
  184. package/src/models/route/decision.ts +18 -10
  185. package/src/models/route/observation-signals.ts +1 -2
  186. package/src/models/route/runtime.ts +8 -5
  187. package/src/npm-artifact.ts +76 -0
  188. package/src/omniroute/client.ts +6 -0
  189. package/src/pi/extension.ts +5 -2
  190. package/src/pi/install.ts +77 -0
  191. package/src/pi/pin.ts +49 -0
  192. package/src/primitives.ts +14 -0
  193. package/src/version.ts +2 -0
  194. package/templates/adec/README.md +10 -6
  195. package/templates/config.json +1 -1
  196. package/templates/specs.block.md +1 -0
@@ -1,3 +1,4 @@
1
+ import { asRecord as record } from "../primitives.ts";
1
2
  import { safeModelLabel } from "../omniroute/usage.ts";
2
3
  import { ACP_MODEL_OPTIONS_MAX, acpLogicalModelId, type AcpModelPolicy } from "./acp-model-policy.ts";
3
4
 
@@ -11,7 +12,6 @@ function label(value: unknown, policy: AcpModelPolicy | undefined): string | und
11
12
  const safe = safeModelLabel(id);
12
13
  return safe !== undefined && safe.toLowerCase() !== "unknown" ? safe : undefined;
13
14
  }
14
- const record = (value: unknown): Record<string, unknown> | undefined => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
15
15
  /** The model in a `session/new` or `session/load` result (or a `configOptions`-only holder). */
16
16
  export function sessionModelId(session: unknown, policy?: AcpModelPolicy): string | undefined {
17
17
  const holder = record(session);
@@ -12,6 +12,7 @@ export { QwenIdentityError } from "./definitions/qwen-native.ts";
12
12
  import { BasePeer } from "../hub/peers.ts";
13
13
  import type { DeliveryFailureCause } from "../hub/delivery-failure.ts";
14
14
  import { peerChildEnv, stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
15
+ import { ACP_STOPPED_BEFORE_SETTLEMENT } from "../hub/delivery-hints.ts";
15
16
  import { AcpOwnedGroup } from "./acp-owned-group.ts";
16
17
  import type { StartForm, ModelOverrideSelection } from "./registry-types.ts";
17
18
  import { assessVersion, readTrust } from "./compat.ts";
@@ -646,8 +647,8 @@ export class AcpPeer extends BasePeer {
646
647
  // invalidates its generation, while stopping still prevents a drain.
647
648
  if (legacy?.turn === this.turn) this.onFailed?.(legacy.envs);
648
649
  if (reason !== undefined) this.turn++; // a requested stop cannot escalate or complete the cancelled turn
649
- if (this.activeDeliveryId) this.delivery({ id: this.activeDeliveryId, state: "needs_review", reason: reason ?? "ACP session stopped before settlement", failureCause: "turn aborted" });
650
- this.settleSteers("needs_review", reason ?? "ACP session stopped before settlement");
650
+ if (this.activeDeliveryId) this.delivery({ id: this.activeDeliveryId, state: "needs_review", reason: reason ?? ACP_STOPPED_BEFORE_SETTLEMENT, failureCause: "turn aborted", ...(reason === undefined ? { holdsSelf: true as const } : {}) }); // #1946: only this host path marks a row self-held; a requested stop keeps its peer-wide hold
651
+ this.settleSteers("needs_review", reason ?? ACP_STOPPED_BEFORE_SETTLEMENT, undefined, reason === undefined); // #1946: an accepted steer is part of the same unrequested stop
651
652
  this.activeDeliveryId = undefined;
652
653
  const proc = this.proc;
653
654
  if (!proc) { this.setState("offline"); return; }
@@ -872,9 +873,9 @@ export class AcpPeer extends BasePeer {
872
873
  if (deliveryId) { this.steerIds.push(deliveryId); this.delivery({ id: deliveryId, state: "accepted" }); }
873
874
  }
874
875
 
875
- private settleSteers(state: "completed" | "needs_review", reason?: string, failureCause?: DeliveryFailureCause): void {
876
+ private settleSteers(state: "completed" | "needs_review", reason?: string, failureCause?: DeliveryFailureCause, holdsSelf = false): void {
876
877
  const ids = this.steerIds; this.steerIds = [];
877
- for (const id of ids) this.delivery({ id, state, ...(state === "needs_review" ? { reason: reason ?? "steered turn did not complete normally", ...(failureCause ? { failureCause } : {}) } : {}) });
878
+ for (const id of ids) this.delivery({ id, state, ...(state === "needs_review" ? { reason: reason ?? "steered turn did not complete normally", ...(failureCause ? { failureCause } : {}), ...(holdsSelf ? { holdsSelf: true as const } : {}) } : {}) });
878
879
  }
879
880
 
880
881
  private acceptDelivery(): void {
@@ -1,3 +1,4 @@
1
+ import { shellQuote } from "../../primitives.ts";
1
2
  import { NATIVE_ROUTING_POLICY, NATIVE_ADAPTER_POLICY } from "../definitions/native-adapter-policy.ts";
2
3
  import { runAgyEntry } from "./entry.ts";
3
4
  import type { AdapterDefinition, LaunchContext, LaunchPlan } from "../registry-types.ts";
@@ -5,7 +6,6 @@ import { AGY_REVIEWER_VARIANT } from "../definitions/reviewer-variants.ts";
5
6
  import { NATIVE_FACTS_HOOKS } from "../native-facts-hooks.ts";
6
7
 
7
8
  const DISPLAY = { palette: { fg: "#6558a6", bg: "#f1effa" } };
8
- const shellQuote = (value: string): string => `'${value.replace(/'/g, `'\\''`)}'`;
9
9
 
10
10
  function agyLaunch(ctx: LaunchContext): LaunchPlan {
11
11
  const argv = ["agy", ...ctx.userArgs], command = argv.map(shellQuote).join(" ");
@@ -4,10 +4,10 @@ import { isAbsolute, join, relative } from "node:path";
4
4
  import { createHash } from "node:crypto";
5
5
  import { safeModelLabel } from "../../omniroute/usage.ts";
6
6
  import type { NativeFactsInput, NativeFactsPort, NativeFactsReadOptions, NativeFactsTranscript } from "../registry-types.ts";
7
+ import { isRecord as record } from "../../primitives.ts";
7
8
 
8
9
  const EVENTS = ["SessionStart", "PreInvocation", "PostInvocation", "PreToolUse", "PostToolUse", "Stop"] as const;
9
10
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
- const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
11
11
 
12
12
  /** #1402: Antigravity names the session's model in every hook payload (`modelName`, verified for 1.4.3 to 1.5.3). A value `safeModelLabel` refuses or the placeholder `unknown` names none; an alias is kept as reported. */
13
13
  function agyModel(value: unknown): string | undefined {
@@ -7,7 +7,7 @@ import type { ClaudeChannelEvidence } from "./claude-channel-evidence.ts";
7
7
  /** Only the control socket operations the peer owns; authentication remains in the daemon. */
8
8
  export interface ChannelSocket {
9
9
  readyState: number;
10
- data: { launchId?: string; claudeSessionId?: string; protocol?: number; standbyId?: string; retainStandby?: boolean; clientPid?: number; clientVersion?: string; channel?: boolean; channelEvidence?: ClaudeChannelEvidence; cwd?: string; peerGeneration?: string | number; detachedByPerson?: boolean; accountLabel?: string };
10
+ data: { launchId?: string; claudeSessionId?: string; claudeRelay?: boolean; protocol?: number; standbyId?: string; retainStandby?: boolean; clientPid?: number; clientVersion?: string; channel?: boolean; channelEvidence?: ClaudeChannelEvidence; cwd?: string; peerGeneration?: string | number; detachedByPerson?: boolean; accountLabel?: string };
11
11
  send(data: string): unknown;
12
12
  close(code?: number, reason?: string): void;
13
13
  }
@@ -77,6 +77,8 @@ export class WsPeer extends BasePeer {
77
77
  return [...this.standbys.values()].map(session => ({ ...session }));
78
78
  }
79
79
  get managedLaunchId(): string | undefined { return this.attached ? this.sock?.data.launchId : undefined; }
80
+ get reportedClaudeSessionId(): string | undefined { return this.attached ? this.sock?.data.claudeSessionId : undefined; }
81
+ get claudeRelay(): boolean { return this.attached && this.sock?.data.claudeRelay === true; }
80
82
  /**
81
83
  * Who holds this peer now, for display only (#1310). Absent while a newer hello is claiming (the peer reads as offline until its preface ends), while offline and after a detach, so a claimant or a
82
84
  * previous owner is never shown as attached. `ownerPid` is the current socket's bounded client pid, `attachedAt` is when its attach completed (not the hello), and `nativeSessionId` appears only
@@ -1,4 +1,4 @@
1
- import { spawnSync } from "node:child_process";
1
+ import { execFile, spawnSync } from "node:child_process";
2
2
 
3
3
  export type ClaudeChannelEvidence = "development-channel-launch" | "inherited-marker" | "launch-unverified" | "unknown" | "unreported";
4
4
  export type ClaudeAttachMode = "channel" | "tools-only";
@@ -54,3 +54,28 @@ export function claudeChannelEvidence(env: NodeJS.ProcessEnv = process.env, ppid
54
54
  export function currentClaudeChannelEvidence(): ClaudeChannelEvidence {
55
55
  return claudeChannelEvidence();
56
56
  }
57
+
58
+ function readClaudeRelayRows(pid: number, ppid: number): Promise<string | undefined> {
59
+ return new Promise(resolve => {
60
+ execFile("/bin/ps", ["-ww", "-p", `${pid},${ppid}`, "-o", "pid=", "-o", "ppid=", "-o", "command="], {
61
+ encoding: "utf8", timeout: 1500, maxBuffer: 8192, env: { PATH: "/usr/bin:/bin", LC_ALL: "C" },
62
+ }, (error, stdout) => resolve(error ? undefined : stdout));
63
+ });
64
+ }
65
+
66
+ /** The hello supplies candidate pids only. Both process rows must agree on the direct relationship. */
67
+ export async function claudeRelayParentEvidence(pid: number, ppid: number, read = readClaudeRelayRows): Promise<ClaudeChannelEvidence> {
68
+ if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(ppid) || pid <= 1 || ppid <= 1 || pid === ppid) return "unknown";
69
+ try {
70
+ const snapshot = await read(pid, ppid);
71
+ if (!snapshot || snapshot.length > 8192) return "unknown";
72
+ const rows = snapshot.trimEnd().split("\n").map(row => /^\s*(\d+)\s+(\d+)\s+(\S.*)$/.exec(row));
73
+ if (rows.length !== 2 || rows.some(row => !row)) return "unknown";
74
+ const child = rows.find(row => Number(row?.[1]) === pid);
75
+ const parent = rows.find(row => Number(row?.[1]) === ppid);
76
+ if (Number(child?.[2]) !== ppid || !parent?.[3]) return "unknown";
77
+ return classifyClaudeParentCommand(parent[3]);
78
+ } catch {
79
+ return "unknown";
80
+ }
81
+ }
@@ -17,12 +17,13 @@ import { readFileSync } from "node:fs";
17
17
  import { isAbsolute, join } from "node:path";
18
18
  import { homedir } from "node:os";
19
19
  import { ControlClient } from "../hub/control-client.ts";
20
- import { channelProject } from "../hub/channel-project.ts";
20
+ import { channelProject, channelProjectRoles } from "../hub/channel-project.ts";
21
21
  import { VERSION } from "../version.ts";
22
22
  import { DEFAULT_ROLES } from "../hub/hub-tools.ts";
23
23
  import { frame, type Envelope } from "../hub/envelope.ts";
24
24
  import { renderHeldHint } from "../hub/delivery-hints.ts";
25
25
  import { currentClaudeChannelEvidence } from "./claude-channel-evidence.ts";
26
+ import { claudeGapText, claudeHeldReason, claudeOfflineText, createGapHold, claudeReconnectDelay, claudeTerminalClose, HELD_CLOSE, WIRE_MISMATCH_CLOSE, WIRE_MISMATCH_REASON, WIRE_MISMATCH_RETRY_MS } from "./claude-connection-policy.ts";
26
27
 
27
28
  // A native session is pinned at launch. Unlike a new CLI invocation after `cd`,
28
29
  // its MCP server must not silently move to another hub (including while offline).
@@ -32,10 +33,7 @@ import { currentClaudeChannelEvidence } from "./claude-channel-evidence.ts";
32
33
  // root recorded in it equals the resolved root of this process's cwd, or (a declared extra instance) when its managed worktree is this cwd. A session started in `<repo>/.worktrees/<name>`
33
34
  // uses its own project. A session with no project of its own that inherited another project's state joins THAT hub as a distinct session (`<peer>~<id>`, minted by the hub): it can send and
34
35
  // read, holds none of the peer's roles, and never replaces the attached session. Nothing is refused. Limit: this makes sessions distinguishable, it does not authenticate them.
35
- const own = channelProject(process.cwd(), process.env, root => {
36
- const read = (name: string) => { try { return JSON.parse(readFileSync(join(root, ".agenthub", name), "utf8")).roles ?? {}; } catch { return {}; } };
37
- return { ...DEFAULT_ROLES, ...read("config.json"), ...read("config.local.json") };
38
- });
36
+ const own = channelProject(process.cwd(), process.env, channelProjectRoles);
39
37
  /** Set when this process joins as a distinct session. The hub's answer names the minted id; until then the session is only "a session". */
40
38
  const sessionJoin = own?.session;
41
39
  /** A hub that predates `session_identity` would ignore the request and bind the real peer id, which is the takeover this exists to prevent: such a session does not connect, and says why. */
@@ -114,22 +112,7 @@ function sessionRoles(): import("../hub/roles.ts").CatalogRole[] {
114
112
  return selectedRoles(peerId, roles(), assignments, catalog);
115
113
  } catch { console.error("[agent-hub] catalog role assignment refused: invalid id, shape or flow base"); return []; }
116
114
  }
117
- const MAX_RECONNECT_DELAY_MS = 30_000;
118
- const WIRE_MISMATCH_RETRY_MS = 5 * 60_000;
119
- const WIRE_MISMATCH_CLOSE = 4426;
120
- /** Close codes a retry cannot fix: bad token, wrong project, reserved or taken id. */
121
- const TERMINAL_CLOSES: Record<number, string> = {
122
- 4401: "the hub refused the control token",
123
- 4404: "the hub belongs to a different project or instance; restart this session from the intended project",
124
- 4403: `the hub refused "${peerId}": the id is reserved or malformed, or this process is not an owned launch of that peer (start it with ahub jcode)`,
125
- 4405: "detached by the person",
126
- 4409: `the peer id "${peerId}" is taken by a hub-managed adapter`,
127
- 4430: "this Claude launch ended; start a new session with ahub claude, or use a plain session with hub_inbox",
128
- };
129
- /** Another session attached under this peer id. Unlike the other closes this one ends on its own, so the
130
- * session stands by and takes the peer back once the hub reports it offline (issue #30). */
131
- const HELD_CLOSE = 4000;
132
- const HELD = `another session is attached to the hub as "${peerId}"; this one is standing by and takes the peer back when that session leaves`;
115
+ const HELD = claudeHeldReason(peerId);
133
116
  const INBOX_CAP = 200;
134
117
 
135
118
  /**
@@ -165,9 +148,9 @@ const server = new Server({ name: "agent-hub", version: VERSION }, mcpServerOpti
165
148
  const inbox: string[] = []; // pushes that failed; drained by hub_inbox
166
149
  let hub: ControlClient | undefined;
167
150
  let detached: string | undefined; // why this server stopped reconnecting; tool calls report it
168
- const offline = () => detached === "detached by the person"
169
- ? `detached by the person; this session no longer acts as ${peerId}. Stop here and tell the person. If they want this session back, start a fresh ahub claude.`
170
- : detached ?? "hub is not running for this project (start it with: ahub up).";
151
+ let reconnecting = false; // a served hub connection was lost and the loop is reconnecting (#1807 T4)
152
+ const gap = createGapHold<(connected: boolean) => void>({ expire: resolve => resolve(false) });
153
+ const offline = () => claudeOfflineText(peerId, detached);
171
154
  const offlineToolResult = (suffix = "") => {
172
155
  const result = text(`${offline()}${suffix}`);
173
156
  return detached === "detached by the person" ? { ...result, isError: true } : result;
@@ -211,7 +194,7 @@ async function connectLoop(): Promise<void> {
211
194
  for (let attempt = 0; ; attempt++) {
212
195
  // Standing by after a take-over: wait for the slot rather than evicting whoever holds it now.
213
196
  if (standingBy && peerHeld()) {
214
- await new Promise((r) => setTimeout(r, Math.min(1000 * 2 ** Math.max(attempt, 0), MAX_RECONNECT_DELAY_MS)));
197
+ await new Promise((r) => setTimeout(r, claudeReconnectDelay(attempt)));
215
198
  continue;
216
199
  }
217
200
  let code: number | undefined;
@@ -255,6 +238,8 @@ async function connectLoop(): Promise<void> {
255
238
  }).catch(() => log(`delivery receipt for ${msg.deliveryId} remains unconfirmed by hub`));
256
239
  };
257
240
  hub = client;
241
+ reconnecting = false;
242
+ for (const resolve of gap.release()) resolve(true);
258
243
  attempt = -1;
259
244
  standingBy = client.standby;
260
245
  detached = client.standby ? `${HELD}; a person can hand it over with ahub peer takeover ${peerId}` : undefined;
@@ -265,6 +250,7 @@ async function connectLoop(): Promise<void> {
265
250
  if (listedTools !== undefined) void reannounce(client).catch(() => {});
266
251
  code = await new Promise<number>((r) => { client.onClose = (value, reason) => { closeReason = reason; r(value); }; });
267
252
  hub = undefined;
253
+ reconnecting = !client.standby;
268
254
  log("hub connection lost");
269
255
  } catch (e) {
270
256
  code = (e as { code?: number }).code;
@@ -272,15 +258,20 @@ async function connectLoop(): Promise<void> {
272
258
  if (attempt === 0) log((e as Error).message);
273
259
  }
274
260
  if (code === WIRE_MISMATCH_CLOSE) {
275
- const reason = "wire version mismatch with the running hub; this session retries every 5 minutes. Check the project hub with ahub status. If the hub upgrade does not restore compatibility, run ahub setup and restart this session.";
261
+ const reason = WIRE_MISMATCH_REASON;
276
262
  if (detached !== reason) log(reason);
277
263
  detached = reason;
264
+ reconnecting = false;
265
+ for (const resolve of gap.release()) resolve(true); // detached now: each held call answers with today's text
278
266
  await Bun.sleep(WIRE_MISMATCH_RETRY_MS);
279
267
  continue;
280
268
  }
281
269
  // Retrying these only hammers a hub that will refuse again.
282
- if (code !== undefined && TERMINAL_CLOSES[code]) {
283
- detached = TERMINAL_CLOSES[code];
270
+ const terminal = claudeTerminalClose(code, peerId);
271
+ if (terminal) {
272
+ detached = terminal;
273
+ reconnecting = false;
274
+ for (const resolve of gap.release()) resolve(true);
284
275
  return log(`stopped reconnecting: ${detached}`);
285
276
  }
286
277
  if (code === HELD_CLOSE) {
@@ -288,8 +279,10 @@ async function connectLoop(): Promise<void> {
288
279
  if (!standingBy || detached !== reason) log(`standing by: ${reason}`);
289
280
  standingBy = true;
290
281
  detached = reason;
282
+ reconnecting = false;
283
+ for (const resolve of gap.release()) resolve(true);
291
284
  }
292
- await new Promise((r) => setTimeout(r, Math.min(1000 * 2 ** Math.max(attempt, 0), MAX_RECONNECT_DELAY_MS)));
285
+ await new Promise((r) => setTimeout(r, claudeReconnectDelay(attempt)));
293
286
  }
294
287
  }
295
288
 
@@ -327,7 +320,11 @@ const toolCallState: McpToolCallState = {
327
320
  get pendingQueued() { return pendingQueued; }, set pendingQueued(value) { pendingQueued = value; },
328
321
  HELD, NO_PROJECT, NO_SESSION_SUPPORT, UNIDENTIFIED,
329
322
  };
330
- async function callTool(req: { params: { name: string; arguments?: Record<string, unknown> } }, signal?: AbortSignal) { return hubToolCall(toolCallState, req, signal); }
323
+ async function callTool(req: { params: { name: string; arguments?: Record<string, unknown> } }, signal?: AbortSignal) {
324
+ // #1807 T4: while a served hub connection is being re-established, the call waits for it (up to the hold) instead of failing at once.
325
+ if (!hub && reconnecting && !detached && !(await new Promise<boolean>(resolve => { if (!gap.add(resolve, 128)) resolve(true); }))) return text(claudeGapText(peerId));
326
+ return hubToolCall(toolCallState, req, signal);
327
+ }
331
328
 
332
329
  // Inbox results still show fresh counts, without telling a held or refused reader to retry in a loop.
333
330
  server.setRequestHandler(CallToolRequestSchema, async (req, extra) => withPendingHint(toolCallState, await callTool(req, extra.signal), req.params.name !== "hub_inbox" && req.params.name !== "hub_source_read"));
@@ -0,0 +1,62 @@
1
+ // Shared display and retry policy for the bridge and the socket relay.
2
+ export const WIRE_MISMATCH_RETRY_MS = 5 * 60_000;
3
+ export const WIRE_MISMATCH_CLOSE = 4426;
4
+ export const HELD_CLOSE = 4000;
5
+ export const WIRE_MISMATCH_REASON = "wire version mismatch with the running hub; this session retries every 5 minutes. Check the project hub with ahub status. If the hub upgrade does not restore compatibility, run ahub setup and restart this session.";
6
+
7
+ const MAX_RECONNECT_DELAY_MS = 30_000;
8
+
9
+ export function claudeReconnectDelay(attempt: number): number {
10
+ return Math.min(1000 * 2 ** Math.max(attempt, 0), MAX_RECONNECT_DELAY_MS);
11
+ }
12
+
13
+ export function claudeTerminalClose(code: number | undefined, peer: string): string | undefined {
14
+ switch (code) {
15
+ case 4401: return "the hub refused the control token";
16
+ case 4404: return "the hub belongs to a different project or instance; restart this session from the intended project";
17
+ case 4403: return `the hub refused "${peer}": the id is reserved or malformed, or this process is not an owned launch of that peer (start it with ahub jcode)`;
18
+ case 4405: return "detached by the person";
19
+ case 4409: return `the peer id "${peer}" is taken by a hub-managed adapter`;
20
+ case 4430: return "this Claude launch ended; start a new session with ahub claude, or use a plain session with hub_inbox";
21
+ default: return undefined;
22
+ }
23
+ }
24
+
25
+ export function claudeHeldReason(peer: string): string {
26
+ return `another session is attached to the hub as "${peer}"; this one is standing by and takes the peer back when that session leaves`;
27
+ }
28
+
29
+ export function claudeOfflineText(peer: string, reason?: string): string {
30
+ return reason === "detached by the person"
31
+ ? `detached by the person; this session no longer acts as ${peer}. Stop here and tell the person. If they want this session back, start a fresh ahub claude.`
32
+ : reason ?? "hub is not running for this project (start it with: ahub up).";
33
+ }
34
+
35
+ /** How long a tool call waits for the hub to come back while it is being replaced (#1807 T4). */
36
+ const GAP_HOLD_MS = 30_000;
37
+
38
+ export function claudeGapText(peer: string): string {
39
+ return `the hub for this project is being replaced (upgrade or restart); this call was not run for ${peer}. Retry it; if it keeps failing, check ahub status.`;
40
+ }
41
+
42
+ /**
43
+ * Calls held while a connection that was served is re-established. `release` hands the held items back in arrival
44
+ * order, `expire` runs for an item that waited the whole hold. Nothing is held past `max` items, and a held item was
45
+ * never written to a socket, so it is safe to run later.
46
+ */
47
+ export function createGapHold<T>(options: { holdMs?: number; expire: (item: T) => void }) {
48
+ const held: { item: T; timer: ReturnType<typeof setTimeout> }[] = [];
49
+ return {
50
+ get size() { return held.length; },
51
+ add(item: T, room: number): boolean {
52
+ if (held.length >= room) return false;
53
+ const entry = { item, timer: setTimeout(() => { held.splice(held.indexOf(entry), 1); options.expire(item); }, options.holdMs ?? GAP_HOLD_MS) };
54
+ held.push(entry);
55
+ return true;
56
+ },
57
+ release(): T[] {
58
+ const items = held.splice(0).map(entry => { clearTimeout(entry.timer); return entry.item; });
59
+ return items;
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,255 @@
1
+ // The bundled plugin entry. The old stdio server is loaded only when the hub does not serve the endpoint.
2
+ import { lstatSync, readFileSync } from "node:fs";
3
+ import { createConnection, type Socket } from "node:net";
4
+ import { homedir } from "node:os";
5
+ import { dirname, isAbsolute, join, sep } from "node:path";
6
+ import { channelProjectBase, type ChannelProject } from "../hub/channel-project-base.ts";
7
+ import { claudeGapText, claudeHeldReason, claudeOfflineText, createGapHold, claudeReconnectDelay, claudeTerminalClose, HELD_CLOSE, WIRE_MISMATCH_CLOSE, WIRE_MISMATCH_REASON, WIRE_MISMATCH_RETRY_MS } from "./claude-connection-policy.ts";
8
+
9
+ const LINE_LIMIT = 1024 * 1024;
10
+ const REPLY_LIMIT = 8 * LINE_LIMIT;
11
+ const CONNECT_TIMEOUT_MS = 3_000;
12
+ const MAX_PENDING = 128;
13
+
14
+ type RequestId = string | number;
15
+ type Frame = { id?: unknown; method?: unknown; result?: unknown; error?: { message?: unknown; code?: unknown; data?: { closeCode?: unknown } } };
16
+ interface Descriptor { projectId: string; instanceId: string; cwd: string; mcpSocket: string; mcpServing?: boolean }
17
+ interface ConnectionEnd { code?: number; message?: string; served: boolean }
18
+ interface Connection { admitted: Promise<boolean>; ended: Promise<ConnectionEnd>; flushEarly(): void }
19
+
20
+ function readDescriptor(project: ChannelProject): Descriptor | undefined {
21
+ try {
22
+ const row = JSON.parse(readFileSync(join(project.stateDir, "status.json"), "utf8")) as Partial<Descriptor>;
23
+ if (typeof row.cwd !== "string" || typeof row.projectId !== "string" || typeof row.instanceId !== "string") return;
24
+ return row as Descriptor;
25
+ } catch { return undefined; }
26
+ }
27
+
28
+ function endpointPath(status: Descriptor): string | undefined {
29
+ if (status.mcpServing !== true || typeof status.mcpSocket !== "string" || !isAbsolute(status.mcpSocket) || !/^[a-zA-Z0-9_-]+$/.test(status.projectId)
30
+ || !status.mcpSocket.endsWith(`${sep}run${sep}${status.projectId}${sep}mcp.sock`)) return;
31
+ try {
32
+ const file = lstatSync(status.mcpSocket), parent = lstatSync(dirname(status.mcpSocket)), uid = process.getuid?.();
33
+ if (!file.isSocket() || !parent.isDirectory() || (file.mode & 0o777) !== 0o600 || (parent.mode & 0o777) !== 0o700) return;
34
+ if (uid !== undefined && (file.uid !== uid || parent.uid !== uid)) return;
35
+ return status.mcpSocket;
36
+ } catch { return undefined; }
37
+ }
38
+
39
+ function frame(line: string): Frame {
40
+ try { return JSON.parse(line) ?? {}; } catch { return {}; }
41
+ }
42
+ function requestId(value: unknown): value is RequestId {
43
+ return typeof value === "string" || typeof value === "number";
44
+ }
45
+
46
+ /** StringDecoder (via setEncoding) keeps UTF-8 splits intact; buffer only the current incomplete line. */
47
+ function lineReader(limit: number, line: (value: string) => void, overflow: () => void) {
48
+ let buffer = "", failed = false;
49
+ return (chunk: string) => {
50
+ if (failed) return;
51
+ const lines = chunk.split("\n");
52
+ buffer += lines.shift() ?? "";
53
+ for (const next of lines) {
54
+ if (Buffer.byteLength(buffer) > limit) { failed = true; return overflow(); }
55
+ if (buffer) line(buffer);
56
+ buffer = next;
57
+ }
58
+ if (Buffer.byteLength(buffer) > limit) { failed = true; overflow(); }
59
+ };
60
+ }
61
+
62
+ async function relay(project: ChannelProject, initial: Descriptor, peer: string): Promise<boolean> {
63
+ const tools = process.env.AGENTHUB_MODE === "tools";
64
+ const configuredHome = process.env.CLAUDE_CONFIG_DIR;
65
+ const cwd = process.cwd(), channelRequested = process.env.AGENTHUB_CHANNEL === "1";
66
+ const home = configuredHome && isAbsolute(configuredHome) ? configuredHome : join(homedir(), ".claude");
67
+ const nativeSession = process.env.CLAUDE_CODE_SESSION_ID, launchId = process.env.AGENTHUB_LAUNCH_ID;
68
+ const readyId = `ahub-relay-${crypto.randomUUID()}`;
69
+ let socket: Socket | undefined, ready = false, initialized = false, ownsStdio = false, stopped = false;
70
+ let previousInstance: string | undefined, terminal: string | undefined, standby = false, delayedReason: string | undefined;
71
+ let wake: (() => void) | undefined;
72
+ const pending = new Map<RequestId, string | undefined>();
73
+ // #1807 T4: while a served connection is being re-established, a new tool call waits instead of failing at once.
74
+ let reconnecting = false;
75
+ const gap = createGapHold<{ line: string; id: RequestId }>({ expire: held => fail(held.id, "tools/call", claudeGapText(peer)) });
76
+ const output = (line: string) => {
77
+ const current = socket;
78
+ if (!process.stdout.write(line + "\n") && current) {
79
+ current.pause();
80
+ process.stdout.once("drain", () => { if (!current.destroyed) current.resume(); });
81
+ }
82
+ };
83
+ const fail = (id: RequestId, method: unknown, message: string, sent = false) => {
84
+ const response = method === "tools/call" && !sent
85
+ ? { result: { content: [{ type: "text", text: message }], ...(terminal === "detached by the person" ? { isError: true } : {}) } }
86
+ : { error: { code: -32000, message } };
87
+ output(JSON.stringify({ jsonrpc: "2.0", id, ...response }));
88
+ };
89
+ const offline = () => claudeOfflineText(peer, terminal ?? delayedReason);
90
+ const forward = (line: string, request: Frame) => {
91
+ const id = request.id;
92
+ if (!socket || socket.destroyed || !ready || pending.size >= MAX_PENDING || socket.writableLength > LINE_LIMIT) {
93
+ if (reconnecting && !terminal && request.method === "tools/call" && requestId(id) && gap.add({ line, id }, MAX_PENDING - pending.size)) return;
94
+ if (requestId(id)) fail(id, request.method, offline());
95
+ return;
96
+ }
97
+ if (requestId(id) && typeof request.method === "string") pending.set(id, request.method);
98
+ socket.write(line + "\n");
99
+ };
100
+ const end = () => {
101
+ stopped = true;
102
+ process.stdin.pause();
103
+ wake?.();
104
+ socket?.destroy();
105
+ };
106
+ const delay = (ms: number) => new Promise<void>(resolve => {
107
+ const timer = setTimeout(() => { wake = undefined; resolve(); }, ms);
108
+ wake = () => { clearTimeout(timer); wake = undefined; resolve(); };
109
+ });
110
+
111
+ const connect = (status: Descriptor, path: string, token: string): Connection => {
112
+ let admit!: (value: boolean) => void, finish!: (value: ConnectionEnd) => void;
113
+ const admitted = new Promise<boolean>(resolve => { admit = resolve; });
114
+ const ended = new Promise<ConnectionEnd>(resolve => { finish = resolve; });
115
+ const link = createConnection(path);
116
+ socket = link;
117
+ let served = false, code: number | undefined, message: string | undefined, refused = false;
118
+ const earlyLines: string[] = [];
119
+ let earlyBytes = 0;
120
+ const flushEarly = () => {
121
+ if (!ownsStdio || link.destroyed) return;
122
+ earlyBytes = 0;
123
+ for (const early of earlyLines.splice(0)) output(early);
124
+ };
125
+ link.setEncoding("utf8");
126
+ const deadline = setTimeout(() => link.destroy(), CONNECT_TIMEOUT_MS);
127
+ link.on("error", () => link.destroy());
128
+ link.once("connect", () => {
129
+ const hello = { v: 1, mode: tools ? "tools" : "channel", relay: true, peer, pid: process.pid, ppid: process.ppid, cwd, home, token,
130
+ projectId: initial.projectId, instanceId: status.instanceId, projectRoot: initial.cwd, channelRequested, standby, reconnect: initialized,
131
+ ...(project.session ? { session: project.session.label } : {}),
132
+ ...(nativeSession && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(nativeSession) ? { claudeSessionId: nativeSession } : {}),
133
+ ...(launchId && launchId.length <= 128 ? { launchId } : {}),
134
+ ...(tools && process.env.AGENTHUB_PERMISSION_TOOL === "1" ? { permissionTool: true } : {}),
135
+ ...(process.env.AGENTHUB_DELIVERY_ONLY === "true" ? { deliveryOnly: true } : {}),
136
+ };
137
+ link.write(JSON.stringify(hello) + "\n" + JSON.stringify({ jsonrpc: "2.0", id: readyId, method: "ping" }) + "\n");
138
+ });
139
+ link.on("data", lineReader(REPLY_LIMIT, line => {
140
+ if (refused || link.destroyed) return;
141
+ const response = frame(line);
142
+ if (response.id === null && response.error?.code === -32000) {
143
+ code = Number.isSafeInteger(response.error.data?.closeCode) ? response.error.data?.closeCode as number : undefined;
144
+ message = typeof response.error.message === "string" ? response.error.message : undefined;
145
+ refused = true;
146
+ link.destroy();
147
+ return;
148
+ }
149
+ if (response.id === readyId) {
150
+ if (response.error || response.result === undefined) { link.destroy(); return; }
151
+ if (served) return;
152
+ clearTimeout(deadline);
153
+ ready = served = true;
154
+ admit(true);
155
+ delayedReason = undefined;
156
+ reconnecting = false;
157
+ if (initialized && previousInstance !== undefined && previousInstance !== status.instanceId)
158
+ output(JSON.stringify({ jsonrpc: "2.0", method: "notifications/tools/list_changed" }));
159
+ previousInstance = status.instanceId;
160
+ flushEarly();
161
+ // Held calls were never written to a socket: run them now, in arrival order.
162
+ if (ownsStdio) for (const held of gap.release()) forward(held.line, frame(held.line));
163
+ return;
164
+ }
165
+ if (!served || !ownsStdio) {
166
+ earlyBytes += Buffer.byteLength(line);
167
+ if (earlyBytes > REPLY_LIMIT) { link.destroy(); return; }
168
+ earlyLines.push(line);
169
+ return;
170
+ }
171
+ if (requestId(response.id)) {
172
+ if (pending.get(response.id) === "initialize" && !response.error) initialized = true;
173
+ pending.delete(response.id);
174
+ }
175
+ output(line);
176
+ }, () => link.destroy()));
177
+ link.once("close", () => {
178
+ clearTimeout(deadline);
179
+ ready = false;
180
+ socket = undefined;
181
+ admit(false);
182
+ finish({ served, code, message });
183
+ });
184
+ return { admitted, ended, flushEarly };
185
+ };
186
+
187
+ const connectTarget = (status: Descriptor | undefined): Connection | undefined => {
188
+ const path = status && endpointPath(status);
189
+ if (!status || !path) return;
190
+ try {
191
+ const token = readFileSync(join(project.stateDir, "control-token"), "utf8").trim();
192
+ return token ? connect(status, path, token) : undefined;
193
+ } catch { return undefined; }
194
+ };
195
+
196
+ // Choose before reading stdin. A stale descriptor or refused probe must leave initialize for the bridge.
197
+ if (project.root && project.root !== initial.cwd) return false;
198
+ let connection = connectTarget(initial);
199
+ if (!connection) return false;
200
+ if (!(await connection.admitted) || !ready) { await connection.ended; return false; }
201
+
202
+ ownsStdio = true;
203
+ process.stdin.setEncoding("utf8");
204
+ process.stdin.once("end", end);
205
+ process.stdin.once("close", end);
206
+ process.stdin.on("error", end);
207
+ process.stdout.on("error", end);
208
+ process.stdin.on("data", lineReader(LINE_LIMIT, line => forward(line, frame(line)), end));
209
+ connection.flushEarly();
210
+
211
+ for (let attempt = 0; !stopped && !terminal; attempt++) {
212
+ const ended = await connection?.ended;
213
+ if (stopped) break;
214
+ if (ended?.served) attempt = 0;
215
+ terminal = claudeTerminalClose(ended?.code, peer);
216
+ if (ended?.code === HELD_CLOSE) {
217
+ standby = true;
218
+ delayedReason = ended.message?.includes("off roster") ? `${peer} is off roster; a person can add it with ahub roster add ${peer}` : claudeHeldReason(peer);
219
+ } else if (ended?.code === WIRE_MISMATCH_CLOSE) delayedReason = WIRE_MISMATCH_REASON;
220
+ for (const [id, method] of pending) {
221
+ fail(id, method, terminal ? offline() : "Hub connection closed; the outcome may be unknown. Inspect the hub before repeating the request.", true);
222
+ }
223
+ pending.clear();
224
+ // A served connection that closed without a terminal, standby or wire-mismatch reason is a gap; the hold lasts until the next one is ready.
225
+ reconnecting = !terminal && ended?.code !== HELD_CLOSE && ended?.code !== WIRE_MISMATCH_CLOSE && (reconnecting || ended?.served === true);
226
+ if (!reconnecting) for (const held of gap.release()) fail(held.id, "tools/call", offline());
227
+ if (terminal) break;
228
+ await delay(ended?.code === WIRE_MISMATCH_CLOSE ? WIRE_MISMATCH_RETRY_MS : claudeReconnectDelay(attempt));
229
+ if (stopped) break;
230
+ const status = readDescriptor(project);
231
+ if (status && (status.projectId !== initial.projectId || status.cwd !== initial.cwd)) {
232
+ terminal = claudeTerminalClose(4404, peer);
233
+ for (const held of gap.release()) fail(held.id, "tools/call", offline());
234
+ break;
235
+ }
236
+ connection = connectTarget(status);
237
+ }
238
+ if (terminal && !stopped) console.error(`[agent-hub] stopped reconnecting: ${terminal}`);
239
+ return true;
240
+ }
241
+
242
+ async function resolveProject(): Promise<ChannelProject | undefined> {
243
+ const peer = process.env.AGENTHUB_PEER_ID;
244
+ if (process.env.AGENTHUB_MODE !== "tools" && peer && peer !== "claude" && process.env.AGENTHUB_PROJECT_DIR) {
245
+ const { channelProject, channelProjectRoles } = await import("../hub/channel-project.ts");
246
+ return channelProject(process.cwd(), process.env, channelProjectRoles);
247
+ }
248
+ return channelProjectBase(process.cwd(), process.env);
249
+ }
250
+
251
+ const project = await resolveProject();
252
+ const status = project && readDescriptor(project);
253
+ const peer = process.env.AGENTHUB_PEER_ID ?? (process.env.AGENTHUB_MODE === "tools" ? "" : "claude");
254
+ if (!project || !status || !/^[a-z][a-z0-9-]{0,31}$/.test(peer) || !(await relay(project, status, peer)))
255
+ await import("./claude-channel.ts");
@@ -1,8 +1,8 @@
1
+ import { sha256Hex as digest } from "../primitives.ts";
1
2
  import { isNativeModelToken } from "./model-token.ts";
2
3
  import { codexReviewerQuota } from "./definitions/native-quota.ts";
3
4
  import { DENY_NAMES, DENY_SEGMENTS } from "@staix/agent-mem/platform";
4
5
  import { assessVersion, COMPAT } from "./compat.ts";
5
- import { createHash } from "node:crypto";
6
6
  import { spawn } from "node:child_process";
7
7
  import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
8
8
  import { createRequire } from "node:module";
@@ -16,7 +16,6 @@ const TOOLS = ["hub_review", "hub_task_show"];
16
16
  /** A version refusal names only versions and a command, so the daemon may show it (#691). */
17
17
  class VersionRefusal extends Error {}
18
18
  const CAP = 128 * 1024, MAX_SERVERS = 64;
19
- const digest = (value: string | Buffer) => createHash("sha256").update(value).digest("hex");
20
19
  /** Conservative translation of the portable core's regex sources; unfamiliar syntax refuses the receipt. */
21
20
  export function codexCoreDenyGlobs(names: readonly string[] = DENY_NAMES, segments: readonly string[] = DENY_SEGMENTS): string[] {
22
21
  if (names.length > 64 || segments.length > 64) throw new Error("core deny policy bound exceeded");