| 915 | }; |
| 916 | |
| 917 | const waitForStreamStarted = async (timeoutMs?: number): Promise<void> => { |
| 918 | let timer: ReturnType<typeof setTimeout> | null = null; |
| 919 | const streamFailedOrEndedBeforeStart = completionPromise.then(() => { |
| 920 | throw new Error("Goal continuation stream ended before it started"); |
| 921 | }); |
| 922 | const waits: Array<Promise<void>> = [streamStartedPromise, streamFailedOrEndedBeforeStart]; |
| 923 | if (timeoutMs != null) { |
| 924 | waits.push( |
| 925 | new Promise<never>((_, reject) => { |
| 926 | timer = setTimeout(() => { |
| 927 | reject(new Error("Timed out waiting for goal continuation stream to start")); |
| 928 | }, timeoutMs); |
| 929 | timer.unref?.(); |
| 930 | }) |
| 931 | ); |
| 932 | } |
| 933 | try { |
| 934 | await Promise.race(waits); |
| 935 | } finally { |
| 936 | if (timer != null) { |
| 937 | clearTimeout(timer); |
| 938 | } |
| 939 | } |
| 940 | }; |
| 941 | |
| 942 | const resetCompletionHandlers = () => { |
| 943 | resolveCompletion = null; |