@namzu/sdk 68.0.1 → 69.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/bridge/acp/server.d.ts +12 -0
  3. package/dist/bridge/acp/server.d.ts.map +1 -1
  4. package/dist/bridge/acp/server.js +20 -0
  5. package/dist/bridge/acp/server.js.map +1 -1
  6. package/dist/compaction/context-window.d.ts +8 -0
  7. package/dist/compaction/context-window.d.ts.map +1 -1
  8. package/dist/compaction/context-window.js +14 -0
  9. package/dist/compaction/context-window.js.map +1 -1
  10. package/dist/compaction/loaded-skills.d.ts +10 -0
  11. package/dist/compaction/loaded-skills.d.ts.map +1 -1
  12. package/dist/compaction/loaded-skills.js +45 -1
  13. package/dist/compaction/loaded-skills.js.map +1 -1
  14. package/dist/compaction/manager.d.ts +8 -0
  15. package/dist/compaction/manager.d.ts.map +1 -1
  16. package/dist/compaction/manager.js +31 -0
  17. package/dist/compaction/manager.js.map +1 -1
  18. package/dist/compaction/manual.d.ts.map +1 -1
  19. package/dist/compaction/manual.js +7 -1
  20. package/dist/compaction/manual.js.map +1 -1
  21. package/dist/compaction/model-summary.js +2 -2
  22. package/dist/compaction/model-summary.js.map +1 -1
  23. package/dist/compaction/restore.d.ts +8 -0
  24. package/dist/compaction/restore.d.ts.map +1 -1
  25. package/dist/compaction/restore.js +65 -0
  26. package/dist/compaction/restore.js.map +1 -1
  27. package/dist/compaction/salience/working-set.d.ts.map +1 -1
  28. package/dist/compaction/salience/working-set.js +2 -2
  29. package/dist/compaction/salience/working-set.js.map +1 -1
  30. package/dist/compaction/tool-result-editing.d.ts +6 -0
  31. package/dist/compaction/tool-result-editing.d.ts.map +1 -1
  32. package/dist/compaction/tool-result-editing.js +7 -1
  33. package/dist/compaction/tool-result-editing.js.map +1 -1
  34. package/dist/compaction/types.d.ts +2 -0
  35. package/dist/compaction/types.d.ts.map +1 -1
  36. package/dist/compaction/wire.d.ts.map +1 -1
  37. package/dist/compaction/wire.js +4 -0
  38. package/dist/compaction/wire.js.map +1 -1
  39. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  40. package/dist/manager/session/turn-recorder.js +23 -1
  41. package/dist/manager/session/turn-recorder.js.map +1 -1
  42. package/dist/network/join.d.ts +10 -0
  43. package/dist/network/join.d.ts.map +1 -1
  44. package/dist/network/join.js +15 -0
  45. package/dist/network/join.js.map +1 -1
  46. package/dist/network/service.d.ts.map +1 -1
  47. package/dist/network/service.js +166 -12
  48. package/dist/network/service.js.map +1 -1
  49. package/dist/network/store.d.ts +23 -1
  50. package/dist/network/store.d.ts.map +1 -1
  51. package/dist/network/store.js +23 -1
  52. package/dist/network/store.js.map +1 -1
  53. package/dist/network/transport.d.ts +1 -1
  54. package/dist/network/transport.js +1 -1
  55. package/dist/network/wire.d.ts +12 -0
  56. package/dist/network/wire.d.ts.map +1 -1
  57. package/dist/network/wire.js +12 -1
  58. package/dist/network/wire.js.map +1 -1
  59. package/dist/prompt/coding-agent-doctrine.d.ts +4 -4
  60. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  61. package/dist/prompt/coding-agent-doctrine.js +7 -2
  62. package/dist/prompt/coding-agent-doctrine.js.map +1 -1
  63. package/dist/provider/fallback.d.ts.map +1 -1
  64. package/dist/provider/fallback.js +5 -0
  65. package/dist/provider/fallback.js.map +1 -1
  66. package/dist/provider/idle-timeout.d.ts.map +1 -1
  67. package/dist/provider/idle-timeout.js +5 -0
  68. package/dist/provider/idle-timeout.js.map +1 -1
  69. package/dist/provider/instrumentation.d.ts.map +1 -1
  70. package/dist/provider/instrumentation.js +10 -0
  71. package/dist/provider/instrumentation.js.map +1 -1
  72. package/dist/provider/model-window-suffix.d.ts.map +1 -1
  73. package/dist/provider/model-window-suffix.js +1 -0
  74. package/dist/provider/model-window-suffix.js.map +1 -1
  75. package/dist/provider/retry.d.ts.map +1 -1
  76. package/dist/provider/retry.js +5 -0
  77. package/dist/provider/retry.js.map +1 -1
  78. package/dist/public-runtime.d.ts +1 -1
  79. package/dist/public-runtime.d.ts.map +1 -1
  80. package/dist/public-runtime.js +1 -1
  81. package/dist/public-runtime.js.map +1 -1
  82. package/dist/public-tools.d.ts +2 -0
  83. package/dist/public-tools.d.ts.map +1 -1
  84. package/dist/public-tools.js +4 -0
  85. package/dist/public-tools.js.map +1 -1
  86. package/dist/public-types.d.ts +1 -0
  87. package/dist/public-types.d.ts.map +1 -1
  88. package/dist/registry/tool/presentation.d.ts +8 -1
  89. package/dist/registry/tool/presentation.d.ts.map +1 -1
  90. package/dist/registry/tool/presentation.js +14 -5
  91. package/dist/registry/tool/presentation.js.map +1 -1
  92. package/dist/runtime/jobs/registry.d.ts.map +1 -1
  93. package/dist/runtime/jobs/registry.js +2 -1
  94. package/dist/runtime/jobs/registry.js.map +1 -1
  95. package/dist/runtime/query/auto-review/classifier.d.ts.map +1 -1
  96. package/dist/runtime/query/auto-review/classifier.js +19 -3
  97. package/dist/runtime/query/auto-review/classifier.js.map +1 -1
  98. package/dist/runtime/query/auto-review/failure.d.ts +12 -0
  99. package/dist/runtime/query/auto-review/failure.d.ts.map +1 -0
  100. package/dist/runtime/query/auto-review/failure.js +46 -0
  101. package/dist/runtime/query/auto-review/failure.js.map +1 -0
  102. package/dist/runtime/query/auto-review/index.d.ts +1 -0
  103. package/dist/runtime/query/auto-review/index.d.ts.map +1 -1
  104. package/dist/runtime/query/auto-review/index.js +1 -0
  105. package/dist/runtime/query/auto-review/index.js.map +1 -1
  106. package/dist/runtime/query/file-evidence-replay.d.ts.map +1 -1
  107. package/dist/runtime/query/file-evidence-replay.js +6 -6
  108. package/dist/runtime/query/file-evidence-replay.js.map +1 -1
  109. package/dist/runtime/query/index.d.ts.map +1 -1
  110. package/dist/runtime/query/index.js +8 -1
  111. package/dist/runtime/query/index.js.map +1 -1
  112. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  113. package/dist/runtime/query/iteration/index.js +2 -0
  114. package/dist/runtime/query/iteration/index.js.map +1 -1
  115. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  116. package/dist/runtime/query/iteration/phases/compaction.js +21 -3
  117. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  118. package/dist/runtime/query/iteration/phases/context.d.ts +4 -0
  119. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  120. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  121. package/dist/runtime/query/iteration/phases/per-call-review.d.ts +6 -2
  122. package/dist/runtime/query/iteration/phases/per-call-review.d.ts.map +1 -1
  123. package/dist/runtime/query/iteration/phases/per-call-review.js +24 -9
  124. package/dist/runtime/query/iteration/phases/per-call-review.js.map +1 -1
  125. package/dist/runtime/query/iteration/step-shaping.d.ts.map +1 -1
  126. package/dist/runtime/query/iteration/step-shaping.js +4 -0
  127. package/dist/runtime/query/iteration/step-shaping.js.map +1 -1
  128. package/dist/runtime/query/prepare-turn.d.ts +5 -1
  129. package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
  130. package/dist/runtime/query/prepare-turn.js +13 -3
  131. package/dist/runtime/query/prepare-turn.js.map +1 -1
  132. package/dist/runtime/query/review-policy.d.ts +13 -2
  133. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  134. package/dist/runtime/query/review-policy.js +13 -2
  135. package/dist/runtime/query/review-policy.js.map +1 -1
  136. package/dist/runtime/query/turn/outcome-ledger.d.ts +4 -0
  137. package/dist/runtime/query/turn/outcome-ledger.d.ts.map +1 -1
  138. package/dist/runtime/query/turn/outcome-ledger.js +36 -1
  139. package/dist/runtime/query/turn/outcome-ledger.js.map +1 -1
  140. package/dist/sandbox/provider/local.d.ts.map +1 -1
  141. package/dist/sandbox/provider/local.js +3 -1
  142. package/dist/sandbox/provider/local.js.map +1 -1
  143. package/dist/tools/admit-facts.d.ts.map +1 -1
  144. package/dist/tools/admit-facts.js +20 -0
  145. package/dist/tools/admit-facts.js.map +1 -1
  146. package/dist/tools/builtins/bash.d.ts.map +1 -1
  147. package/dist/tools/builtins/bash.js +5 -2
  148. package/dist/tools/builtins/bash.js.map +1 -1
  149. package/dist/tools/builtins/browser.js +1 -1
  150. package/dist/tools/builtins/browser.js.map +1 -1
  151. package/dist/tools/builtins/computer-use.d.ts +4 -0
  152. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  153. package/dist/tools/builtins/computer-use.js +106 -5
  154. package/dist/tools/builtins/computer-use.js.map +1 -1
  155. package/dist/tools/builtins/content-fingerprint.d.ts.map +1 -1
  156. package/dist/tools/builtins/content-fingerprint.js +2 -1
  157. package/dist/tools/builtins/content-fingerprint.js.map +1 -1
  158. package/dist/tools/builtins/edit-apply.d.ts +1 -0
  159. package/dist/tools/builtins/edit-apply.d.ts.map +1 -1
  160. package/dist/tools/builtins/edit-apply.js +108 -21
  161. package/dist/tools/builtins/edit-apply.js.map +1 -1
  162. package/dist/tools/builtins/edit-match.d.ts +37 -0
  163. package/dist/tools/builtins/edit-match.d.ts.map +1 -1
  164. package/dist/tools/builtins/edit-match.js +193 -0
  165. package/dist/tools/builtins/edit-match.js.map +1 -1
  166. package/dist/tools/builtins/edit.d.ts.map +1 -1
  167. package/dist/tools/builtins/edit.js +14 -7
  168. package/dist/tools/builtins/edit.js.map +1 -1
  169. package/dist/tools/builtins/exit-semantics.d.ts +8 -0
  170. package/dist/tools/builtins/exit-semantics.d.ts.map +1 -1
  171. package/dist/tools/builtins/exit-semantics.js +19 -0
  172. package/dist/tools/builtins/exit-semantics.js.map +1 -1
  173. package/dist/tools/builtins/index.d.ts +2 -0
  174. package/dist/tools/builtins/index.d.ts.map +1 -1
  175. package/dist/tools/builtins/index.js +1 -0
  176. package/dist/tools/builtins/index.js.map +1 -1
  177. package/dist/tools/builtins/present-file.d.ts +24 -0
  178. package/dist/tools/builtins/present-file.d.ts.map +1 -0
  179. package/dist/tools/builtins/present-file.js +116 -0
  180. package/dist/tools/builtins/present-file.js.map +1 -0
  181. package/dist/tools/builtins/read-file.js +1 -1
  182. package/dist/tools/builtins/read-file.js.map +1 -1
  183. package/dist/tools/builtins/read-render.d.ts +12 -1
  184. package/dist/tools/builtins/read-render.d.ts.map +1 -1
  185. package/dist/tools/builtins/read-render.js +16 -3
  186. package/dist/tools/builtins/read-render.js.map +1 -1
  187. package/dist/tools/builtins/search-tools.d.ts +10 -0
  188. package/dist/tools/builtins/search-tools.d.ts.map +1 -1
  189. package/dist/tools/builtins/search-tools.js +36 -2
  190. package/dist/tools/builtins/search-tools.js.map +1 -1
  191. package/dist/tools/builtins/wait-for-job.d.ts.map +1 -1
  192. package/dist/tools/builtins/wait-for-job.js +5 -0
  193. package/dist/tools/builtins/wait-for-job.js.map +1 -1
  194. package/dist/tools/builtins/web.d.ts.map +1 -1
  195. package/dist/tools/builtins/web.js +13 -2
  196. package/dist/tools/builtins/web.js.map +1 -1
  197. package/dist/tools/task/create.js +2 -2
  198. package/dist/tools/task/create.js.map +1 -1
  199. package/dist/tools/task/update.js +1 -1
  200. package/dist/tools/task/update.js.map +1 -1
  201. package/dist/types/provider/chat.d.ts +8 -0
  202. package/dist/types/provider/chat.d.ts.map +1 -1
  203. package/dist/types/provider/interface.d.ts +10 -0
  204. package/dist/types/provider/interface.d.ts.map +1 -1
  205. package/dist/types/provider/model.d.ts +6 -0
  206. package/dist/types/provider/model.d.ts.map +1 -1
  207. package/dist/types/provider/stream.d.ts +2 -0
  208. package/dist/types/provider/stream.d.ts.map +1 -1
  209. package/dist/types/tool/presentation.d.ts +11 -0
  210. package/dist/types/tool/presentation.d.ts.map +1 -1
  211. package/dist/utils/node-on-path.d.ts +27 -0
  212. package/dist/utils/node-on-path.d.ts.map +1 -0
  213. package/dist/utils/node-on-path.js +70 -0
  214. package/dist/utils/node-on-path.js.map +1 -0
  215. package/package.json +1 -1
  216. package/src/bridge/acp/server.ts +25 -0
  217. package/src/compaction/context-window.ts +18 -0
  218. package/src/compaction/loaded-skills.ts +42 -1
  219. package/src/compaction/manager.ts +28 -0
  220. package/src/compaction/manual.ts +9 -1
  221. package/src/compaction/model-summary.ts +2 -2
  222. package/src/compaction/restore.ts +69 -0
  223. package/src/compaction/salience/working-set.ts +6 -2
  224. package/src/compaction/tool-result-editing.ts +8 -1
  225. package/src/compaction/types.ts +2 -0
  226. package/src/compaction/wire.ts +4 -0
  227. package/src/manager/session/turn-recorder.ts +24 -1
  228. package/src/network/join.ts +17 -0
  229. package/src/network/service.ts +185 -12
  230. package/src/network/store.ts +28 -1
  231. package/src/network/transport.ts +1 -1
  232. package/src/network/wire.ts +13 -1
  233. package/src/prompt/coding-agent-doctrine.ts +7 -2
  234. package/src/provider/fallback.ts +6 -0
  235. package/src/provider/idle-timeout.ts +6 -0
  236. package/src/provider/instrumentation.ts +12 -0
  237. package/src/provider/model-window-suffix.ts +1 -0
  238. package/src/provider/retry.ts +6 -0
  239. package/src/public-runtime.ts +1 -0
  240. package/src/public-tools.ts +9 -0
  241. package/src/public-types.ts +1 -0
  242. package/src/registry/tool/presentation.ts +14 -4
  243. package/src/runtime/jobs/registry.ts +2 -1
  244. package/src/runtime/query/auto-review/classifier.ts +19 -3
  245. package/src/runtime/query/auto-review/failure.ts +50 -0
  246. package/src/runtime/query/auto-review/index.ts +1 -0
  247. package/src/runtime/query/file-evidence-replay.ts +6 -5
  248. package/src/runtime/query/index.ts +19 -0
  249. package/src/runtime/query/iteration/index.ts +2 -0
  250. package/src/runtime/query/iteration/phases/compaction.ts +25 -2
  251. package/src/runtime/query/iteration/phases/context.ts +4 -0
  252. package/src/runtime/query/iteration/phases/per-call-review.ts +24 -7
  253. package/src/runtime/query/iteration/step-shaping.ts +4 -0
  254. package/src/runtime/query/prepare-turn.ts +20 -2
  255. package/src/runtime/query/review-policy.ts +24 -4
  256. package/src/runtime/query/turn/outcome-ledger.ts +45 -1
  257. package/src/sandbox/provider/local.ts +3 -1
  258. package/src/tools/admit-facts.ts +18 -0
  259. package/src/tools/builtins/bash.ts +5 -2
  260. package/src/tools/builtins/browser.ts +1 -1
  261. package/src/tools/builtins/computer-use.ts +123 -4
  262. package/src/tools/builtins/content-fingerprint.ts +2 -1
  263. package/src/tools/builtins/edit-apply.ts +124 -24
  264. package/src/tools/builtins/edit-match.ts +200 -0
  265. package/src/tools/builtins/edit.ts +16 -7
  266. package/src/tools/builtins/exit-semantics.ts +23 -0
  267. package/src/tools/builtins/index.ts +2 -0
  268. package/src/tools/builtins/present-file.ts +127 -0
  269. package/src/tools/builtins/read-file.ts +1 -1
  270. package/src/tools/builtins/read-render.ts +18 -3
  271. package/src/tools/builtins/search-tools.ts +36 -2
  272. package/src/tools/builtins/wait-for-job.ts +5 -0
  273. package/src/tools/builtins/web.ts +15 -2
  274. package/src/tools/task/create.ts +2 -2
  275. package/src/tools/task/update.ts +1 -1
  276. package/src/types/provider/chat.ts +9 -0
  277. package/src/types/provider/interface.ts +11 -0
  278. package/src/types/provider/model.ts +6 -0
  279. package/src/types/provider/stream.ts +2 -0
  280. package/src/types/tool/presentation.ts +12 -0
  281. package/src/utils/node-on-path.ts +81 -0
@@ -28,7 +28,7 @@ import { systemClock } from './clock.js';
28
28
  import { isPrivateNetworkAddress, privateInterfaces, } from './discovery.js';
29
29
  import { createNetworkIdentity, createSystemGatewayReader } from './fingerprint.js';
30
30
  import { generateMachineKey, machineIdOf, shortMachineId } from './identity.js';
31
- import { JoinTable, formatJoinCode, joinCode } from './join.js';
31
+ import { JOIN_BACKOFF_DENIED_MS, JOIN_BACKOFF_OTHER_MS, JOIN_EXPIRY_MS, JOIN_ORPHAN_MS, JoinTable, formatJoinCode, joinCode, } from './join.js';
32
32
  import { HoldQueue, SlidingCounter, TokenBuckets, decideMail, } from './mail-policy.js';
33
33
  import { AdmissionSchema, RevocationSchema, admittedBy, createFounding, evaluateMembership, mergeMembership, signAdmission, signRevocation, } from './membership.js';
34
34
  import { offlineSessions, resolveSessionTarget, } from './roster.js';
@@ -155,6 +155,10 @@ export function createNamzuNetwork(options) {
155
155
  const peerState = new Map();
156
156
  const nearby = new Map();
157
157
  const pendingConns = new Map();
158
+ /** Cancels for the timers of requests whose connection dropped. */
159
+ const orphanTimers = new Map();
160
+ /** What a waiting request was made of, so the same machine asking again with the same nonce gets the same code. */
161
+ const askNonces = new Map();
158
162
  const sent = new Map();
159
163
  const seenMail = [];
160
164
  const inFlight = new Set();
@@ -162,6 +166,7 @@ export function createNamzuNetwork(options) {
162
166
  let cancelBrowse;
163
167
  let cancelRecheck;
164
168
  let joining = false;
169
+ let joinEndpoint;
165
170
  let joinClient;
166
171
  let joinCancelled = false;
167
172
  let foundedAt;
@@ -743,6 +748,8 @@ export function createNamzuNetwork(options) {
743
748
  return;
744
749
  if (clock.now() - foundedAt > FRESH_NETWORK_MS)
745
750
  return;
751
+ if (await backingOff(endpoint.netId))
752
+ return;
746
753
  const keyText = `${endpoint.host}:${endpoint.port}`;
747
754
  if (probing.has(keyText))
748
755
  return;
@@ -782,7 +789,7 @@ export function createNamzuNetwork(options) {
782
789
  return;
783
790
  declinedNets.add(endpoint.netId);
784
791
  emit({ type: 'nearby', networks: [endpoint.netId] });
785
- await join({ host: endpoint.host, port: endpoint.port }).catch(() => undefined);
792
+ await joinNetwork({ host: endpoint.host, port: endpoint.port }, endpoint.netId).catch(() => undefined);
786
793
  }
787
794
  async function afterBrowse() {
788
795
  cancelBrowse = undefined;
@@ -793,8 +800,12 @@ export function createNamzuNetwork(options) {
793
800
  return found();
794
801
  if (nets.length === 1) {
795
802
  const target = nearby.get(nets[0])[0];
803
+ if (await backingOff(target.netId)) {
804
+ setState('searching', 'This machine asked to join a Namzu network lately; it will not ask again yet.');
805
+ return;
806
+ }
796
807
  setState('searching', 'Asking to join a Namzu network nearby.');
797
- void join({ host: target.host, port: target.port }).catch(() => undefined);
808
+ void joinNetwork({ host: target.host, port: target.port }, target.netId).catch(() => undefined);
798
809
  return;
799
810
  }
800
811
  setState('ambiguous', `Found ${nets.length} Namzu networks nearby.`);
@@ -892,7 +903,26 @@ export function createNamzuNetwork(options) {
892
903
  };
893
904
  cancelRecheck = clock.setTimer(tick, INTERFACE_RECHECK_MS);
894
905
  }
895
- async function join(endpoint) {
906
+ /**
907
+ * Whether this machine asked `target` lately and was told no (or never answered): the ask is one per
908
+ * machine, kept in the machine's own network directory, so a terminal that opens later, or takes the
909
+ * lead from one that closed, does not ask again at once. A person's own `join` never waits on this.
910
+ */
911
+ async function backingOff(target) {
912
+ const attempt = await store.readJoinAttempt().catch(() => undefined);
913
+ if (attempt?.status !== 'ok')
914
+ return false;
915
+ const { value } = attempt;
916
+ if (value.target !== target || !value.result || value.endedAt === undefined)
917
+ return false;
918
+ const wait = value.result === 'denied' ? JOIN_BACKOFF_DENIED_MS : JOIN_BACKOFF_OTHER_MS;
919
+ return clock.now() - value.endedAt < wait;
920
+ }
921
+ /** A person's request: asks now, whatever happened to an earlier ask. */
922
+ function join(endpoint) {
923
+ return joinNetwork(endpoint, undefined);
924
+ }
925
+ async function joinNetwork(endpoint, netIdHint) {
896
926
  if (!tls || !key)
897
927
  throw new NetworkError('off', 'The Namzu network is not running.');
898
928
  if (view && view.members.size > 1)
@@ -901,7 +931,37 @@ export function createNamzuNetwork(options) {
901
931
  throw new NetworkError('invalid', 'A request to join is already waiting.');
902
932
  joining = true;
903
933
  const publicKey = key.publicKeyDer.toString('base64');
904
- const nonce = randomBytes(16).toString('base64');
934
+ // One ask per machine and network: while it waits, a repeat (another terminal, a restart) uses the
935
+ // same nonce, so the machine asked finds the same request and shows the same code.
936
+ // A person's ask only knows the address until the member answers; the record is then keyed by the
937
+ // network id, so a refusal of a person's ask backs the machine's own asks off like any other.
938
+ let target = netIdHint ?? `${endpoint.host}:${endpoint.port}`;
939
+ const prior = await store.readJoinAttempt().catch(() => undefined);
940
+ const reuse = prior?.status === 'ok' &&
941
+ prior.value.target === target &&
942
+ prior.value.result === undefined &&
943
+ clock.now() - prior.value.startedAt < JOIN_EXPIRY_MS;
944
+ const nonce = reuse && prior?.status === 'ok' ? prior.value.nonce : randomBytes(16).toString('base64');
945
+ if (!reuse)
946
+ await store
947
+ .writeJoinAttempt({ v: 1, target, nonce, startedAt: clock.now() })
948
+ .catch(() => undefined);
949
+ const settle = async (result) => {
950
+ if (result === 'joined' || result === 'cancelled') {
951
+ await store.clearJoinAttempt().catch(() => undefined);
952
+ return;
953
+ }
954
+ await store
955
+ .writeJoinAttempt({
956
+ v: 1,
957
+ target,
958
+ nonce,
959
+ startedAt: reuse && prior?.status === 'ok' ? prior.value.startedAt : clock.now(),
960
+ result,
961
+ endedAt: clock.now(),
962
+ })
963
+ .catch(() => undefined);
964
+ };
905
965
  let client;
906
966
  joinCancelled = false;
907
967
  try {
@@ -910,6 +970,7 @@ export function createNamzuNetwork(options) {
910
970
  client = await dialNet({ identity: tls, host: endpoint.host, port: endpoint.port, clock });
911
971
  }
912
972
  joinClient = client;
973
+ joinEndpoint = endpoint;
913
974
  const first = await client.request({
914
975
  protocol: NET_PROTOCOL,
915
976
  op: 'join_request',
@@ -920,6 +981,7 @@ export function createNamzuNetwork(options) {
920
981
  const pending = PendingFrameSchema.safeParse(first);
921
982
  if (!pending.success) {
922
983
  const reason = EndFrameSchema.safeParse(first);
984
+ await settle('refused');
923
985
  emit({
924
986
  type: 'join-ended',
925
987
  result: 'refused',
@@ -927,6 +989,7 @@ export function createNamzuNetwork(options) {
927
989
  });
928
990
  return 'refused';
929
991
  }
992
+ target = pending.data.netId;
930
993
  const code = joinCode(key.machineId, client.peer.machineId, nonce, pending.data.nonce);
931
994
  emit({ type: 'join-waiting', code, shownCode: formatJoinCode(code), endpoint });
932
995
  let final;
@@ -936,6 +999,7 @@ export function createNamzuNetwork(options) {
936
999
  catch (error) {
937
1000
  if (!joinCancelled)
938
1001
  throw error;
1002
+ await settle('cancelled');
939
1003
  emit({ type: 'join-ended', result: 'cancelled' });
940
1004
  return 'cancelled';
941
1005
  }
@@ -949,11 +1013,13 @@ export function createNamzuNetwork(options) {
949
1013
  ? 'expired'
950
1014
  : 'refused'
951
1015
  : 'refused';
1016
+ await settle(result);
952
1017
  emit({ type: 'join-ended', result, reason: end.success ? end.data.reason : undefined });
953
1018
  return result;
954
1019
  }
955
1020
  const verdict = evaluateMembership({ admissions: admitted.data.admissions, revocations: admitted.data.revocations }, pending.data.netId);
956
1021
  if (verdict.netId !== pending.data.netId || !verdict.members.has(key.machineId)) {
1022
+ await settle('refused');
957
1023
  emit({
958
1024
  type: 'join-ended',
959
1025
  result: 'refused',
@@ -968,6 +1034,7 @@ export function createNamzuNetwork(options) {
968
1034
  netId = verdict.netId;
969
1035
  foundedAt = undefined;
970
1036
  await persistMembership();
1037
+ await settle('joined');
971
1038
  for (const p of admitted.data.peers) {
972
1039
  if (p.machineId === key.machineId)
973
1040
  continue;
@@ -990,6 +1057,7 @@ export function createNamzuNetwork(options) {
990
1057
  finally {
991
1058
  joining = false;
992
1059
  joinClient = undefined;
1060
+ joinEndpoint = undefined;
993
1061
  client?.close();
994
1062
  }
995
1063
  }
@@ -998,6 +1066,19 @@ export function createNamzuNetwork(options) {
998
1066
  return false;
999
1067
  joinCancelled = true;
1000
1068
  joinClient.close();
1069
+ // Closing alone leaves the request waiting on the other machine; say that it is withdrawn.
1070
+ const at = joinEndpoint;
1071
+ if (tls && at)
1072
+ void dialNet({ identity: tls, host: at.host, port: at.port, clock })
1073
+ .then(async (client) => {
1074
+ try {
1075
+ await client.request({ protocol: NET_PROTOCOL, op: 'join_cancel' });
1076
+ }
1077
+ finally {
1078
+ client.close();
1079
+ }
1080
+ })
1081
+ .catch(() => undefined);
1001
1082
  return true;
1002
1083
  }
1003
1084
  // ─── request handling ──────────────────────────────────────────────────
@@ -1051,6 +1132,13 @@ export function createNamzuNetwork(options) {
1051
1132
  : { ok: true };
1052
1133
  case 'join_request':
1053
1134
  return handleJoinRequest(request, ctx);
1135
+ case 'join_cancel': {
1136
+ // Only the machine that asked can withdraw its own request, and only the one it asked here.
1137
+ const waiting = joiners.findByJoiner(peerId);
1138
+ if (waiting?.local)
1139
+ retireJoin(waiting);
1140
+ return { ok: true };
1141
+ }
1054
1142
  case 'hello': {
1055
1143
  const p = peerState.get(peerId) ?? {
1056
1144
  name: request.machineName,
@@ -1071,6 +1159,12 @@ export function createNamzuNetwork(options) {
1071
1159
  return { admissions: adm, revocations: rev };
1072
1160
  }
1073
1161
  case 'join_pending': {
1162
+ // The same machine asking through another member replaces what was waiting from it.
1163
+ const earlier = joiners.findByJoiner(machineIdOf(Buffer.from(request.publicKey, 'base64')));
1164
+ if (earlier && !earlier.local && earlier.requestId !== request.requestId) {
1165
+ joiners.settle(earlier.requestId, 'deny');
1166
+ emit({ type: 'join-settled', requestId: earlier.requestId, result: 'deny' });
1167
+ }
1074
1168
  const created = joiners.addRemote({
1075
1169
  requestId: request.requestId,
1076
1170
  name: sanitizeName(request.name),
@@ -1108,6 +1202,26 @@ export function createNamzuNetwork(options) {
1108
1202
  return { ...admittedFrame() };
1109
1203
  if (view.removed.has(joinerId))
1110
1204
  return { status: 'refused', reason: 'This machine was removed from the network.' };
1205
+ // A machine has one request waiting, however many times it asks: the same ask again (same nonce,
1206
+ // as when another terminal of that machine takes over) keeps the request and its code and only
1207
+ // takes over the held connection; a different ask replaces the old one.
1208
+ const prior = joiners.findByJoiner(joinerId);
1209
+ const known = prior ? askNonces.get(prior.requestId) : undefined;
1210
+ if (prior?.local && known && known.joinerNonce === request.nonce) {
1211
+ const old = pendingConns.get(prior.requestId);
1212
+ pendingConns.set(prior.requestId, ctx);
1213
+ ctx.holdOpen();
1214
+ watchHeld(prior.requestId, ctx);
1215
+ ctx.write({ status: 'pending', nonce: known.memberNonce, netId });
1216
+ old?.close();
1217
+ return undefined;
1218
+ }
1219
+ // A different ask is a new request and meets the same one-a-minute limit as any address; check
1220
+ // before the old one is retired, so a refused ask leaves it standing.
1221
+ if (joiners.tooSoon(ctx.sourceAddress))
1222
+ return { status: 'refused', reason: 'Asked again too soon.' };
1223
+ if (prior)
1224
+ retireJoin(prior);
1111
1225
  const auto = await autoAdmitMode(ctx.sourceAddress).catch(() => undefined);
1112
1226
  const nonceM = randomBytes(16).toString('base64');
1113
1227
  const code = joinCode(joinerId, selfId(), request.nonce, nonceM);
@@ -1126,15 +1240,14 @@ export function createNamzuNetwork(options) {
1126
1240
  status: 'refused',
1127
1241
  reason: added.reason === 'rate' ? 'Asked again too soon.' : 'Too many requests are waiting.',
1128
1242
  };
1243
+ askNonces.set(requestId, { joinerNonce: request.nonce, memberNonce: nonceM });
1244
+ if (askNonces.size > 64)
1245
+ for (const id of askNonces.keys())
1246
+ if (!joiners.get(id))
1247
+ askNonces.delete(id);
1129
1248
  ctx.holdOpen();
1130
1249
  pendingConns.set(requestId, ctx);
1131
- ctx.onClose(() => {
1132
- pendingConns.delete(requestId);
1133
- if (joiners.get(requestId)) {
1134
- joiners.settle(requestId, 'deny');
1135
- emit({ type: 'join-settled', requestId, result: 'deny' });
1136
- }
1137
- });
1250
+ watchHeld(requestId, ctx);
1138
1251
  // The joiner must read `pending` before any decision can reach it, so write it first.
1139
1252
  ctx.write({ status: 'pending', nonce: nonceM, netId });
1140
1253
  logAudit({
@@ -1166,6 +1279,42 @@ export function createNamzuNetwork(options) {
1166
1279
  void gossipPending(added.entry, request.publicKey);
1167
1280
  return undefined;
1168
1281
  }
1282
+ /**
1283
+ * A waiting request outlives its connection: the terminal of the joining machine that asked may close
1284
+ * (another one of the same machine asks again and finds the same request and code), and an Allow given
1285
+ * meanwhile still lets the machine in. It ends by an answer, by the joiner's `join_cancel`, by a
1286
+ * newer request from the same machine, or by its ten minutes.
1287
+ */
1288
+ function watchHeld(requestId, ctx) {
1289
+ orphanTimers.get(requestId)?.();
1290
+ orphanTimers.delete(requestId);
1291
+ ctx.onClose(() => {
1292
+ if (pendingConns.get(requestId) !== ctx)
1293
+ return;
1294
+ pendingConns.delete(requestId);
1295
+ // Long enough for another terminal of the machine to take over; a stranger that asks and leaves
1296
+ // does not keep a slot for ten minutes.
1297
+ orphanTimers.set(requestId, clock.setTimer(() => {
1298
+ orphanTimers.delete(requestId);
1299
+ const entry = joiners.get(requestId);
1300
+ if (entry?.local && !pendingConns.has(requestId))
1301
+ retireJoin(entry);
1302
+ }, JOIN_ORPHAN_MS));
1303
+ });
1304
+ }
1305
+ /** A request that a newer one from the same machine replaced: gone from every screen, nobody told it no. */
1306
+ function retireJoin(entry) {
1307
+ orphanTimers.get(entry.requestId)?.();
1308
+ orphanTimers.delete(entry.requestId);
1309
+ const conn = pendingConns.get(entry.requestId);
1310
+ pendingConns.delete(entry.requestId);
1311
+ askNonces.delete(entry.requestId);
1312
+ joiners.settle(entry.requestId, 'deny');
1313
+ emit({ type: 'join-settled', requestId: entry.requestId, result: 'deny' });
1314
+ conn?.close();
1315
+ if (entry.local)
1316
+ void gossipDecision(entry.requestId, 'deny', undefined, selfId());
1317
+ }
1169
1318
  async function gossipPending(entry, publicKey) {
1170
1319
  const frame = {
1171
1320
  protocol: NET_PROTOCOL,
@@ -1737,6 +1886,11 @@ export function createNamzuNetwork(options) {
1737
1886
  for (const c of pendingConns.values())
1738
1887
  c.close();
1739
1888
  pendingConns.clear();
1889
+ for (const cancel of orphanTimers.values())
1890
+ cancel();
1891
+ orphanTimers.clear();
1892
+ // A terminal that stops lets go of its waiting ask without withdrawing it, as when its process ends.
1893
+ joinClient?.close();
1740
1894
  await discovery.close().catch(() => undefined);
1741
1895
  await Promise.all(netListeners.splice(0).map((l) => l.close()));
1742
1896
  }